PHP style inline tags for Python?
I'm just starting out learning python (for webapp usage) but I'm confused as to the best way for using it with html files and dynamic data.
I know php has the <?php ?>
tags which are great - does python have something li开发者_如何学Pythonke this or equivalent, if not how should I be doing it?
PHP inline tags actually tend to encourage a bad practice - namely, mixing your control logic (PHP code) with your templates (html). Most Python frameworks tend to steer away from such a mix and instead encourage separation between the two - typically using some kind of templating system.
Many frameworks have their own template systems (for instance, the Django templating system is fairly popular). Others don't and let you choose a separate template engine (like Cheetah).
There are a few php style python options out there. Mod_python used to ship with one, and spyce had an alternate implementation, but that modality is out of favor with pythonistas. Instead, use a templating language. Genshi and jinja2 are both popular, but there are lots to choose from.
Since you are new to web programming with python, you would probably be best off choosing an entire framework get started. Django, turbogears, and cherrypy are a few to check out. These frameworks will all include all the tools you need to make a modern website, including a templating language.
Yes, Python does have a roughly equivalent feature: Python Server Pages (a.k.a. psp
) using mod_python
. It enables you to do things like:
<html>
<% import time %>
Hello world, the time is: <%=time.strftime("%Y-%m-%d, %H:%M:%S")%>
</html>
However, in general this practice is not considered Pythonic. I would start with a lightweight Python web framework. web2py
is a nice one to use when you are starting out. bottle
, flask
& cherrypy
are very easy to work with out of the box. Django
, TurboGears
& others are are more complex, but provide more features.
As Tim said, you can use Python Server Pages (psp
) to get a PHP style inline tags working for mod_python
. You have to add psp
handler to Apache configuration:
<Directory /var/www/html>
AddHandler mod_python .psp
PythonHandler mod_python.psp
PythonDebug On
</Directory>
Then save this as test.psp
and enjoy. :-)
<html>
<% import time %>
Hello world, the time is: <%=time.strftime("%Y-%m-%d, %H:%M:%S")%>
</html>
But unfortunately, mod_python
is retired and you have to use mod_wsgi
and unfortunately, "there is no port of mod_python PSP for mod_wsgi".
精彩评论