Moving from PHP to Python. Is it Possible

S

Sancar Saran

Greetings.

I'm 35 yrs old self learner and who do daily PHP coding for food more than a
decade.

After ten years of PHP coding I'm getting bored and give try for learning new
things.

After 3 days of crawling google, diving in python and cursing, now I can show
something on my linux/apache/mod_wsgi setup.

And i'm struck on something.

I had CMS design. It works with PHP very well. And I want to transfer my
design in Python.

My design depends on a Global Array. A huge array which store everything about
requested Web page for a final rendering.

In PHP accessing globals is easy. You may do direct access or use class
something like ZEND Registry.

I'm looking for similar facility in python world.

Also I have couple of questions.

1-) Can I create Global (read/write access anywhere from my code) Multi
dimensional, associative array (or hash) and store any kind of variable type.

2-) Is there any error trigger for mod_wsgi. When something go bad I god
Internal Server error. Looking for error log was't nice. Is there any way to
shows errors in the web page ?

3-) Any documents books sites about helping moving from php to python

4-) In php we had someting like
ob_start(); // start Output buffering
require('hede.php'); // include phtml similar to psp. mixed language and html
(to avoiding string replacement (or marker based) html templates)
$var = ob_get_clean(); // get rendered output and use anywhere

can find a similar abilities in Python ?

5-) is there any Python documentation based on examples. When I give up about
to finding php's $_REQUEST or $_SERVER equivalents in python some demo code in
Twisted docs are much helpful than any other words. Me and my kind already
have problem with English language. Example code much more helpful than full
academic description.

Thanks for support and patience for this old noob.

Regards...
 
Z

zeph

Hi Sancar,

1) PHP does some really nasty things in how it treats globals, and you
will have to break yourself of those sorts of habits -- Python offers
much cleaner alternatives, like grouping similar functionality into
modules which can be imported; the import functionality in python is
pretty flexible.
Python won't pack a ton of garbage into a giant, global
'dictionary' (what python calls associative arrays). There are
modules (bundled of code) which you can import to handle your needs.

2) Check out the traceback[1] module for retrieving the traceback info
for logging to a file, and cgitb[2] modules for printing the traceback
as HTML to your browser.

3) http://docs.python.org/ is a great place to start - it has a lot of
well written and generally thorough documentation with examples

4) It's better to collect all your eventual output into a string that
you print - there are examples at [3]. You can import from other
modules as needed (even conditionally), grow your string for output,
then finally print it like (this example was adapted from one found on
[3]):

output = '<html><head>'
output += '<title>My Page</title>'
output += '</head><body>'
output += '<h1>Powers of two</h1>\n<ol>'
for n in range(1,11):
output += '<li>'+str(2**n)+'</li>'

output += '</ol></body></html>'
print output


You can copy-paste this right into your Python interactive shell to
see the output. Note: += is inline string concatenation.


5) You can get form state from the cgi module[4] and FormStorage
object, and you can get server environment data from the os.environ[5]
dictionary;

Good luck and keep on learning! :)

- zeph


References:
1: http://docs.python.org/library/traceback.html
2: http://docs.python.org/library/cgitb.html
3: http://gnosis.cx/publish/programming/feature_5min_python.html
4: http://docs.python.org/library/cgi.html
5: http://docs.python.org/library/os.html#process-parameters
 
M

MRAB

zeph wrote:
[snip]
4) It's better to collect all your eventual output into a string that
you print - there are examples at [3]. You can import from other
modules as needed (even conditionally), grow your string for output,
then finally print it like (this example was adapted from one found on
[3]):

output = '<html><head>'
output += '<title>My Page</title>'
output += '</head><body>'
output += '<h1>Powers of two</h1>\n<ol>'
for n in range(1,11):
output += '<li>'+str(2**n)+'</li>'

output += '</ol></body></html>'
print output


You can copy-paste this right into your Python interactive shell to
see the output. Note: += is inline string concatenation.
It's better to put the strings into a list and then concatenate them in
one go:

output = ['<html><head>']
output.append('<title>My Page</title>')
output.append('</head><body>')
output.append('<h1>Powers of two</h1>\n<ol>')
for n in range(1, 11):
output.append('<li>%s</li>' % (2 ** n))

output.append('</ol></body></html>')
print ''.join(output)
 
S

Sancar Saran

Hi Sancar,

Hi zeph,

Thanks for reply. And here my needs about those 2 two programming technique.
1) PHP does some really nasty things in how it treats globals, and you
will have to break yourself of those sorts of habits -- Python offers
much cleaner alternatives, like grouping similar functionality into
modules which can be imported; the import functionality in python is
pretty flexible.
Python won't pack a ton of garbage into a giant, global
'dictionary' (what python calls associative arrays). There are
modules (bundled of code) which you can import to handle your needs.

PHP was doing tons of nasty things. 10 years after I'm starting to understand
some those and still not understand most programmers point of view to GLOBALS
are evil. Anyhow I'm self learner plus I got heavy English limitation or
probably I'm too narrow minded to see right thing.

In my usage GLOBALS are too much useful to discard it.

Anyway, I need to save my lots and lots of config variables in dictionary style
global accessible location.

Because.

In my design We got lots of plugins, and those plugins may show in multiple
times and multiple locations in a page.

Each plugin may have setup values to affect entire page output.

Because of this. I have to put those values in global location for future use.

Is it possible

If so ? how ? Is there any way to access directly or I have to wrote some kind
of class like acting Windows registry in global scope ?
2) Check out the traceback[1] module for retrieving the traceback info
for logging to a file, and cgitb[2] modules for printing the traceback
as HTML to your browser.

3) http://docs.python.org/ is a great place to start - it has a lot of
well written and generally thorough documentation with examples

4) It's better to collect all your eventual output into a string that
you print - there are examples at [3]. You can import from other
modules as needed (even conditionally), grow your string for output,
then finally print it like (this example was adapted from one found on
[3]):

output = '<html><head>'
output += '<title>My Page</title>'
output += '</head><body>'
output += '<h1>Powers of two</h1>\n<ol>'
for n in range(1,11):
output += '<li>'+str(2**n)+'</li>'

output += '</ol></body></html>'
print output


You can copy-paste this right into your Python interactive shell to
see the output. Note: += is inline string concatenation.

Yes, I'm aware about this usage. We got similar syntax in php. Problem is we
cannot give this kind of structure to our html designers.

In php world our fine solution was using phtml mixed files for templates. It has
two benefits.

1-) You dont need to string replace in templates (like in marker based
templates)
2-) with php opcode caches your template will stored in ram.

I believe second benefit was not available in python and my point of view
escaping string replacement was good for performance.

So My question is.
For example I had this kind of python file and we want to use this as plugin
template

<div class='foo'>
<%
for n in range(3):
# This indent will persist
%>
<p>This paragraph will be
repeated 3 times.</p>
<%
# This line will cause the block to end
%>
This line will only be shown once.<br>
</div>

on execution time, I want to import this template file, execute as python
script and store output in a GLOBAL dictionary for later usage.

Is it possible ?
5) You can get form state from the cgi module[4] and FormStorage
object, and you can get server environment data from the os.environ[5]
dictionary;

Good luck and keep on learning! :)

- zeph


References:
1: http://docs.python.org/library/traceback.html
2: http://docs.python.org/library/cgitb.html
3: http://gnosis.cx/publish/programming/feature_5min_python.html
4: http://docs.python.org/library/cgi.html
5: http://docs.python.org/library/os.html#process-parameters

And thanks for those links.

Regards...
 
I

imageguy

So My question is.
For example I had this kind of python file and we want to use this as plugin
template

  <div class='foo'>
  <%
  for n in range(3):
      # This indent will persist
  %>
  <p>This paragraph will be
  repeated 3 times.</p>
  <%
  # This line will cause the block to end
  %>
  This line will only be shown once.<br>
  </div>

on execution time, I want to import this template file, execute as python
script and store output in a GLOBAL dictionary for later usage.

Is it possible ?

Have you checked out one of the templating systems modules ?
I have used Cheetah quite successfully, but there a numerous other
options.
http://www.cheetahtemplate.org/
I think you will find that a template system (like Cheetah) will give
you the best results with the most maintainable structure.

g.
 
Z

zeph

output = ['<html><head>']
output.append('<title>My Page</title>')
output.append('</head><body>')
output.append('<h1>Powers of two</h1>\n<ol>')
for n in range(1, 11):
     output.append('<li>%s</li>' % (2 ** n))

output.append('</ol></body></html>')
print ''.join(output)

Agreed (I might join on '\n' though), I was just trying to introduce
as few new concepts as possible :)
 
D

Diez B. Roggisch

1) PHP does some really nasty things in how it treats globals, and you
PHP was doing tons of nasty things. 10 years after I'm starting to understand
some those and still not understand most programmers point of view to GLOBALS
are evil. Anyhow I'm self learner plus I got heavy English limitation or
probably I'm too narrow minded to see right thing.

In my usage GLOBALS are too much useful to discard it.

The problem with global variables is their scope. If you have a piece of
code, the important thing to know is what influences it's behavior when
being executed. Functional programs take this to the extreme and usually
don't allow any global or otherwise shared state, so if you have a
function that reads

a = f(x)

and you invoke it twice with the same value for x, you get the same result.

But sometimes, you need state that is preserved over time. Object
orientied design encapsulates this in objects. Each function (method) in
a car-object shares the cars state. But *not* the state of *all* cars,
which global variables would.

Now when reading code, you have to juggle with all the state that
influences it. The broader the scope (and global is the biggest one you
can get) the harder it is to understand. And believe me, the longer a
system exists and the older the code is you look at, the harder it is to
understand what's happening.
Anyway, I need to save my lots and lots of config variables in dictionary style
global accessible location.

Because.

In my design We got lots of plugins, and those plugins may show in multiple
times and multiple locations in a page.

Each plugin may have setup values to affect entire page output.

Because of this. I have to put those values in global location for future use.

No, you don't. Because of this, you can e.g. use ToscaWidgets as a
framework for creating widgets that encapsulate code, HTML, javascript
and CSS. And no global state is shared.

Also, I think you should *really* look into one of the available
web-frameworks such as Django or Turbogears to learn how to write
webapps in python - instead of shoehorning your tried & trusted PHP
techniques that don't translate well.

Diez
 
S

Sancar Saran

The problem with global variables is their scope. If you have a piece of
code, the important thing to know is what influences it's behavior when
being executed. Functional programs take this to the extreme and usually
don't allow any global or otherwise shared state, so if you have a
function that reads

a = f(x)

and you invoke it twice with the same value for x, you get the same result.

But sometimes, you need state that is preserved over time. Object
orientied design encapsulates this in objects. Each function (method) in
a car-object shares the cars state. But *not* the state of *all* cars,
which global variables would.

Now when reading code, you have to juggle with all the state that
influences it. The broader the scope (and global is the biggest one you
can get) the harder it is to understand. And believe me, the longer a
system exists and the older the code is you look at, the harder it is to
understand what's happening.

Yes, I understood. And I'm using large Global dictionary (or Array) to
replicate those objects. State of the thing will store in there. But it
wasn't an object. Just Assocative array. Staying in global space,

Because.

In web programming we do not store anything except session. Every object we
created was destroyed after execution. Using objects in this conditions was
non sense to me. (of course I'm not very capable programmer probably it was my
fault to take full advantage of oo programming)

Plus. In php we can store arrays in files very easy. Combining this with any
PHP opcode cache can save those arrays in memory. So we got damn cheap state
saver.

Of course things may differ in python.

Anyhow I generate a Registry class to replicate global dictionary. Probably it
much better than my PHP Direct $GLOBAL usage.

So I have no problem with that.
No, you don't. Because of this, you can e.g. use ToscaWidgets as a
framework for creating widgets that encapsulate code, HTML, javascript
and CSS. And no global state is shared.

Also, I think you should *really* look into one of the available
web-frameworks such as Django or Turbogears to learn how to write
webapps in python - instead of shoehorning your tried & trusted PHP
techniques that don't translate well.

Yes I download the django trying to learn but it was much different.

My problem is not writing web apps. I'm doing well.

My design was very good and I'm very proud its abilities.

My problem is with PHP syntax and performance.

I'm just trying to replicate my recepies in python...

Regards

Sancar
 
N

Nobody

1-) Can I create Global (read/write access anywhere from my code) Multi
dimensional, associative array (or hash) and store any kind of variable type.

Global, no; at least not in the sense of e.g. C. Python doesn't have a
global namespace; the highest level is a module.

Read/write from anywhere in your code, yes. You just need to decide which
module to put the variable in, then import that module (or even the
specific variable) from the other modules.

E.g. you can have a file state.py containing nothing but:

state = {}

Other modules can then use:

from state import state

to make the variable visible.
 
L

Lie Ryan

Yes, I understood. And I'm using large Global dictionary (or Array) to
replicate those objects. State of the thing will store in there. But it
wasn't an object. Just Assocative array. Staying in global space,

In python, objects is just syntax sugar for dict/associative array. In
even lower languages (like C++), object is just syntax sugar for a
malloc-ated block of memory. Object-oriented is designed to eliminate
the need for having a God Data Structure such as Global Associative
Array that stores practically everything.
Because.

In web programming we do not store anything except session. Every object we
created was destroyed after execution. Using objects in this conditions was
non sense to me. (of course I'm not very capable programmer probably it was my
fault to take full advantage of oo programming)

Why is it nonsense? You can create an object that stores the session id,
and the object's methods would query the database without you have to
explicitly mention the session id each time. That's cheap and is very
neat in organizational standpoint.
Plus. In php we can store arrays in files very easy. Combining this with any
PHP opcode cache can save those arrays in memory. So we got damn cheap state
saver.

Of course things may differ in python.

Things differ, but not by that much.
 
B

Bruno Desthuilliers

zeph a écrit :
(snip)
4) It's better to collect all your eventual output into a string that
you print

Yuck ! Definitly one of the worst advises you could give.

<OP>
By all mean, *DONT* do that. Use a templating system instead.
</OP>
 
D

Diez B. Roggisch

Yes, I understood. And I'm using large Global dictionary (or Array) to
replicate those objects. State of the thing will store in there. But it
wasn't an object. Just Assocative array. Staying in global space,

Because.

In web programming we do not store anything except session. Every object we
created was destroyed after execution. Using objects in this conditions was
non sense to me. (of course I'm not very capable programmer probably it was my
fault to take full advantage of oo programming)

Plus. In php we can store arrays in files very easy. Combining this with any
PHP opcode cache can save those arrays in memory. So we got damn cheap state
saver.

This is possible in python, too. But "damn cheap"... well, the cheapest
solution in terms of speed is to just keep the things in memory. Which
you can't do with PHP, as everything lives just one request, but in
Python with certain app-servers, you can do this.
Of course things may differ in python.

Anyhow I generate a Registry class to replicate global dictionary. Probably it
much better than my PHP Direct $GLOBAL usage.

So I have no problem with that.


Yes I download the django trying to learn but it was much different.

My problem is not writing web apps. I'm doing well.

My design was very good and I'm very proud its abilities.

My problem is with PHP syntax and performance.

I'm just trying to replicate my recepies in python...

Then the result will be a twice as horrible program in python. Because
you work against the language.

In the end of course, what matters is what works for you.

Diez
 
B

Bruno Desthuilliers

Sancar Saran a écrit :
(snip)
My problem is with PHP syntax and performance.
I'm just trying to replicate my recepies in python...

Python is not PHP, and trying to write PHP in Python won't buy you much
except pain and frustration.
 
R

r0g

Bruno said:
Sancar Saran a écrit :
(snip)

Python is not PHP, and trying to write PHP in Python won't buy you much
except pain and frustration.


I think people are being a little harsh here. Replicating exactly what
PHP code does on a micro level i.e. line by line is probably a bad idea
but for all we know a lot of the macro level stuff might be fine, or
mostly fine i.e. structures, algorithms, classes and functions etc.

If this is the case rewriting the same bits in Python might not be
painful and frustrating, indeed seeing how much terser those things can
be written in Python would probably be quite satisfying.

Of course, some PHP is never going to port well but you can't say for
sure without seeing it.

Roger.
 
B

Bruno Desthuilliers

r0g a écrit :
I think people are being a little harsh here. Replicating exactly what
PHP code does on a micro level i.e. line by line is probably a bad idea
but for all we know a lot of the macro level stuff might be fine, or
mostly fine i.e. structures, algorithms, classes and functions etc.

I was talking about trying to replicate PHP's execution model and idioms
in Python - the "framework" part -, not about application specific
algos, data structures etc.
 
M

mdipierro

About you point 3). You may want to look into:

http://www.web2py.com/php

It translates a PHP page into a web2py template. It is crude and
primitive and fails in some cases. Moreover a literal translation is
not what you really want since you want to follow a more MVC design.
Moreover it will not always maps PHP functions into valid Python/
web2py ones. Yet it may be a useful as a learning tool. I made it to
convert Drupal templates into web2py layouts.

Massimo
 
B

Bruno Desthuilliers

AppRe Godeck a écrit :
Try web2py I think you will surprise yourself with its simplicity and
speed :)

I don't like what I've seen from web2py, thanks. Also and FWIW, I don't
see how it relates to the OP ?
 
A

Aahz

zeph a écrit :

Yuck ! Definitly one of the worst advises you could give.

<OP>
By all mean, *DONT* do that. Use a templating system instead.
</OP>

Because I know Zeph, I know that you two aren't actually disagreeing. ;-)
Templates are one good way to follow Zeph's advice, but particularly for
small projects they may be overkill.
 
R

Robert Kern

Because I know Zeph, I know that you two aren't actually disagreeing. ;-)
Templates are one good way to follow Zeph's advice, but particularly for
small projects they may be overkill.

I find that Ian Bicking's Tempita is small enough (in terms of code and language
design) to not be overkill for even small tasks.

http://pythonpaste.org/tempita/

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
A

Aaron Watters

Sancar wants to move from PHP to Python.

The following a shameless plug for WHIFF: http://whiff.sourceforge.net
-- I wrote it partially because I wanted PHP-like features using
Python, but better ;).

Greetings.
....After 3 days of crawling google, diving in python and cursing, now  I can show
something on my linux/apache/mod_wsgi setup.

It's too bad you didn't find the WHIFF quickstart first :).
http://whiffdoc.appspot.com/docs/W0500.quickstart
And i'm struck on something....

My design depends on a Global Array. A huge array which store everything about
requested Web page for a final rendering.
In PHP accessing globals is easy. You may do direct access or use class
something like ZEND Registry....
1-) Can I create Global (read/write access anywhere from my code) Multi
dimensional, associative array (or hash) and store any kind of variable type.

There are a number of ways to do things like this in WHIFF
-- one way is to use the WSGI environment to store your
"globals" as illustrated in the Mako tutorial:
http://whiffdoc.appspot.com/docs/W1100_1075.MakoGrading
2-) Is there any error trigger for mod_wsgi. When something go bad I god
Internal Server error. Looking for error log was't nice. Is there any way to
shows errors in the web page ?

Configure your application to display tracebacks on errors.
I need to explicitly add this to the documentation, but here
is an example used by the WHIFF documentation app config:

59 whiffDocumentation = resolver.moduleRootApplication("/", docroot,
60 #exception_middleware=None,
61 environment=environment,
62 exception_middleware=displayTraceback.__middleware__,
63 on_not_found=None, # show traceback (could comment)
64 auto_reload=False,
65 )

lines 62 and 63 from
http://aaron.oirt.rutgers.edu/cgi-bin/whiffRepo.cgi/file/4b2cea3d92fc/doc/servedocs.py
3-) Any documents books sites about helping moving from php to python

http://whiffdoc.appspot.com/ (doesn't explicitly mention PHP).
4-) In php we had something like
ob_start(); // start Output buffering
require('hede.php'); // include phtml similar to psp. mixed language and html
(to avoiding string replacement (or marker based) html templates)
$var = ob_get_clean(); // get rendered output and use anywhere
can find a similar abilities in Python ?

Of course:

See the quoteHtml implementation, for example
http://aaron.oirt.rutgers.edu/cgi-bin/whiffRepo.cgi/file/4b2cea3d92fc/whiff/middleware/quoteHtml.py
5-) is there any Python documentation based on examples. When I give up about
to finding  php's $_REQUEST or $_SERVER equivalents in python some demo code in
Twisted docs are much helpful than any other words. Me and my kind already
have  problem with English language. Example code much more helpful than full
academic description.

http://whiffdoc.appspot.com (again) there are lots and lots of
examples.

I hope you like it and have a happy new year! -- Aaron Watters

===
my resolution last year
was not to make any resolutions this year.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top