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

I found the CGI module to be nice in its power but wanted to create my own simpler version of the module. It lacks some of the power that the CGI module affords, but the code is small and has some helpful functions defined in it. The module listed below has been tested but really needs some test code written for it.

Python, 48 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
def execute(function, exception):
    if string == exception:
        self()
    else:
        function()

def html(string):
    print 'Content-Type: text/html\n\n' + string
    raise SystemExit(0)

def plain(string):
    print 'Content-Type: text/plain\n\n' + string
    raise SystemExit(0)

def self():
    from sys import argv
    print 'Content-Type: text/plain\n\n' + file(argv[0]).read()
    raise SystemExit(0)

def export():
    global string, dictionary, export, decode
    try:
        from os import environ
        string = environ['QUERY_STRING']
    except:
        string = None
    try:
        temp = string.replace('+', ' ').split('&')
        for index in range(len(temp)):
            temp[index] = temp[index].split('=')
        dictionary = dict()
        for parameter, value in temp:
            dictionary[decode(parameter)] = decode(value)
    except:
        dictionary = None
    del export, decode

def decode(string):
    index = string.find('%')
    while index is not -1:
        string = string[:index] + chr(int(string[index+1:index+3], 16)) + string[index+3:]
        index = string.find('%', index + 1)
    return string

if __name__ == '__main__':
    self()
else:
    export()

Why would someone want to use this code? It is easy to figure out, small, and has some functions that might be found to be useful.

2 comments

Stephen Chappell (author) 18 years, 6 months ago  # | flag

Error. Ah! A bug! :P -- That's just for me. It is recommended that "raise SystemExit(0)" be removed from the html, plain, and self. Unfortunately, "try: code; except: code" can catch the exception and error handling code can be executed. Does anyone know of a better, harder way to kill a program while still returning an exit code of 0?

Stephen Chappell (author) 18 years, 6 months ago  # | flag

Nevermind. A solution was conjured up at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440642 in regards to the problem. The code can be modified so that it continues passing a SystemExit exception up the stack if needed.