cgi problem

Thomas Guettler niemand.leermann at thomas-guettler.de
Wed Mar 8 10:43:37 EST 2006


Am Wed, 08 Mar 2006 00:19:55 -0800 schrieb Paul Rubin:

> I'm trying to write a simple cgi that reads a post from the user's
> browser, does some stuff with the form data, and redirects the browser
> back to the originating url, i.e. I want the cgi to send a 302
> redirect.

Hi,

I have this setup for a small script (for bigger things I use quixote)



def cgi_main():
    stdout=sys.stdout
    sys.stdout=sys.stderr # print soll zu Apache-Log
    try:
        html=cgi_html()
    except ReturnThis, r:
        stdout.write(str(r))
        return
    stdout.write("Content-Type: text/html\n\n%s" % html)

CGI-Script *very* small
...........
# Python Imports
import os
import sys

import cgitb
cgitb.enable()
import foo

if __name__=="__main__":
    foo.cgi_main()

............

file foo:

def cgi_main():
    stdout=sys.stdout
    sys.stdout=sys.stderr # print should go to Apache-Log
    try:
        html=cgi_html()
    except ReturnThis, r:
        stdout.write(str(r))
        return
    stdout.write("Content-Type: text/html\n\n%s" % html)


class ReturnThis(Exception):
    pass

class Redirect(ReturnThis):
    def __init__(self, destination):
        if os.environ.get("HTTPS")=="on":
            http="https://"
        else:
            http="http://"
        url="%s%s%s%s" % (http, os.environ["SERVER_NAME"], os.environ["SCRIPT_NAME"],
                          destination)
        header="Status: 302 Moved Temporarily\nLocation: %s\n\n" % (
            url)
        ReturnThis.__init__(self, header)


Now you can 'raise Redirect("mylocation")' anywhere in your code.

HTH,
 Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: niemand.leermann at thomas-guettler.de




More information about the Python-list mailing list