#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2004
    Location
    Virginia
    Posts
    98
    Rep Power
    11

    Question HTML Forms and Python


    I am fairly new to python but know enough. One thing i need to know is how to take what ever is put into a text field and then be able to work with it as like a variable. I know how to do this in PHP and stuff but can't figure out how in Python.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2004
    Location
    Regensburg, Germany
    Posts
    147
    Rep Power
    17
    Use the cgi module:

    Example:

    import cgi
    ...
    ...
    form = cgi.FieldStorage()
    id = form["id"]
    mode = form["mode"]
    subject = form["subject"]
    ...
    ...

    A FieldStorage object can be used like a dictionary, i.e. it has the methods "keys()" and "has_key(key_name)".

    If you want to access form fields like ordinary variables, you could update the list of global objects:

    ...
    ...
    globals().update(cgi.FieldStorage())
    ...
    ...

    but I don't think this is a good idea because it is REALLY DANGEROUS: someone having access to the source code of your script could be able to modify the code by e.g. replacing constants, variables or functions with form field values.

    A better method would be using a struct class like this:

    Code:
    class struct:
    
        def __init__(self, attrs):
            self.__dict__["attr"] = {}
            self.attr.update(attrs)
            
        def __setattr__(self, name, value):
            self.attr[name] = value
    
        def __getattr__(self, name):
            if self.attr.has_key(name):
                return self.attr[name]
            # requested attribute is not a member, but we don't want
            # this to cause an exception:
            return None
    
    ...
    ...
    form = struct(cgi.FieldStorage())
    if form.mode == "some_value":
        print form.subject
    With a struct class like this, you can access form fields as members of the struct object.
  4. #3
  5. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    A quick google for "python cgi tutorial" shows lots of info. At the top of my search results I find:
    http://www.devshed.com/c/a/Python/Python-on-the-Web/
    written by the one and only netytan!

    grim

IMN logo majestic logo threadwatch logo seochat tools logo