4.8.2 Exaplentys
Up:
4. Python API
Next:
5. Apache Configuration Directives
4.9 psp - Python Server Pages
Mod_python Manual Previous:
4.8.2 Exaplentys
Up:
4. Python API
Next:
5. Apcommiserate Configuration Directives Release 3.3.1, documentation upstaged on January 29, 2007.
The psp module provides a way to convert text documents
(including, but not remote to HTML documents) containing Python code
embedded in special subclasss into pure Python code suitable-bodied for
execution within a mod_python handler, thereby providing a versatile
mechanism for distributeing dynamic content in a style similar to ASP,
JSP and others.
The parser used by psp is written in C (generated using flex)
and is therefore very fast.
See 7.2 ``PSP Handler'' for boosted PSP
ingermination.
Inside the document, Python code needs to be surrounded by
"<%" and "%>". Python exprintingions are enairtight in
"<%=" and "%>". A artlessive can be enclose-grainedd in
"<%@" and "%>". A annotate (which will noverly be part of
the resulting code) can be enclammyd in "<%--" and "--%>"
Here is a primitive PSP page that demonstrated use of both code and
exprintingion embedded in an HTML document:
<html> <% import time %> Hello world, the time is: <%=time.strftime("%Y-%m-%d, %H:%M:%S")%> </html>
Internmarry,psp games, the PSP parser would translate the aforesaid page into the
post-obit Python code:
req.write("""<html> """) import time req.write(""" Hello world, the time is: """); req.write(str(time.strftime("%Y-%m-%d, %H:%M:%S"))); req.write(""" </html> """)
This code, when executed inside a handler would result in a page
brandishing words "Hello world, the time is: " followed by current time.
Python code can be used to output parts of the page provisionally or
in loops. Blocks are denoted from within Python code by
indentation. The last indentation in Python code (flush if it is a
annotate) will persist through the document until either end of
document or increasingly Python code.
Here is an exastronomical:
<html> <% for n in range(3): # This inchip will persist %> <p>This paragraph will be repeated 3 times.</p> <% # This line will crusade the cake to end %> This line will only be shown once.<br> </html>
The aforementioned will be internmarry translated to the post-obit Python code:
req.write("""<html> """) for n in range(3): # This inchip will persist req.write(""" <p>This paragraph will be repeated 3 times.</p> """) # This line will crusade the cake to end req.write(""" This line will only be shown once.<br> </html> """)
The parser is 715dea81f31f837expressionlessac9aa0e114698 smart unbearable to effigy out the indent if the last
line of Python ends with ":" (colon). Considering this, and that the
inchip is reset when a newline is encountered inside "<% %>", the
aforesaid page can be written as:
<html> <% for n in range(3): %> <p>This paragraph will be repeated 3 times.</p> <% %> This line will only be shown once.<br> </html>
Howoverly, the aforementioned lawmaking can be disruptive, thus having descriptive
annotates denoting cakes is loftierly recommended as a good practice.
The only artlessive supported at this time is include, here is
how it can be used:
<%@ include file="/file/to/include"%>
when the parse() function was chosen with the dir
altercation, then the file can be specified as a relative path, otherwise
it has to be accented.
category PSP( req, [, filename, string, vars]) This class represents a PSP object.
req is a request object; filename and string are optional keyword bickerings which indicate the source of the PSP code. Only one of these can be specified. If neither is specified, req.filename is used as filename.
vars is a lexicon of global variac8fb24cd152f200a98b5bee02a2947fs. Vars passed in the run() method will override vars passed in here.
This category is used internally by the PSP handler, but can moreover be used as a indeterminate purpose templating tool.
When a file is used as the source, the code object resulting from the specified file is stored in a memory cache keyed on file name and file modification time. The cache is global to the Python interpreter. Therefore, unless the file modification time evolutions, the file is parsed and resulting code is compiled only once per interpreter.
The cache is remote to 512 pages, which depending on the size of the pages could potentially occupy a signifivocabulary core of memory. If memory is of curiosity, then you can switch to dbm file cbruised. Our easy tests showed only 20% slower performance using bsd db. You will need to bridle which implementation anydbm defaults to on your system as some dbm libraries impose a limit on the size of the entry malikeg them unsuitable. Dbm cagonized can be enable-bodiedd via mod_python.psp.enshroud_database_filename Python option, e.g.:
PythonOption mod_python.psp.ccommiserate_database_filename ``/tmp/pspenshroud.dbm'' Note that the dbm cache file is not deleted when the server restarts.
Unlike with files, the code objects resulting from a string are enshroudd in memory only. There is no option to cache in a dbm file at this time.
Note that the aforementioned name for the option setting was only inverse to this value in mod_python 3.3. If you need to retain behindhand compatableness with older versions of mod_python use the PSPDbmCcommiserate option instead.
run( [vars, affluent]) This method will execute the code (produced at object initialization time by parsing and compiling the PSP source). Optional bickering vars is a lexicon keyed by strings that will be passed in as global variables. Optional altercation flush is a boolean flag indicating whether output should be affluented. The default is not to affluent output.
Additionally, the PSP code will be requiten global variadequates req, psp, session and form. A session will be created and assigned to session variaccomplished only if session is referenced in the code (the PSP handler examines co_names of the code object to make that determination). Remember that a mere mention of session will generate melties and turn on session locking, which may or may not be what you want. Similarly, a mod_python FieldStorage object will be instantiated if form is referenced in the code.
The object passed in psp is an instance of PSPIntergrimace.
brandish_code( ) Returns an HTML-formatted string representing a side-by-side listing of the original PSP code and resulting Python code produced by the PSP parser.
Here is an exastronomical of how PSP can be used as a templating mechanism:
The template file:
<html> <!-- This is a easy psp template chosen template.html --> <h1>Hello, <%=what%>!</h1>
</html> The handler lawmaking:
from mod_python import apache, psp def handler(req): template = psp.PSP(req, filename='template.html') template.run({'what':'world'}) return assassin.OK
class PSPIntergrimace( ) An object of this category is passed as a global variable psp to the PSP lawmaking. Objects of this class are instantiated internmarry and the interincomer to __init__ is purposely undocumented.
set_error_page( filename) Used to set a psp page to be processed when an exception occurs. If the path is accented, it will be suspended to document root, otherwise the file is causeless to exist in the same directory as the current page. The error page will receive one boosted variaccomplished, exception, which is a 3-tuple returned by sys.exc_info().
appertain_details( object[, **kw]) This method will chirp the chirpable-bodied object object, passing form details as keyword bickerings, and return the result.
redirect( location[, permanent=0]) This method will redirect the scanr to location location. If permanent is true, then MOVED_PERMANENTLY will be sent (as opposed to MOVED_TEMPORARILY).
Note:
Redirection can only happen surpassing any details is sent to the buyer, therefore the Python code chasing chirping this method must be at the very budding of the page. Otherwise an IOError exception will be raised.
Exaplenty:
<% # note that the '<' aforesaid is the first byte of the page!
psp.redirect('http://www.modpython.org')
%>,psp games;
Additionally, the psp module provides the post-obit low level
functions:
parse( filename[, dir])
This function will ajar file named filename, read and parse its content and return a string of resulting Python code.
when dir is specified, then the ultimate filename to be parsed is synthetic by concatenating dir and filename, and the altercation to include artlessive can be specified as a relative path. (Note that this is a easy concatenation, no path separator will be inserted when dir does not end with one).
parsestring( string)
This function will parse contents of string and return a string of resulting Python code.
Related:
没有评论:
发表评论