Moving from PHP to Python. Is it Possible

2009-12-11 Thread 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...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Moving from PHP to Python. Is it Possible

2009-12-11 Thread Sancar Saran
On Friday 11 December 2009 05:11:12 pm zeph wrote:
> 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 =  ''
> output += 'My Page'
> output += ''
> output += 'Powers of two\n'
> for n in range(1,11):
>   output += ''+str(2**n)+''
> 
> output += ''
> 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

  
  <%
  for n in range(3):
  # This indent will persist
  %>
  This paragraph will be 
  repeated 3 times.
  <%
  # This line will cause the block to end
  %>
  This line will only be shown once.
  

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...

-- 
http://mail.python.org/mailman/listinfo/python-list


Problems with debugging Lists

2009-12-11 Thread Sancar Saran
Hello again.

I wrote small class for generating and accessing globalized Dictionary.

And of course I want to add some kind of debug ability to check what is 
inside...

In php we had print_r function to see entire array structure. After some 
search I found some equal module named pprint.

And some how this module wont work with mod_wsgi it was something about 
mod_wsgi portability standards.

After some research there where some thing about putting some variables in 
apache config to disable this.

And now I can see some dictionary structure in my apache log and I got some 
errors like
r += pprint.pprint(self.data)
TypeError: cannot concatenate 'str' and 'NoneType' objects

So is there any way to get dictionary structure in string format ?

Another question is. When I import a module from top is it available for later 
imported modules

# -*- coding: utf-8 -*-

import os, sys, cgi, pprint
import cgitb
cgitb.enable()


def application(environ, start_response):
sys.path.append(environ['DOCUMENT_ROOT']+"core")
#sys.path.append(environ['DOCUMENT_ROOT']+"util")
import registry, k5
#from print_r import print_r

# new registry

r = registry.Registry(environ)
r.set_entry('hede','hodo')

#response_headers = [('Content-type',k5.headers['content-type']+'; 
charset='+k5.headers['charset'])]
#start_response(kk5.headers['status'], response_headers)

# build the response body possibly using the environ dictionary
response_body = 'The request method was %s' % environ['REQUEST_METHOD']
response_body += ''
response_body += str(r.debug())

# HTTP response code and message
status = '200 OK'

# These are HTTP headers expected by the client.
# They must be wrapped as a list of tupled pairs:
# [(Header name, Header value)].
response_headers = [('Content-Type', 'text/plain'),
('Content-Length', str(len(response_body)))]

# Send them to the server using the supplied function
start_response(status, response_headers)

# Return the response body.
# Notice it is wrapped in a list although it could be any iterable.



return [response_body]



Following script was not working. I have to re import pprint from registry.

Is it normal or what is my problem :) 

Regards

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with debugging Lists

2009-12-12 Thread Sancar Saran
On Saturday 12 December 2009 04:52:26 am Gabriel Genellina wrote:
> En Fri, 11 Dec 2009 19:11:38 -0300, Sancar Saran 
> 
> escribió:
> > In php we had print_r function to see entire array structure. After some
> > search I found some equal module named pprint.
> >
> > And some how this module wont work with mod_wsgi it was something about
> > mod_wsgi portability standards.
> >
> > After some research there where some thing about putting some variables
> > in
> > apache config to disable this.
> >
> > And now I can see some dictionary structure in my apache log and I got
> > some
> > errors like
> > r += pprint.pprint(self.data)
> > TypeError: cannot concatenate 'str' and 'NoneType' objects
> 
> The pprint function in the pprint module (that is, pprint.pprint) *prints*
> its argument, and returns nothing -- or, better said, it returns None
> (same as print_r in PHP, without the return parameter set to true)
> 
> > So is there any way to get dictionary structure in string format ?
> 
> You don't need anything special for that. There are two built-in functions
> that convert any object to string: str and repr. str(x) provides a simple
> representation of x (whatever it is), and repr(x) provides a more
> technical view; when possible, eval(repr(x)) should return x.
> For debugging purposes, repr() is your friend.
> pprint.pformat is like the built-in repr(), but provides a better
> formatted representation, with indenting, a maximum width, etc.
> 
> > Another question is. When I import a module from top is it available for
> > later
> > imported modules
> 
> Each module contains its own, separate namespace. If you `import foo` in
> some module, the name `foo` becomes available to be used in that module --
> if you want to use `foo` in another module, you have to `import foo` in
> that other module too.
> 
> Don't worry; after the very first import (which involves locating the
> module, loading and compiling it if necesary, and writing the .pyc file)
> any subsequent imports of the same module just return a new reference to
> the existing, in-memory module object.
> 
Hello Gabriel,

Thanks for support.

repr works as you say and I had some complaints, it wont format the output. 
Finding some string in 100 key dictionary in formatted in single line bit 
problematic. Is it any way to format it ?

Also, very interesting things are happen.

def debug(self):

r = ''
r += repr(self.data)
r += ''

return r

following code works and does not work ever reload ?

One time work another reload wont work.  What I missing ?

And is possible to get this ? (I store the environ here)

r += repr(self.data['environ']['mod_wsgi.listener_port'])

or similar multi sub level elements ?

Regards...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Moving from PHP to Python. Is it Possible

2009-12-13 Thread Sancar Saran
On Monday 14 December 2009 02:10:16 am Diez B. Roggisch wrote:
> >> 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.
> 
> 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.

> > 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.
> 

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...

> Diez
> 

Regards

Sancar
-- 
http://mail.python.org/mailman/listinfo/python-list


Moving from PHP to Python. Part Two

2009-12-14 Thread Sancar Saran
Hello Again.

I hope, I don't bug too much.

First of all. I want to Thank to everyone who respond my messages. 

I was able to do some of my needs and stuck some others. 

So ? I need help again.

And here my progress..

Following was my globalized registry solution

# -*- coding: utf-8 -*-

class Registry:

data = {}

def __init__(self,environ):
self.data['env'] = environ
self.data['init'] = 'hede'

def set_entry(self,key,data):
self.data[key] = data

def get_entry(self,key):
return self.data[key]

def debug(self):

r = ''
r += repr(self.data)
r += ''

return r

I have some questions about this code.

First of all. when execute debug function. It wont work in every request.

# -*- coding: utf-8 -*-

import os, sys, cgi, pprint
import cgitb
cgitb.enable()


def application(environ, start_response):
sys.path.append(environ['DOCUMENT_ROOT']+"core")
import registry, k5
# new registry

r = registry.Registry(environ)
r.set_entry('hede','hodo')

#response_headers = [('Content-type',k5.headers['content-type']+'; 
charset='+k5.headers['charset'])]
#start_response(kk5.headers['status'], response_headers)

response_body = 'The request method was %s' % environ['REQUEST_METHOD']
response_body += ''
response_body += r.debug()


status = '200 OK'

response_headers = [('Content-Type', 'text/plain'),
('Content-Length', str(len(response_body)))]

start_response(status, response_headers)


return [response_body]

In first request I can see elements of my registry and second request it was 
shows noting. Then 3rd request I can see my registry elements again. next 
request was empty too. And it was go like that. I don't understand why ?

Second problem is. Formatting.

I need to see my dictionary elements like this.

   [k5req] => Array
(
[raw] => heede
[post] => Array
(
)

[proto] => http://
[base_url] => http://k5.int/?
[bend_url] => http://k5.int/?backend/
[ajax_url] => http://k5.int/?ajax/
[domain] => k5.int
[path] => Array
(
[0] => heede
)

[location] => frontend
[page] => heede
[dom_stat] => 1
)

Is there any available solution (like php's print_r) or have I write to my own 
?

And

If I understood correctly PSP template execution in mod_wsgi is impossible. So 
I have to look something like cheetah or similar marker based template 
systems.

And

If I understood correctly I have to import every module in sub imported 
module. 

And I want to make sure to my 5 different base module was available every other 
sub imported module. 

Is there any way to this from do and forget from start ?

Regards.
-- 
http://mail.python.org/mailman/listinfo/python-list