Toronto CSC 309H - Web Programming - Server-Side HTTP

Unformatted text preview:

CSC309: Web ProgrammingGreg Wilson 11Web Programming:Server-Side HTTPGreg [email protected] 20052The Active WebThe web is far more than just a fancy replacement for inter-library loanMost of its power comes from the fact that browsers can interact with programs that aren't web serversMore accurately, clients can ask web servers to run other programs on their behalfThis lecture looks at how to handle HTTP requestsPlease make sure you attend the security lecture!3The Common Gateway InterfaceHow to let everyday users write programs that handle HTTP requests?Require them to write socket-level code?Complicated and error-proneRequires lots of portsHave the web server handle the details!Recompiling it repeatedly would be a painSo define a protocol that lets it run external programs4…CGIThe Common Gateway Interface (CGI) specifies:How a web server passes data to a programHow that program passes data back to the serverRemember, the web runs on protocolsDoes not specify:A programming languageHow the server decides what program to runEach server defines its own configuration and permission rulesCSC309: Web ProgrammingGreg Wilson 25…CGIWhen a server runs a CGI, it sends data:Through environment variablesThings that are expected to be shortThrough standard inputThe "extra" data in the HTTP requestThe program sends data to the server through standard outputIn most cases, the server just forwards it to the clientSo the program must create all headers6CGI Environment Variables17290img/jpegname=mydog.jpg/cgi-bin/upload.pyGETHow much extra data is being sentCONTENT_LENGTHWhat kind of extra data is being sentCONTENT_TYPEQuery parameters from the URLQUERY_STRINGWhat's runningSCRIPT_NAMEor POSTREQUEST_METHOD7MIME TypesClients and servers need a way to specify data types to one anotherRemember, bytes are just bytesMultipart Internet Mail Extensions (MIME) standard defines:Families of types (image, audio, …)Particular members of families (JPEG, MP3, …)See RFC 2045Learn how to read RFCs!8…MIME TypesAdobe PDFapplication/pdfApplication-specific dataApple Quicktime video formatvideo/quicktimeVideoMP3 audio filesaudio/x-mp3AudioJPEG-format imagesimage/jpegImageWeb pagestext/htmlTextCSC309: Web ProgrammingGreg Wilson 39Hello, CGISimplest possible CGI pays no attention to query parameters or extra dataJust prints HTML to stdoutBut must also print Content-type headerAnd a blank line to separate headers from content#!/python/python.exeprint 'Content-type: text/html\n'print '<html><body><p>Hello, CGI!</p></body></html>'10Displaying the EnvironmentWhole point of CGI is active contentShow a list of environment variablesYou'll use this frequently when debugging…print 'Content-type: text/html\n'print '<html><body>'keys = os.environ.keys()keys.sort()for k in keys:print '<p>%s: %s</p>' % \(cgi.escape(k), cgi.escape(os.environ[k]))print '</body></html>'11…Environment OutputDOCUMENT_ROOT: /var/www/GATEWAY_INTERFACE: CGI/1.1HTTP_ACCEPT: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5HTTP_ACCEPT_CHARSET: ISO-8859-1,utf-8;q=0.7,*;q=0.7HTTP_ACCEPT_ENCODING: gzip,deflateHTTP_ACCEPT_LANGUAGE: en-us,en;q=0.5HTTP_CONNECTION: keep-aliveHTTP_KEEP_ALIVE: 300HTTP_USER_AGENT: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6) Gecko/20050317 Firefox/1.0.2PATH: /usr/local/bin:/usr/bin:/bin…etc…12Creating FormsHTML forms allow users to…oh, you know how they workNot nearly as sophisticated as desktop GUIsBut programmers keep finding ways to do new thingsCreate a form using a <form> elementaction attribute specifies URL to send data tomethod attribute specifies type of request (i.e., GET or POST)CSC309: Web ProgrammingGreg Wilson 413…Creating FormsInside the form, can have:<select> elements to let users choose from a listList items specified using <option> elements<input> elements for other kinds of data<input type="text"> creates a text entry box<input type="checkbox"> creates an on/off box<input type="submit"> creates a submit button<input type="reset"> creates a reset buttonEtc.14A Simple Form<html><body><form action="http://www.bio.com/simple_form.py" method="POST"><p>Sequence: <input name="sequence" type="text" value="GATTACA"/>Search type:<select name="search_type"><option>Exact match</option><option selected="selected">Similarity match</option><option>Sub-match</option></select></p>…15…A Simple Form…<p>Programs:<input checked="checked" name="program" type="checkbox" value="FROG-11">FROG (version 1.1)</input><input name="program" type="checkbox" value="FROG-beta">FROG (2.0 beta)</input><input checked="checked" name="program" type="checkbox" value="Bayes-Hart">Bayes-Hart</input></p><p><input type="submit"/><input type="reset"/></p></form></body></html>16…A Simple FormCSC309: Web ProgrammingGreg Wilson 517ParametersEach input element has a name attributeBecomes the parameter name in the HTTP requestSubmitting the previous form with defaults sets os.environ['REQUEST_METHOD'] to "POST", etc.Stdin gets:sequence=GATTACA&search_type=Similarity+match&program=FROG-11&program=Bayes-Hart18Handling FormsWe could handle form data directlyBut the mechanics are the same each time, so use Python's cgi moduleDefines a FieldStorage classHas dictionary-like interfaceWhen one is created, Python fills it with dataKeys are parameter namesValues are either strings or listsExtra data available on stdin19Development TipsWhen writing CGIs, add this to the top:import cgitbcgitb.enable()Creates an HTML stack trace for errorsTesting whether a FieldStorage value is a string or a list is tediousUse fs.getfirst(name) if you expect oneOr fs.getlist(name) if you expect many20Maintaining StateAlmost always want to maintain state on the serverYour shopping cart, the message you're previewing, etc.CGIs can do this any way they want toIndustrial-strength solution is to use a relational databaseA three-tier architectureWe'll see this later in the courseCSC309: Web ProgrammingGreg Wilson 621…Maintaining StateSimple programs often just use filesCGI re-reads the file each time it handles an HTTP requestOverwrites it if state has changedExample: append messages to a web pageOld messages are saved in a file, one per


View Full Document

Toronto CSC 309H - Web Programming - Server-Side HTTP

Download Web Programming - Server-Side HTTP
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Web Programming - Server-Side HTTP and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Web Programming - Server-Side HTTP 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?