Click here to load reader

Another CGI

  • View

  • Download

Embed Size (px)


Another CGI. Python. Strings. Single and double quotes interchangeable Triple quotes ( """ ) allow multi-line literal quoting Escaping of \n , % , etc by default Prefix r can be used for regexps, r'[a-z].*' - PowerPoint PPT Presentation

Text of Another CGI

  • PythonAnother CGI

  • StringsSingle and double quotes interchangeableTriple quotes (""") allow multi-line literal quotingEscaping of \n, %, etc by defaultPrefix r can be used for regexps, r'[a-z].*'Any variable can be converted to a string with str(v). Can go back with int(s), float(s)Strings operations:Concatenation with +, repeating with *Length with len()Substrings with []. Interesting index options.Special boolean operator in

  • String Methodscountfindisdigitupper, lowerrjust, ljuststripreplace

  • Tuples and ListsTuples store a set of elements. Syntax: foo = ("Korn", "Jeff")Lists also store elements but unlike tuples can be modified (thus cheaper). Syntax:foo = ["Korn", "Jeff"]foo[1] = "Jeffrey"List operations:append, extend, +, *, len, index, in, pop, sort, reverse, join, etc.Be careful about references!

  • DictionaryDictionaries are associative arrays (arrays indexed by string or number). Values can be any object.Syntax:student = {'name' : 'Guido', 'score': 95 }Operations:has_key, keys, values, len, get, copy, updateExample:print student['name']

  • StatementsStandard if, then, else

    While loops

    if person == 'Korn': status = 'teacher'elif person == 'Cano' status = 'yankee'else: status = 'unknown'print person, statuswhile n

  • for loopsSimilar to shell:

    To do c-style loops, use special function range:

    Also: xrangefor val in ["foo", "bar", "baz"]: print "Hello %s" % valfor val in range(5, 20, 2): print val# prints 5, 7, 9 ... 19

  • ExceptionsRun-time errors are possible with Python, but they can be caught with try-except:

    You can also use: raise, finallytry: n = float(inputstring) m = n * 2except ValueError, msg: print msg# will print: invalid literal for float(): foo

  • FunctionsDefined with def:

    Types not neededArguments can have defaults:

    Variables in functions are localglobal changes thisreturn used to return valuesdef my_func(foo, bar): print foo + bardef my_func(foo, bar=12): print foo + barmy_func(3)15my_func(3, bar=3)

  • ModulesPython modules are libraries of reusable code with specific functionalitiesStandard modules are distributed with Python to do a variety of things.Modules names are unique, but functions in modules don't conflict with other modules.Modules can have sub-modules.

  • Using ModulesInclude modules in your program with use, e.g. import math incorporates the math moduleimport mathprint math.log(4906, 2)12.0

    print math.sqrt(100)10

  • Important modulessyssys.argv, sys.path, sys.platform, sys.exit, sys.stdin, sys.stderr, sys.stdoutosos.getcwd, os.environ, os.chdir, os.listdir, os.mkdir, os.rmdir, os.remove, os.system, os.popen, os.getpidos.pathos.path.abspath, os.path.dirname, os.path.basename, os.path.join, os.path.split, os.isfile, os.isdir

  • HTTPProtocol for the WebClient-server modelClient (user agent) is typically web browser (e.g. Firefox)Server is web server (e.g. Apache)Client request a resource identified by URLse.g.

  • Apache HTTP ServerOpen source HTTP (Web) server Most popular web server since 1996The A in LAMPPart of Apache Software FoundationOther projects: Ant, Hadoop, Tomcat, SpamAssassin,

  • HTTP TransactionsHTTP request to web serverGET /v40images/nyu.gif HTTP/1.1Host: www.nyu.eduHTTP response to web clientHTTP/1.1 200 OKContent-type: image/gifContent-length: 3210

  • HTML Example

    Some Document

    Some TopicsThis is an HTML document

    This is another paragraph

  • HTMLFile format that describes a webpageCan be written by hand, or generated by a programA good way to generate a HTML file is by writing a shell or Perl script

  • GatewaysInterface between resource and a web server

    Web ServerresourceGatewayHTTP

  • CGICommon Gateway Interface - a standard interface for running helper applications to generate dynamic contentsSpecify the encoding of data passed to programsAllow HTML documents to be created on the flyTransparent to clientsClient sends regular HTTP requestWeb server receives HTTP request, runs CGI program, and sends contents back in HTTP responsesCGI programs can be written in any language

  • How CGI WorksWeb ServerScriptDocumentHTTP requestHTTP responsespawn process

  • FormsHTML forms are used to collect user inputData sent via HTTP requestServer launches CGI script to process data

    Enter your query:

  • Input TypesText Field

    Radio Buttons Small Medium LargeCheckboxes Lettuce TomatoText Area

  • Submit ButtonSubmits the form for processing by the CGI script specified in the form tag

  • HTTP MethodsDetermine how form data are sent to web serverTwo methods:GETForm variables stored in URLPOSTForm variables sent as content of HTTP request

  • Encoding Form ValuesBrowser sends form variable as name-value pairsname1=value1&name2=value2&name3=value3Names are defined in form elements

    Special characters are replaced with %## (2-digit hex number), spaces replaced with +e.g. 10/20 Wed is encoded as 10%2F20+Wed

  • GET/POST examplesGET:GET /cgi-bin/ company=Microsoft HTTP/1.1HOST: www.cs.nyu.eduPOST:POST /cgi-bin/ HTTP/1.1HOST: www.cs.nyu.eduother headers


  • GET or POST?GET method forRetrieving information, e.g. from a databaseA safe method - no action taken other than retrievalEmbedding data in URL without form elementPOST method forForms with many fields or long fieldsSending data for updating database, posting to bulletin board, etc.GET requests may be cached by clients browsers or proxies, but not POST requests

  • Parsing Form InputMethod stored in HTTP_METHODGET: Data encoded into QUERY_STRINGPOST: Data in standard input (from body of request)Most scripts parse input into an associative arrayParse it yourself, orUse available libraries (e.g. Perl CGI module)


  • Example: Comment Form

  • Part 1: HTML Form

    Anonymous Comment Submission

    Please enter your comment below which willbe sent anonymously to [email protected] you want to be extra cautious, access thispage through Anonymizer.

  • Part 2: CGI Script (ksh)#!/home/unixtool/bin/ksh

    . cgi-lib.ksh # Read special functions to help parseReadParsePrintHeader

    print -r -- "${Cgi.comment}" | /bin/mailx -s "COMMENT" kornj

    print "You submitted the comment"print ""print -r -- "${Cgi.comment}"print ""

  • Example: Find words in Dictionary

    Regular expression:

  • Example: CGI Script (ksh)#!/home/unixtool/bin/ksh

    PATH=$PATH:.. cgi-lib.kshReadParsePrintHeader

    print " Words matching ${} in the dictionary \n";print ""grep "${}" /usr/dict/words | while read worddo print " $word"doneprint ""

  • DebuggingDebugging can be tricky, since error messages don't always print well as HTMLOne method: run interactively$ QUERY_STRING='birthday=10/15/03' $ ./birthday.cgiContent-type: text/html

    Your birthday is 10/15/02.

  • A Python CGI Script#!/usr/bin/pythonimport cgiimport cgitb

    cgitb.enable()form = cgi.FieldStorage()

    bday = form['birthday'].value

    # Print headerprint 'Content-Type: text/html'print

    # Your HTML bodyprint "Your birthday is %s.\n" % bday

  • Debugging Python CGI ScriptsDebugging CGI script is tricky - error messages dont always come up on your browserRun script with test datapython cgiScript prod=MacBook price=1800Content-Type: text/html

  • CGI BenefitsSimpleLanguage independentUNIX tools are good for this becauseWork well with textIntegrate programs wellEasy to prototypeNo compilation (CGI scripts)

    ******************HTTP_HOST The name of the web server. This may or may not be the same as SERVER_NAME, depending on type of name resolution you are using on your Web server.HTTP_REFERER The page address where the HTTP request originated.HTTP_USER_AGENT The browser the client is using to send the request.HTTP_COOKIE The cookie string that was included in the request.REMOTE_ADDR The IP address of the remote host making the request.REMOTE_HOST The name of the host making the request.REMOTE_USER If the server supports user authentication, and the script is protected, this is the username they have authenticated as.REQUEST_METHOD The method with which the request was made. For HTTP, this is "GET", "HEAD", "POST", etc.SERVER_NAME The server's hostname, DNS alias, or IP address as it would appear in self-referencing URLs.SERVER_PORT The port number*********