July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Jürgen Hermann
You need to build URLs within a CGI script—for example, to send an HTTP redirection header.
To build a URL within a script, you need information such as the
hostname and script name. According to the CGI standard, the web
server sets up a lot of useful information in the process environment
of a script before it runs the script itself. In a Python script, we
can access the process environment as os.environ,
an attribute of the os module:
import os, string def isSSL( ): """ Return true if we are on an SSL (https) connection. """ return os.environ.get('SSL_PROTOCOL', '') != '' def getScriptname( ): """ Return the scriptname part of the URL ("/path/to/my.cgi"). """ return os.environ.get('SCRIPT_NAME', '') def getPathinfo( ): """ Return the remaining part of the URL. """ pathinfo = os.environ.get('PATH_INFO', '') # Fix for a well-known bug in IIS/4.0 if os.name == 'nt': scriptname = getScriptname( ) if string.find(pathinfo, scriptname) == 0: pathinfo = pathinfo[len(scriptname):] return pathinfo def getQualifiedURL(uri = None): """ Return a full URL starting with schema, servername, and port. Specifying uri causes it to be appended to the server root URL (uri must start with a slash). """ schema, stdport = (('http', '80'), ('https', '443'))[isSSL( )] host = os.environ.get('HTTP_HOST', '') if not host: host = os.environ.get('SERVER_NAME', 'localhost') port = os.environ.get('SERVER_PORT', '80') if port != stdport: host ...Read now
Unlock full access