Moving from PHP to Python. Is it Possible

Tino Wildenhain tino at wildenhain.de
Sat Dec 12 15:59:28 EST 2009


MRAB schrieb:
> 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)

Actually I'd use a proper template engine in any case. The above
construction of mixing code and representation (or rather code with
code and data for another interpreter - the users browser) is not only
unlucky, it is almost everytime very dangerous.

Keep in mind if you are using a user supplied string, like coming from
a form entry and just include it as above literally into your HTML, you
have created a way of cross site scripting, a very common attack.

To prevent that, you should always propery quote strings for the context
where they are used. Template engines such as Zope Page Templates (also
usable stand allone) are doing this for you.

Regards
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3254 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20091212/bb7d24c6/attachment-0001.bin>


More information about the Python-list mailing list