Welcome, guest | Sign In | My Account | Store | Cart
1

The following are some useful functions to build URLs within a CGI script, for example to send a HTTP redirection header (see example).

Python, 49 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os, string

def isSSL():
    """ Return true if we are on a 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 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.

        *uri* -- append this server-rooted uri (must start with a slash)
    """
    schema, stdport = (('http', '80'), ('https', '443'))[isSSL()]
    host = getEnvValue('HTTP_HOST')
    if not host:
        host = getEnvValue('SERVER_NAME')
        port = getEnvValue('SERVER_PORT', '80')
        if port != stdport: host = host + ":" + port

    result = "%s://%s" % (schema, host)
    if uri: result = result + uri
    
    return result


def getBaseURL():
    """ Return a fully qualified URL to this script. """
    return getQualifiedURL(getScriptname())

# example (redirect)
print "Location:", getQualifiedURL("/go/here")

1 comment

Sjoerd Schalekamp 8 years, 3 months ago  # | flag

GetEnvValue missing. I had to add the following function to get this script running:

def getEnvValue(value):

env = os.environ

return env[value]

Add a comment

Sign in to comment