{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Form cgifieldstorage parse query cgi if

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ides output to stdout Provides stdout • (usually) parses a special set of global variables. CS 206 G. Dudek 121 A typical CGI script #!/usr/local/bin/python import cgi cgi def main(): print "Content-type: text/html\n" # note HTTP transactions start with this! form = cgi.FieldStorage() # parse query cgi if form.has_key("firstname") and form["firstname"].value != "": print "<h1>Hello", form["firstname"].value, "</h1>" else: print "<h1>Error! Please enter first name.</h1>" main() CS 206 G. Dudek 122 CGI script structure • Check form fields – use cgi.FieldStorage class to parse query use cgi class » » takes care of decoding, handles GET and POST "foo=ab+cd%21ef&bar=spam" --> {'foo': 'ab cd!ef', 'bar': 'spam'} # (well, actually, ...) 'ab • Perform action – this is up to you! – database interfaces available • Generate HTTP + HTML output – – – (HTTP is the way to returning data, HTML is the formatting.) print statements are simplest template solutions available CS 206 G. Dudek 123 Structure refinement form = cgi.FieldStorage() form cg if not form: ...display blank form... elif ...valid form...: elif ...valid ...perform action, display results (or next form)... else: ...display error message (maybe repeating form)... CS 206 G. Dudek 124 FieldStorage details FieldStorage • Behaves like a dictionary: – .keys(), .has_key() # but not others! – dictionary-like object ("mapping") • Items – values are MiniFieldStorage instances values instances » .value gives field value! – if multiple values: list of MiniFieldStorage instances if list instances » if type(...) == types.ListType: ... – may also be FieldStorage instances may instances » used for file upload (test .file attribute) CS 206 G. Dudek 125 Other CGI niceties • cgi.escape(s) – translate "<", "&", ">" to "&lt;"...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online