Gashero mod_python development experience
· Default release processor objects
The publishing processor can point to the index. py module by default when the module name is not explicitly specified in the URI. In index. find the corresponding method in The py module, but if there is no directory name in the URI, find the corresponding index. def index (req [,...]) in The py Module.
In addition, the module name used by the release processor can be used without the extension.
If the specified URL contains only a path but not a specific module, the index. py module in this path is accessed by default. Similarly, if the module name is specified but no method is specified, the index method is accessed by default. This is very useful. We recommend that you retain the index. py module for each directory and the index () method for each module.
Traditional default objects such as index.html and index.pyare not automatically linked to that page. The. htaccess file does not allow you to specify the directoryindex flag to specify the default access object.
· Template Publishing
Add the key name variable of the python dictionary to the custom webpage template to be replaced. The replacement string rules are as follows:
It starts with a percent sign, and is the dictionary key name in parentheses, followed by a type sign. Replace the key-name pair in the dictionary with the string value as follows:
% (Name) S
In this way, the corresponding replacement web page is generated, and then the corresponding dictionary is generated in the processor to replace. Read the corresponding file first, then read the file as a string, replace the variable, and then return the page to the client.
The location of the template file is based on the Apache installation directory, for example, a complete processor example:
Def get (req ):
FF = open ("htdocs/ns/index. pyml", "R ")
Allfile = ff. Read (65536)
Dicts = {'name': 'gashero ',}
Return (allfile % dicts)
# By gashero
The variables to be replaced in each template must be replaced. Otherwise, an internal server error occurs and the log is a keyerror thrown by the release processor. If the remaining key-value pairs in the dictionary are not used in the template, no errors will occur.
The following is a mature template function used in the commontest project.
Def get_page (path, filename, vardict ):
"Get a dynamic page from a file
And will fix the VaR WITH dict, then return page string
And status """
If (type (PATH )! = Types. stringtype) | (type (filename )! = Types. stringtype) | (type (vardict )! = Types. dicttype ):
Apache. log_error ('[pytemp]: ARGs type error ')
Raise Apache. server_return, Apache. http_internal_server_error
Fullpath = OS. Path. Join (path, filename)
Try:
File = open (fullpath, 'R ')
Filestr = file. Read ()
File. Close ()
Except t:
Apache. log_error ("[pytemp]: Can't open & Read File ")
Raise Apache. server_return, Apache. http_not_found
Try: # By gashero
Filestr = filestr % vardict
Failed t keyerror, keyname:
Apache. log_error ('[pytemp]: vardict not match key =' + keyname)
Raise Apache. server_return, Apache. http_internal_server_error
Return filestr
The first parameter path is the path of the template file, the second parameter filename is the template file name, and the third parameter is the replacement dictionary used for variable replacement in the template. In this way, each time you call the get_page () function, you can return the corresponding HTML file string of the replaced template. When the keys in the template do not exist in the dictionary, the corresponding processing is also done in this template function, and an internal server error page will be returned to the user. All kinds of errors that may occur when the template file is opened are processed accordingly, and Apache server logs are written for record.
This template function separates path and filename to easily support template files in relative paths. The function used to obtain the current specified path in the URL is as follows. It can be used to fill the path, that is, to use the template file in the current path specified in the URL.
Def get_cwd (req ):
If Req. _ class _. _ name __! = 'Mp _ request ':
Return none # A invoke error
Path, FN = OS. Path. Split (req. filename)
Return Path
In this way, the corresponding import template is added to form a dedicated template module, which is used to provide the template function in mod_python. The following is a call example:
Retstr=pytemp.get_page(pytemp.get_cwd(req.pdf, 'queslist.html ', vardict)
Return retstr
The code is truncated from the queslist. py module. Before calling this statement, you must enter all the variables needed in the template into the vardict dictionary.
· Release useless processor Parameters
When users in the URI submit unused parameters using the release processor, for example, the parameters of the corresponding processing function do not have the corresponding parameters, the submitted fields are directly discarded, if you really need to handle this unreasonable submission field, you can use the dictionary to receive it. When writing such a processor function, you must follow the form below:
Def myhandler (req, ** kargs ):
In this way, all input parameters can be obtained through kargs. However, in general, each processor function exists to process specific events. Therefore, the general processor function is in the following form:
Def myhandler (req, AAA = ***, BBB = *** [,...]):
In this way, you can only receive specific parameters, discard unnecessary troubles, and there are also default values available when the client does not submit some parameters again.
If you really need to view all input parameters, you can use a dictionary to receive undefined submission fields, and use STR to convert the dictionary to a string for display, facilitating debugging.
Multiple Fields submitted by Uri are separated by question marks and separated by semicolons.
· Publish static pages through mod_python
By default, setting sethandler mod_python in. htaccess cannot publish HTML pages. If necessary, add the following as follows:
Addhandler mod_python. html
However, the supported types are limited to. html, excluding other types. After this setting, the content of a complete. htaccess file is as follows:
Sethandler mod_python
Addhandler mod_python. py
Addhandler mod_python. html
Pythonhandler mod_python.publisher
Pythondebug on
This configuration allows you to add a. py extension when calling a module in a URL. Supports displaying static html files and debugging.
Note that this experience applies only to mod_python3.2.5b and is no longer valid when you upgrade to mod_python3.2.8. However, when mod_python3.2.8 is used, the publishing processor publisher cannot directly display HTML static files. You have to use the following configuration to set the publisher operation, and use the template system and static html files in other folders for display:
Sethandler mod_python
Pythonhandler mod_python.publisher
Pythondebug on
However, the preceding statement cannot be separated and written as follows:
Sethandler mod_python.publisher
Pythondebug on
The effect is different. In this case, the processor does not run and the source code of python is directly returned.
· Internal verification of released processor objects
The release processor supports three members in the object to Verify access permissions. The three members are _ auth _, _ Access _, and _ auth_realm __. The three members provide logon verification, user name verification, and verification prompts respectively. Note: Although mod_python allows _ auth _ to be set as a dictionary, the user name can be verified directly, but the actual test shows that all input is allowed. Therefore, real verification requires the use of _ auth _ as a function to call.
I prefer to use _ auth _ as a function, so as to avoid bypassing verification when some modules are not loaded. However, if you need to call the function of the same module in the internal function _ auth _, it is invalid to introduce the function name by global alone. You also need to re-import the verification function module name in the _ auth _ function. We recommend that you do a better job of this verification function and directly add it to the database access module.
In one of my examples, pay attention to the authentication method and import:
# Inauth. py
Def index (req ):
Def _ auth _ (req, username, password ):
Import inauth # re-import by gashero
Return inauth. myauth (req, username, password)
_ Auth_realm __= "Logon Verification"
Return "auth OK! "
Def myauth (req, username, password ):
If username = 'aaa' and Password = 'aaa ':
Return true
Else:
Return false
Of course, note that the parameter of the _ auth _ function must be like this and cannot be changed.
· An example of connecting to the MySQL database for user verification
Note that the SQL injection vulnerability may exist in a simple example:
Import mysqldb
Con = mysqldb. Connect (host = 'localhost', Port = 3306 ,/
User = '***', passwd = '***', DB = '***')
Cur = con. cursor ()
SQL = "select username, name from login where/
Username = '% s' and Password =' % s ';"
Presql = SQL % (username, password)
Rtw.cur.exe cute (presql)
Results = cur. fetchall ()
Con. Close ()
If RT = 1:
Print 'auth OK! '
Else:
# By gashero
Print 'auth failed! '
· Mod_python command line parameters in Web Applications
Python command line parameters are obtained through SYS. argv. In mod_python web applications, only one command line parameter is 'mod _ python', and no other parameters are provided.
· An example of session Programming
The default session in mod_python is very interesting. Different sessions exist for different browser processes at the same time and do not interfere with each other. However, the sessions implemented for different windows of the same browser process are the same. The default session timeout time is half an hour. The session operation method is the same as the dictionary, which is very convenient.
From mod_python import session
Def index (req, encoding = ''):
Sess = session. Session (req)
# Sess. set_timeout (90)
If region = 'delete ':
Sess. invalidate () # delete a session
Return 'session deleted! '
If sess. is_new ():
Sess ['name'] = 'gashero'
Sess. Save () # Save it
Return "new session % s" % (sess. ID ())
Else:
Retstr = "name = % s/n" % sess ['name']
Retstr + = "sessionid = % s" % sess. ID ()
Return retstr
· About the _ name _ attribute of the module in mod_python running
This attribute does not change to a common module name at runtime, but to a complete path with a module name. Do not rely on it.
· Pythonoption flag
You can specify the pythonoption flag in. htaccess or httpd. conf. The syntax is as follows:
Pythonoption name value
In this way, you can add a key-value pair to an existing httpd table object. You can use Req. get_options () to obtain the reference of this table and extract these settings. You can add options to your program. Especially in. htaccess, It is very convenient to read it immediately as long as the settings are updated. However, because the req object must be used to obtain this table object, it is difficult to use it for Initialization Configuration of the program. In addition, because the req object must be used, and the lifecycle of the req object is a request, even if the mp_table object obtained by req is first stored, the object will be deleted after the request ends. In this way, if mod_python does not use the cache for the configuration file, it takes a lot of time to read the file each time. If the cache is used, the configuration cannot be updated in real time. By gashero
In short, it was not easy to use. Later I wrote a module dedicated to reading the configuration file in the M $ ini format and saved the configuration to the dictionary.
· About mod_python.session
Memorysession is implemented by default on Win32, so the session disappears after the server is restarted. In addition, it is recommended to specify the timeout value when creating a session. It can be set to a little longer. The default value is 1800, in seconds. If the timeout value is not set, the newly set session is occasionally lost. The specific cause has not been identified yet, and may also be related to my browser. However, we recommend that you set it first.
In addition, to prevent errors so far, it is best to check whether the session is a newly created session after the session is created. If not, load () the previous data. The strange errors mentioned above are finally solved in this way. We recommend that you write the following code segment for each session:
From mod_python import session
Sess = session. Session (req, timeout = 3600) #1 hour
If not sess. is_new ():
Sess. Load ()
# Other operation...
In addition, because HTTP is a stateless protocol, it only relies on session and cookie to maintain the interaction status, so occasionally some disordered order damages the server status, for example, a function can be operated only after an object exists in the session, but the client prestores the URL of the corresponding page of the function and directly accesses this page, cause server errors. Therefore, we recommend that you read an object in the session as follows to prevent unexpected errors:
If sess. has_key ('key _ name '):
OBJ = sess ('key _ name ')
Else:
Apache. log_error ('[*] [*]...')
Raise Apache. server_return, Apache. http_internal_server_error
In addition, you must use the sess. Save () method to submit the changes to the corresponding storage media after each operation session ends.
· Release method parameters
We recommend that you use the following method to declare the release method:
Def func (req, A = none [, B = none...])
This can be noticed when the client submits insufficient data. If the client contains a field with the corresponding name and this field is not assigned a value, an empty string ''is returned '', if the page is maliciously modified, the corresponding field is none at the time of submission. When the page is maliciously modified, logs can be used to output something to record the client's attack behavior.
· Return value of the release method
The Return Value of the release method is a string. Although other types can be returned and corresponding string representation can be obtained using the STR () function internally, it is recommended to use a string to return the result, you can easily control the returned content. A recommended method is to define the string variables to be returned at the beginning of the method, such:
Retstr = STR ()
In this way, the variable retstr is initialized to '', and you can use retstr + = * for multiple string operations.
· Import Statement location
By convention, the Import Statement is placed in the module File Header, "#-*-coding: GBK-*-" and other encoding declarations, but for some methods with special scopes, for example, the internal authentication method of the method cannot share the import settings. However, there is also a solution, that is, the import method can be used internally in the same format.
· APACHE-HTTPd log output
The simplest log output method is as follows:
From mod_python import Apache
Apache. log_error (STR)
However, we recommend that you do not use Chinese characters in the error output. Otherwise, logs cannot be read due to confusion of various codes.
Because web development can only output through pages and the Interaction feature of python is exhausted, logs can only be used as another better output mode for debugging convenience. The recommended output string format is as follows:
'[Module] [func] STR'
In this way, the corresponding modules and functions can be pointed out, which is convenient for debugging. However, the most important thing is to form a certain log style, otherwise it will be hard to understand in the future.
Generally, serious errors occur when logs are written, or attacks are detected. Therefore, in most cases, an error statement is thrown after the log is output, such as an internal server error:
Raise Apache. server_return, Apache. http_internal_server_error
· For the mod_python custom configuration reading module
Because it is inconvenient to use Req. get_options () in mod_python to read the configuration, you can write this module by yourself and simply support the M $ ini configuration file format. Currently, segments are not supported. For the configuration flag with the same name, the later part will overwrite the previous one. You can automatically ignore comments starting with ";", ignore empty rows, and ignore rows without "=. Only the key-value pairs at both ends of the first "=" can be identified, and parts after the second "=" cannot be identified. The spaces at both ends of the key and value strings are removed. The final configuration result is saved in a dictionary. The Code is as follows:
#-*-Coding: GBK -*-
# Date: 2006-04-22
# Author: gasheor
# Copyright @ 1999-2006, Harry gashero Liu.
From string import split
From string import strip
Def getconfig (filename ):
Global ctconfig
Ctfile = open (filename)
If ctconfig ={} and ctfile! = None:
While true:
Line = ctfile. Readline ()
If line = '': # End of the file
Break
Line = strip (line) # Remove leading and trailing Spaces
If line! = ''And line [0] = ';': # Remove comment lines
Continue
If '=' in line: # contains the configured rows
Retstr = Split (line, '= ')
If Len (retstr)> = 2:
Key = retstr [0]
Value = retstr [1]
Key = strip (key)
# By gashero
Value = strip (value)
# Print "'" + key + "' = '" + value + "'"
Ctconfig [Key] = Value
Else:
# An error row exists.
Pass
Ctfile. Close ()
Return ctconfig
######### Variant ###########
# Dictionary of stored file configurations
Ctconfig = dict ()
The code for testing is as follows, which can be added to the above module:
If _ name __= = "_ main __":
Myconf = getconfig ('commontest. ini ')
Print STR (myconf)
The following is a configuration file, which can be read by the above module:
Note: Do not delete all fields contained in this configuration file,
Otherwise, the normal operation of the system will be affected.
; The comment line starts with a semicolon ";"
; Author of the general examination system for testing
Author = gashero
; Exam duration, in minutes
For example, "timelong = 120" is a two-hour test.
Timelong = 5
; Log on to the database location, preferably not to modify
Logindb = htdocs/ct/scripts/students. DB
; Exam result database location, preferably not modified
Resultdb = htdocs/ct/scripts/results. DB
Of course, the format is too monotonous. You can refer to the module code to use the understandable but more eccentric configuration information.
· Mod _ Global server settings in Python
Sometimes some variables with application scope are required, but mod_python does not provide them. I have also tried to manually specify Sid when creating a session to share the same session among requests, the setting is always invalid. mod_python still generates its own Sid. However, after studying the implementation principles of Python, we found that some non-mod_python features can be used to store application-scope variables, that is, module variables, you can also consider using class members (not instance members ). In this way, you can add a dictionary to the read configuration module to support application scope variables, as shown below:
# Store the dictionary configured during running.
Server = dict ()
It is still very useful after actual tests.
Application Scope variables can be used to store some global configurations and cache pages to cache all frequently accessed files in the memory, even some dynamic pages with few parameters can be cached to improve server performance. Of course, this operation sacrifices a certain amount of memory.
· Publish the mod_python application in bytecode Mode
It is somewhat risky to publish a web application using the. py source code. Thanks to the advanced features of Python, we can publish a web application using bytecode. Back up the entire web application, compile each module into A. PyC bytecode file, and delete the. py source file.
The compilation method is as follows. You can write a small script to compile a single script or the entire directory. As follows:
· Differences between modules imported by mod_python
Here is a small detail, that is, the import between Python modules is different from the import by mod_python. Even in the same mod_python program, the import of one module to another is also a standard import behavior, while the import by mod_python is not standard.
The import of mod_python does not execute module-level code, that is, the module initialization code. Instead, it only extracts the required objects from the module File, such as class instances and functions.
· Mod _ Python system settings
Some configurations of each module in all mod_python applications are replaced with mod_python settings.
For example, the _ name _ attribute of the module is replaced with the file name of the complete path of the module under the current OS, with special characters replaced with underscores, such as "d_httpd2_0_55_apache2_htdocs_ct_scripts_test_py ". In general, the application command line parameter SYS. argv is a list with only one empty string as the element. In mod_python, the list length is also 1 and the element is "mod_python ".
Because the mod_python application still needs to be embedded in Apache-HTTPd, the current path used is the installation path of APACHE-httpd. For example, a relative path is 'htdocs/ct/index.html '. The relative path should start with the installation directory of APACHE-HTTPd, rather than the startup directory of the HTTPd process.
· Initialize some variable methods
You can assign a simple initial value or use the constructor of the corresponding object. The constructor looks simpler. For example, to initialize an empty string, it is often used as follows:
A =''
You can also use the constructor:
A = STR ()
# By gashero
Similarly, you can use other constructor methods, such as the dictionary dict () and list.
· From import behavior and Remove string edge Spaces
Objects imported using from package import OBJ are added to the current module space, and are now part of the current module. You can see this by using Dir () or other methods externally, you can also call the original method indirectly through the current module. For example, the following import method is used to separate strings and remove edge spaces:
From string import split
From string import strip
These two functions can be used anywhere in the current module, just like using global functions. Other modules can also call these two functions through this module.
· _ Doc _ auto indent
The recommended _ Doc _ method is to use triple quotation marks, such:
"
Bbb """
In this case, a is displayed as the left-aligned top header, while BBB is displayed as a tab than. In fact, BBB is more indented than a, regardless of whether there is a blank line under. This indent is clearly only the size of one tab, no matter how many spaces or tabs are in front of BBB in actual writing. In addition, according to the Convention, write an introduction at the beginning of "", then empty rows, and then detailed annotations.
· Python support for Chinese
I have used Python 2.4.3 to provide excellent support for Chinese characters and support multiple encoding methods and aliases. Because I often use Ziguang pinyin, the file encoding statement is:
#-*-Coding: GBK -*-
If the encoding is 'China', It is the alias of gb2312.
· Class variables and instance variables in Python
In python, class variables are defined at the class definition level. The instances of each class share the values of these variables and can be used to pass common parameters between instances. This is of limited use. However, note that instance variables must be referenced using the self. prefix in the method. In python, instance variables cannot be defined outside of methods. Therefore, it is generally defined in the constructor _ init _ () and initialized. The unified declaration of all instance variables in _ init _ () helps to Write clear code, although Python does not need to declare a variable before it is used. In addition, although you can add member variables to the class at runtime, that is, modify the class definition at runtime, this method is not recommended, which is not conducive to the readability of the Code.
The first parameter of all methods of the class must use self. Although you can define a method without any parameters, an error occurs during running. When all methods are called, The instance reference is passed as the first parameter. If the first parameter does not use self, your code may fail. Self is just a recommended naming convention. You don't need this name, but it will lead to lower readability.
We recommend that you add a return to the end of all the methods or functions, even if it is an empty return. This will prevent code from continuing to be executed due to format issues at the end of the stop.
· Object Persistence pickle
For Object persistence, it is best not to make the object member another huge object, so it is difficult to deal with it during persistence. The recommendation is just the index of the other party. For example, student paper members in the general examination system do not need to be stored, so objects can be used. The paper class also needs to store user information, but only uses a string field to store the user name as the index. This greatly reduces the storage space requirements.
We recommend that you define the corresponding _ getstate _ and _ setstate _ methods when defining the persistence of objects to carefully control the storage and reading of objects. You can also perform something similar to the constructor in _ setstate _ to initialize the unstored members.
Note that during testing, _ name _ is _ main __, which is used as the module name to be read by pickle and written to the storage object. When reading the object again, you also need to verify the module and Class Definition of the object. Therefore, if the data written during the test is _ name __= = '_ main, an error occurs when the data is read again. Because the real Module name may be used for the _ name _ at that time.
Many objects not only need to be stored, but sometimes need to display summaries. Therefore, the _ STR _ (Self) method must be implemented. Return a string using this method. In STR (OBJ), you can automatically call this method to return the information Summary of the object.
An example of _ getstate _ and _ setstate:
Class paper:
......
Def _ getstate _ (Self ):
Return (self. username, self. Answer)
Def _ setstate _ (self, State ):
# Initialization of some instances
Self. username, self. Answer = state # unpack
Return
· Use dbhash Database
Although the query function of the dbhash database is far inferior to that of the existing RDBMS, its backend database, berkeleydb, is also one of the four open source databases with extraordinary stability. In addition, the key: Value Pair method is also very suitable for applications that store objects as units. The storage method is also very open and can be stored in key-value pairs without any specific format.
Another characteristic is the storage speed. Because it is not an RDBMS and the technology is quite mature, after decades of development, the advanced access speed can surpass all RDBMS.
In terms of security, because you do not use SQL statements to control access, but manually package and package data, the security is very good, at least there is no SQL injection vulnerability.
Dbhash is suitable for some simple or flexible applications. The storage method is not in the table unit, but the unit is the object indexed by the key. For example, it can be used for user verification. The user name is used as the key name, and the complete user data is used as the key value for verification. The user name and password can be directly stored as key-value pairs. However, user information extraction can be performed using other dbhash data files after verification.
Because the implementation of dbhash has internal cache, it is recommended to use a DB connection pool for access operations, which will further improve the system performance. Because the main bottleneck of the current application system is the query of the database, this simple query method and ultra-high efficiency are still useful.
About dbhash opening. By default, only the data file name can be opened in a read-only database and cannot be modified. In addition, because sometimes the database file may not be created, the flag is generally set to 'C', so that both the data file does not exist and the data can be written. As follows:
Import dbhash
DB = dbhash. Open ('filename. db', 'C ')
In this way, you can use the DB object in the dictionary mode. During the processing, you can use the DB. Sync () method to write data to the disk in real time for storage. You can also use dB. Close () to save data to the disk and close the data file.
Before reading the corresponding key, you can use dB. has_key (key) to determine whether the corresponding key exists. Otherwise, a keyerror is thrown. You can also use dB. Get (Key, default_value) to obtain the default value when the key does not exist. Because dB has a dictionary interface, you can use dB. setdefault (Key, default_value) to read the value and save the key-value pair to the data file.
You can select the method above to read data. The has_key (key) method needs to query the key twice, so it is less efficient and not recommended. You can choose get () or setdefault (). Of course, this is a dictionary method.
For dbhash data files, the disk space of 24kb (24,576 bytes) is automatically used after creation, and the data volume continues to expand after expansion. However, if a large amount of data is stored, even if the data is deleted, the size of the data file will not be reduced. Therefore, you can manually sort the data files regularly to avoid occupying too much space. Although the data file will be expanded, after the excess data is deleted, the space in the past can still be reused by dbhash, without 'disk leakage '.
When writing an application system, we recommend that you implement the preceding dbhash read/write and object packaging and package functions in one module to provide the database read/write interface for the object. Of course, you still need to pay attention to the same problem. During object packaging, the value of the current _ name _ attribute should not be _ main __, so as to prevent future read failures. A recommended interface includes the following functions:
Def getdb ():
"Used to obtain database objects"
Pass
Def get_obj (key ):
"The value object is retrieved by key. If the value object does not exist, none is returned or an error is thrown, including unpacking"
Pass
Def set_obj (Key, OBJ ):
"Save the key-Value Pair object to the database, including the packaging operation"
Pass
The specific application may involve more than one data file, so you can change the interface name by yourself. The last system I designed was a mess. I combined three functions into one, for example:
Def getdb (Key = none, OBJ = none ):
Pass
If both key and OBJ are none, the database object is returned! = None and OBJ = none! = None and OBJ! = When none, key-value pairs are stored in the database.
· About index. py
We recommend that you write an index. py page script, because no one knows what strange functions will be added to mod_python in the future. Therefore, there is an index. py page that allows users to customize the behavior when accessing a specific directory. Even if this page does not do anything, there is only one index function.
The content of my index. py page is as follows, only to prevent earlier versions of mod_python from returning the directory file list When apache-HTTPd accesses a specific directory, a 404 error is thrown. The Code is as follows:
From mod_python import Apache
Def index (req ):
Raise Apache. server_return, Apache. http_not_found
Return 'gashero'
Of course, I use mod_python.publisher for development. Other development methods are not limited by this restriction.
· Time Operation Analysis
Time operations in Python are relatively convenient. A dedicated time module provides multiple interfaces. The two commonly used operation data formats are tick answer and time tuples. I cannot explain these two strange names. In short, this is the way they are written in a book, it is really hard to hear. Tick is the number of seconds from January 1, 1970 to the present. In python2.4.3, It is a floating point number. The decimal part is a more precise part, and the time value is smaller than 1 second. Time tuples are key tuples with nine members: year, month, day, hour, minute, second, Week (0-6, 0 is Monday) which day of the year (1-366, ancient Rome), daylight savings (-, 1, I do not know what to do ).
Therefore, you can use the following method to extract the time of the current day:
A, hour, minute, second, a, a = time. localtime (Time. Time ())
Here, hour, minute, and second are time, minute, and second, which are also common parameters. The other is about time difference, if time is used. localtime () is used to determine the time difference. The Chinese standard time when the tick value is 0 is, January 1, January 1, 1970, and the time difference cannot be discussed. Therefore, the time difference should be used. gmtime () is converted to timetuple. For example, obtain the time difference as follows:
A, hour, minute, second, a, a = time. gmtime (t1-t2)
· Mod _ external redirection in Python
To switch to the desired path after an operation, you need to use the redirection operation. Internal redirection changes the returned content to the specified path, but the display path of the client is still the current path. In this way, when you click some links on the client again, using the relative path will be very troublesome, and it is often difficult to debug. External redirection uses the HTTP header to send relevant redirection information, requiring the client to change the current path and obtain the corresponding page path. In this way, the relative path can still be used. For example, the following modules:
Def index (req ):
Return "...."
Def modify (req ):
Assume that the module is named test. py. the URL to open this module is "http: // localhost/ct/test", that is, to open the index function of the test module. If the HTML code returned by the index function contains a form that is submitted to the modify function, the form's action is "modify" and the relative path is used. In this way, the client URL after the form is submitted becomes "http: // localhost/ct/test/modify", and the displayed page is the return value of the modify function. However, in general, the modify function does not return values, but uses the index function to display the refresh results after the operation. If it is only an internal redirection and changes the return value of the modify function, the absolute action path when the form is submitted again becomes "http: // localhost/ct/test/modify ", it is obviously wrong. In this case, you need to use the external redirection of mod_python.
The external redirection in mod_python uses the Redirect method of the util module. This function requires two parameters. The first parameter is the request object, and the second parameter is the redirection path. The redirection path allows the relative path. The call method is as follows:
From mod_python import util
Def modify (req ):
#......
Util. Redirect (req, "newurl/gashero ")
Return none
In this way, you can implement the happy redirection operation. However, in general, to improve system portability, use relative URL operations. If newurl uses ". ", the path in the preceding example is changed from" http: // localhost/CT "to" http: // localhost/ct/". Note that there is an additional"/"at the end "/". It is this "/" that leads to a relative path error and still cannot be used. Therefore, the recommended redirection path for the modify method in the above example is:
Util. Redirect (req, "../test ")
Note that test is the name of the module where modify is located.
In util. in the internal implementation of the Redirect () function, an exception is thrown to end the execution of the current function. Therefore, util is written in the function. all the statements after the Redirect () function are not executed, including the return statement. If you really need to do some work after external redirection, you can put the util. Redirect () function in the try statement block to handle the exception thrown by it.
All the redirection of cherrypy, which is also a web development technology of Python, uses the relative path of the path, which is much more convenient than mod_python, and does not need to consider the relative relationship of the relative path too much.