id
int64
0
25.6k
text
stringlengths
0
4.59k
5,700
your system' file explorer gui howeverthe cgi scripts ultimately invoked by some of the example links must be run by web server if you click to browse such pages directlyyour browser will likely display the scriptssource codeinstead of running it to run scriptstoobe sure to open the html pages by typing their "localhosturl address into your browser' address field eventuallyyou probably will want to start using more powerful web serverso we will study additional cgi installation details later in this you may also wish to review our prior exploration of custom server options in (apache and mod_python are popular optionsuch details can be safely skipped or skimmed if you will not be installing on another server right away for nowwe'll run locally viewing server-side examples and output the source code of examples in this part of the book is listed in the text and included in the book' examples distribution package in all casesif you wish to view the source code of an html fileor the html generated by python cgi scriptyou can also simply select your browser' view source menu option while the corresponding web page is displayed keep in mindthoughthat your browser' view source option lets you see the output of server-side script after it has runbut not the source code of the script itself there is no automatic way to view the python source code of the cgi scripts themselvesshort of finding them in this book or in its examples distribution to address this issuelater in this we'll also write cgi-based program called getfilewhich allows the source code of any file on this book' website (htmlcgi scriptand so onto be downloaded and viewed simply type the desired file' name into web page form referenced by the getfile html link on the internet demos launcher page of figure - or add it to the end of an explicitly typed url as parameter like the followingreplace tutor py at the end with the name of the script whose code you wish to viewand omit the cgi-bin component at the end to view html files insteadin responsethe server will ship back the text of the named file to your browser this process requires explicit interface stepsthoughand much more knowledge of urls than we've gained thus farto learn how and why this magic line workslet' move on to the next section server-side scripting
5,701
now that we've looked at setup issuesit' time to get into concrete programming details this section is tutorial that introduces cgi coding one step at time--from simplenoninteractive scripts to larger programs that utilize all the common web page user input devices (what we called widgets in the tkinter gui in part iiialong the waywe'll also explore the core ideas behind server-side scripting we'll move slowly at firstto learn all the basicsthe next will use the ideas presented here to build up larger and more realistic website examples for nowlet' work through simple cgi tutorialwith just enough html thrown in to write basic server-side scripts first web page as mentionedcgi scripts are intimately bound up with htmlso let' start with simple html page the file tutor htmlshown in example - defines bona fidefully functional web page-- text file containing html codewhich specifies the structure and contents of simple web page example - pp \internet\web\tutor html html first html page hellohtml worldif you point your favorite web browser to the internet address of this fileyou should see page like that shown in figure - this figure shows the internet explorer browser at work on the address browser' address field)and it assumes that the local web server described in the prior section is runningother browsers render the page similarly since this is static html fileyou'll get the same result if you simply click on the file' icon on most platformsthough its text won' be delivered by the web server in this mode climbing the cgi learning curve
5,702
to truly understand how this little file does its workyou need to know something about html syntaxinternet addressesand file permission rules let' take quick first look at each of these topics before we move on to the next example html basics promised that wouldn' teach much html in this bookbut you need to know enough to make sense of examples in shorthtml is descriptive markup languagebased on tags-items enclosed in pairs some tags stand alone ( specifies horizontal ruleothers appear in begin/end pairs in which the end tag includes an extra slash for instanceto specify the text of level-one header linewe write html code of the form text the text between the tags shows up on the web page some tags also allow us to specify options (sometimes called attributesfor examplea tag pair like text specifies hyperlinkpressing the link' text in the page directs the browser to access the internet address (urllisted in the href option it' important to keep in mind that html is used only to describe pagesyour web browser reads it and translates its description to web page with headersparagraphslinksand the like notably absent are both layout information--the browser is responsible for arranging components on the page--and syntax for programming logic-there are no if statementsloopsand so on alsopython code is nowhere to be found in example - raw html is strictly for defining pagesnot for coding programs or specifying all user interface details html' lack of user interface control and programmability is both strength and weakness it' well suited to describing pages and simple user interfaces at high level the browsernot youhandles physically laying out the page on your screen on the other handhtml by itself does not directly support full-blown guis and requires us to introduce cgi scripts (or other technologies such as riasto websites in order to add dynamic programmability to otherwise static html server-side scripting
5,703
once you write an html fileyou need to put it somewhere web browser can reference it if you are using the locally running python web server described earlierthis becomes trivialuse url of the form and the web server script by default serves pages and scripts from the directory in which it is run on other serversurls may be more complex like all html filestutor html must be stored in directory on the server machinefrom which the resident web server program allows browsers to fetch pages for exampleon the server used for the second edition of this bookthe page' file must be stored in or below the public_html directory of my personal home directory--that issomewhere in the directory tree rooted at /home/lutz/public_html the complete unix pathname of this file on the server is/home/lutz/public_html/tutor html this path is different from its pp \internet\web location in the book' examples distributionas given in the example file listing' title when referencing this file on the clientthoughyou must specify its internet addresssometimes called urlinstead of directory path name the following url was used to load the remote page from the serverthe remote server maps this url to the unix pathname automaticallyin much the same way that the server script for our locally-running server in generalurl strings like the one just listed are composed as the concatenation of multiple partsprotocol namehttp the protocol part of this url tells the browser to communicate with the http ( webserver program on the server machineusing the http message protocol urls used in browsers can also name different protocols--for exampleftp:/to reference file managed by the ftp protocol and serverfile:/to reference file on the local machinetelnet to start telnet client sessionand so on server machine name and portstarship python net url also names the target server machine' domain name or internet protocol (ipaddress following the protocol type herewe list the domain name of the server machine where the examples are installedthe machine name listed is used to open socket to talk to the server as usuala machine name of localhost (or the equivalent ip address here means the server is running on the same machine as the client optionallythis part of the url may also explicitly give the socket port on which the server is listening for connectionsfollowing colon ( starship python net or : for httpthe socket is usually connected to port number climbing the cgi learning curve
5,704
on machine names and ports file path~lutz/tutor html finallythe url gives the path to the desired file on the remote machine the http web server automatically translates the url' file path to the file' true pathnameon the starship server~lutz is automatically translated to the public_html directory in my home directory when using the python-coded web server script in example - files are mapped to the server' current working directory instead urls typically map to such filesbut they can reference other sorts of items as welland as we'll see in few moments may name an executable cgi script to be run when accessed query parameters (used in later examplesurls may also be followed by additional input parameters for cgi programs when usedthey are introduced by and are typically separated by characters for instancea string of the form ?name=bob&job=hacker at the end of url passes parameters named name and job to the cgi script named earlier in the urlwith values bob and hackerrespectively as we'll discuss later in this when we explore escaping rulesthe parameters may sometimes be separated by characters insteadas in ?name=bob;job=hackerthough this form is less common these values are sometimes called url query string parameters and are treated the same as form inputs by scripts technically speakingquery parameters may have other structures ( unnamed values separated by +)but we will ignore additional options in this textmore on both parameters and input forms later in this tutorial to make sure we have handle on url syntaxlet' pick apart another example that we will be using later in this in the following http protocol urlthe components uniquely identify server script to be run as followsthe server name localhost means the web server is running on the same machine as the clientas explained earlierthis is the configuration we're using for our examples port number gives the socket port on which the web server is listening for connections (port is the default if this part is omittedso we will usually omit itthe file path cgi-bin/languages py gives the location of the file to be run on the server machinewithin the directory where the server looks for referenced files the query string ?language=all provides an input parameter to the referenced script languages pyas an alternative to user input in form fields (described later server-side scripting
5,705
of urls is slightly richerprotocol://networklocation/path;parameters?querystring#fragment for instancethe fragment part may name section within page ( #part moreovereach part can have formats of its ownand some are not used in all protocols the ;parameters part is omitted for httpfor instance (it gives an explicit file type for ftp)and the networklocation part may also specify optional user login parameters for some protocol schemes (its full format is user:password@host:port for ftp and telnetbut just host:port for httpwe used complex ftp url in for examplewhich included username and passwordas well as binary file type (the server may guess if no type is given)ftp://lutz:password@ftp rmi net/filename;type= we'll ignore additional url formatting rules here if you're interested in more detailsyou might start by reading the urllib parse module' entry in python' library manualas well as its source code in the python standard library you may also notice that url you type to access page looks bit different after the page is fetched (spaces become characterscharacters are addedand so onthis is simply because browsers must also generally follow url escaping ( translationconventionswhich we'll explore later in this using minimal urls because browsers remember the prior page' internet addressurls embedded in html files can often omit the protocol and server namesas well as the file' directory path if missingthe browser simply uses these componentsvalues from the last page' address this minimal syntax works for urls embedded in hyperlinks and for form actions (we'll meet forms later in this tutorialfor examplewithin page that was fetched from the directory dirpath on the server <form action="next pyare treated exactly as if we had specified complete url with explicit server and path componentslike the followingthe first minimal url refers to the file more html on the same server and in the same directory from which the page containing this hyperlink was fetchedit is expanded to complete url within the browser urls can also employ unix-style relative path syntax in the file path component hyperlink tag like for instancenames gif file on the server machine and parent directory of the file that contains this link' url climbing the cgi learning curve
5,706
eyesightthe main advantage of such minimal urls is that they don' need to be changed if you ever move your pages to new directory or server--the server and path are inferred when the page is usedthey are not hardcoded into its html the flipside of this can be fairly painfulexamples that do include explicit site names and pathnames in urls embedded within html code cannot be copied to other servers without source code changes scripts and special html tags can help herebut editing source code can be error-prone the downside of minimal urls is that they don' trigger automatic internet connections when followed offline this becomes apparent only when you load pages from local files on your computer for examplewe can generally open html pages without connecting to the internet at all by pointing web browser to page' file that lives on the local machine ( by clicking on its file iconwhen browsing page locally like thisfollowing fully specified url makes the browser automatically connect to the internet to fetch the referenced page or script minimal urlsthoughare opened on the local machine againusuallythe browser simply displays the referenced page or script' source code the net effect is that minimal urls are more portablebut they tend to work better when running all pages live on the internet (or served up by locally running web serverto make them easier to work withthe examples in this book will often omit the server and path components in urls they contain in this bookto derive page or script' true url from minimal urlimagine that the stringappears before the filename given by the url your browser willeven if you don' html file permission constraints one install pointer before we move onif you want to use different server and machineit may be necessary on some platforms to grant web page files and their directories world-readable permission that' because they are loaded by arbitrary people over the web (often by someone named "nobody,who we'll introduce in momentan appropriate chmod command can be used to change permissions on unix-like machines for instancea chmod filename shell command usually sufficesit makes filename readable and executable by everyoneand writable by you only these directory and file permission details are typicalbut they can vary from server to server be sure to find out about the local server' conventions if you upload html files to remote site these are not necessarily magic numbers on unix machinesmode is bit mask the first simply means that you (the file' ownercan readwriteand execute the file ( in binary is --each bit enables an access modethe two (binary say that everyone else (your group and otherscan read and execute (but not writethe file see your system' manpage on the chmod command for more details server-side scripting
5,707
the html file we saw in the prior section is just that--an html filenot cgi script when referenced by browserthe remote web server simply sends back the file' text to produce new page in the browser to illustrate the nature of cgi scriptslet' recode the example as python cgi programas shown in example - example - pp \internet\web\cgi-bin\tutor py #!/usr/bin/python ""runs on the serverprints html to create new pageurl=""print('content-typetext/html\ 'print('cgi 'print(' first cgi script'print('hellocgi world!'this filetutor pymakes the same sort of page as example - if you point your browser at it--simply replace html with py in the urland add the cgi-bin subdirectory name to the path to yield its address to enter in your browser' address fieldbut this time it' very different kind of animal--it is an executable program that is run on the server in response to your access request it' also completely legal python programin which the page' html is printed dynamicallyinstead of being precoded in static file in factlittle is cgi-specific about this python programif run from the system command lineit simply prints html instead of generating browser pagec:\pp \internet\web\cgi-binpython tutor py content-typetext/html cgi first cgi script hellocgi worldwhen run by the http server program on web server machinehoweverthe standard output stream is tied to socket read by the browser on the client machine in this contextall the output is sent across the internet to your web browser as suchit must be formatted per the browser' expectations in particularwhen the script' output reaches your browserthe first printed line is interpreted as headerdescribing the text that follows there can be more than one header line in the printed responsebut there must always be blank line between the headers and the start of the html code (or other dataas we'll see later"cookiestate retention directives show up in the header area as wellprior to the blank line in this scriptthe first header line tells the browser that the rest of the transmission is html text (text/html)and the newline character (\nat the end of the first print call climbing the cgi learning curve
5,708
itself the net effect is to insert blank line after the header line the rest of this program' output is standard html and is used by the browser to generate web page on clientexactly as if the html lived in static html file on the server +cgi scripts are accessed just like html filesyou either type the full url of this script into your browser' address field or click on the tutor py link line in the examples root page of figure - (which follows minimal hyperlink that resolves to the script' full urlfigure - shows the result page generated if you point your browser at this script figure - simple web page from cgi script installing cgi scripts if you are running the local web server described at the start of this no extra installation steps are required to make this example workand you can safely skip most of this section if you want to put cgi scripts on another serverthoughthere are few pragmatic details you may need to know about this section provides brief overview of common cgi configuration details for reference like html filescgi scripts are simple text files that you can either create on your local machine and upload to the server by ftp or write with text editor running directly on the server machine (perhaps using telnet or ssh clienthoweverbecause cgi scripts are run as programsthey have some unique installation requirements that differ from simple html files in particularthey usually must be stored and named speciallyand they must be configured as programs that are executable by arbitrary users depending on your needscgi scripts also may require help finding imported +notice that the script does not generate the enclosing and tags included in the static html file of the prior section strictly speakingit should--html without such tags is technically invalid but because all commonly used browsers simply ignore the omissionwe'll take some liberties with html syntax in this book if you need to care about such thingsconsult html references for more formal details server-side scripting
5,709
being uploaded let' look at each install constraint in more depthdirectory and filename conventions firstcgi scripts need to be placed in directory that your web server recognizes as program directoryand they need to be given name that your server recognizes as cgi script in the local web server we're using in this scripts need to be placed in special cgi-bin subdirectory and be named with py extension on the server used for this book' second editioncgi scripts instead were stored in the user' public_html directory just like html filesbut they required filename ending in cginot py some servers may allow other suffixes and program directoriesthis varies widely and can sometimes be configured per server or per user execution conventions because they must be executed by the web server on behalf of arbitrary users on the webcgi script files may also need to be given executable file permissions to mark them as programs and be made executable by others againa shell command chmod filename does the trick on most servers under some serverscgi scripts also need the special #line at the topto identify the python interpreter that runs the file' code the text after the #in the first line simply gives the directory path to the python executable on your server machine see for more details on this special first lineand be sure to check your server' conventions for more details on non-unix platforms some servers may expect this lineeven outside unix most of the cgi scripts in this book include the #line just in case they will ever be run on unix-like platformsunder our locally running web server on windowsthis first line is simply ignored as python comment one subtlety worth notingas we saw earlier in the bookthe special first line in executable text files can normally contain either hardcoded path to the python interpreter ( #!/usr/bin/pythonor an invocation of the env program ( #!/usr/bin/env python)which deduces where python lives from environment variable settings ( your $paththe env trick is less useful in cgi scriptsthoughbecause their environment settings may be those of the user "nobody(not your own)as explained in the next paragraph module search path configuration (optionalsome http servers may run cgi scripts with the username "nobodyfor security reasons (this limits the user' access to the server machinethat' why files you publish on the web must have special permission settings that make them accessible to other users it also means that some cgi scripts can' rely on the python module search path to be configured in any particular way as you've learned by nowthe module path is normally initialized from the user' pythonpath setting and pth filesplus defaults which normally include the current working directory climbing the cgi learning curve
5,710
when cgi script runs before you puzzle over this too hardyou should know that this is often not concern in practice because python usually searches the current directory for imported modules by defaultthis is not an issue if all of your scripts and any modules and packages they use are stored in your web directoryand your web server launches cgi scripts in the directory in which they reside but if the module lives elsewhereyou may need to modify the sys path list in your scripts to adjust the search path manually before imports--for instancewith sys path append(dir namecallsindex assignmentsand so on end-of-line conventions (optionalon some unix (and linuxserversyou might also have to make sure that your script text files follow the unix end-of-line convention (\ )not dos (\ \nthis isn' an issue if you edit and debug right on the server (or on another unix machineor ftp files one by one in text mode but if you edit and upload your scripts from pc to unix server in tar file (or in ftp binary mode)you may need to convert end-of-lines after the upload for instancethe server that was used for the second edition of this text returns default error page for scripts whose end-of-lines are in dos format see for techniques and note on automated end-of-line converter scripts unbuffered output streams (optionalunder some serversthe print call statement may buffer its output if you have long-running cgi scriptto avoid making the user wait to see resultsyou may wish to manually flush your printed text (call sys stdout flush()or run your python scripts in unbuffered mode recall from that you can make streams unbuffered by running with the - command-line flag or by setting your pythonunbuffered environment variable to nonempty value to use - in the cgi worldtry using first line on unix-like platforms like #!usr/bin/python - in typical usageoutput buffering is not usually factor on some servers and clientsthoughthis may be resolution for empty reply pagesor premature end-of-script header errors--the client may time out before the buffered output stream is sent (though more commonlythese cases reflect genuine program errors in your scriptthis installation process may sound bit complex at first glancebut much of it is server-dependentand it' not bad once you've worked through it on your own it' only concern at install time and can usually be automated to some extent with python scripts run on the server to summarizemost python cgi scripts are text files of python codewhichare named according to your web server' conventions ( file pyare stored in directory recognized by your web server ( cgi-bin/are given executable file permissions if required ( chmod file py server-side scripting
5,711
configure sys path only if needed to see modules in other directories use unix end-of-line conventions if your server rejects dos format flush output buffers if requiredor to send portions of the reply periodically even if you must use server machine configured by someone elsemost of the machine' conventions should be easy to root out during normal debugging cycle as usualyou should consult the conventions for any machine to which you plan to copy these example files finding python on remote servers one last install pointereven though python doesn' have to be installed on any clients in the context of server-side web applicationit does have to exist on the server machine where your cgi scripts are expected to run if you're running your own server with either the webserver py script we met earlier or an open source server such as apachethis is nonissue but if you are using web server that you did not configure yourselfyou must be sure that python lives on that machine moreoveryou need to find where it is on that machine so that you can specify its path in the #line at the top of your script if you are not sure if or where python lives on your server machinehere are some tipsespecially on unix systemsyou should first assume that python lives in standard place ( /usr/local/bin/python)type python (or which pythonin shell window and see if it works chances are that python already lives on such machines if you have telnet or ssh access on your servera unix find command starting at /usr may help if your server runs linuxyou're probably set to go python ships as standard part of linux distributions these daysand many websites and internet service providers (ispsrun the linux operating systemat such sitespython probably already lives at /usr/bin/python in other environments where you cannot control the server machine yourselfit may be harder to obtain access to an already installed python if soyou can relocate your site to server that does have python installedtalk your isp into installing python on the machine you're trying to useor install python on the server machine yourself if your isp is unsympathetic to your need for python and you are willing to relocate your site to one that isyou can find lists of python-friendly isps by searching the web and if you choose to install python on your server machine yourselfbe sure to check out the python world' support for frozen binaries--with ityou can create single executable program file that contains the entire python interpreteras well as all the standard library modules assuming compatible machinessuch frozen interpreter might be uploaded to your web account by ftp in single stepand it won' require climbing the cgi learning curve
5,712
systems can produce frozen python binary finallyto run this book' examplesmake sure the python you find or install is python xnot python as mentioned earliermany commercial isps support the latter but not the former as ' writing this fourth editionbut this is expected to change over time if you do locate commercial isp with supportyou should be able to upload your files by ftp and work by ssh or telnet you may also be able to run this webserver py script on the remote machinethough you may need to avoid using the standard port depending on how much control your account affords adding pictures and generating tables let' get back to writing server-side code as anyone who' ever surfed the web knowsweb pages usually consist of more than simple text example - is python cgi script that prints an html tag in its output to produce graphic image in the client browser this example isn' very python-specificbut note that just as for simple html filesthe image file (ppsmall gifone level up from the script filelives on and is downloaded from the server machine when the browser interprets the output of this script to render the reply page (even if the server' machine is the same as the client'sexample - pp \internet\web\cgi-bin\tutor py #!/usr/bin/python text """content-typetext/html cgi second cgi script hellocgi world""print(textnotice the use of the triple-quoted string block herethe entire html string is sent to the browser in one fell swoopwith the print call statement at the end be sure that the blank line between the content-type header and the first html is truly blank in the string (it may fail in some browsers if you have any spaces or tabs on that lineif both client and server are functionala page that looks like figure - will be generated when this script is referenced and run so farour cgi scripts have been putting out canned html that could have just as easily been stored in an html file but because cgi scripts are executable programsthey can also be used to generate html on the flydynamically--evenpossiblyin response to particular set of user inputs sent to the script that' the whole purpose server-side scripting
5,713
of cgi scriptsafter all let' start using this to better advantage nowand write python script that builds up response html programmaticallylisted in example - example - pp \internet\web\cgi-bin\tutor py #!/usr/bin/python print("""content-typetext/html cgi third cgi script hellocgi world"""for in range( )print(''for in range( )print('% % (ij)print(''print("""""despite all the tagsthis really is python code--the tutor py script uses triple-quoted strings to embed blocks of html again but this timethe script also uses nested python climbing the cgi learning curve
5,714
cificallyit emits html to lay out two-dimensional table in the middle of pageas shown in figure - figure - page with table generated by tutor py each row in the table displays "row columnpairas generated by the executing python script if you're curious how the generated html looksselect your browser' view source option after you've accessed this page it' single html page composed of the html generated by the first print in the scriptthen the for loopsand finally the last print in other wordsthe concatenation of this script' output is an html document with headers table tags the script in example - generates html table tags againwe're not out to learn html herebut we'll take quick look just so that you can make sense of this book' examples tables are declared by the text between and tags in html typicallya table' text in turn declares the contents of each table row between and tags and each column within row between and tags the loops in our script build up html to declare five rows of four columns each by printing the appropriate tagswith the current row and column number as column values for instancehere is part of the script' outputdefining the first two rows (to see the full outputrun the script standalone from system command lineor select your browser' view source option) server-side scripting
5,715
other table tags and options let us specify row title ()lay out bordersand so on we'll use more table syntax to lay out forms in uniform fashion later in this tutorial adding user interaction cgi scripts are great at generating html on the fly like thisbut they are also commonly used to implement interaction with user typing at web browser as described earlier in this web interactions usually involve two-step process and two distinct web pagesyou fill out an input form page and press submitand reply page eventually comes back in betweena cgi script processes the form input submission page that description sounds simple enoughbut the process of collecting user inputs requires an understanding of special html taglet' look at the implementation of simple web interaction to see forms at work firstwe need to define form page for the user to fill outas shown in example - example - pp \internet\web\tutor html cgi first user interactionforms enter your nameclimbing the cgi learning curve
5,716
from script as wellwhen this file is accessedall the text between its and tags generates the input fields and submit button shown in figure - figure - simple form page generated by tutor html more on form tags we won' go into all the details behind coding html formsbut few highlights are worth underscoring the following occurs within form' html codeform handler action the form' action option gives the url of cgi script that will be invoked to process submitted form data this is the link from form to its handler program-in this casea program called tutor py in the cgi-bin subdirectory of the locally running server' working directory the action option is the equivalent of command options in tkinter buttons--it' where callback handler (herea remote handler scriptis registered to the browser and server input fields input controls are specified with nested tags in this exampleinput tags have two key options the type option accepts values such as text for text fields and submit for submit button (which sends data to the server and is labeled "submit queryby defaultthe name option is the hook used to identify the entered value by keyonce all the form data reaches the server for instancethe server-side cgi script we'll see in moment uses the string user as key to get the data typed into this form' text field as we'll see in later examplesother input tag options can specify initial values (value= )display-only mode (readonly)and so on as we'll also see laterother server-side scripting
5,717
in pages (type=hidden)reinitializes fields (type=reset)or makes multiple-choice buttons (type=checkboxsubmission methodget and post forms also include method option to specify the encoding style to be used to send data over socket to the target server machine herewe use the post stylewhich contacts the server and then ships it stream of user input data in separate transmission over the socket an alternative get style ships input information to the server in single transmission step by appending user inputs to the query string at the end of the url used to invoke the scriptusually after character query parameters were introduced earlier when we met urlswe will put them to use later in this section with getinputs typically show up on the server in environment variables or as arguments in the command line used to start the script with postthey must be read from standard input and decoded because the get method appends inputs to urlsit allows users to bookmark actions with parameters for later submission ( link to retail sitetogether with the name of particular item)post is very generally meant for sending data that is to be submitted once ( comment textthe get method is usually considered more efficientbut it may be subject to length limits in the operating system and is less secure (parameters may be recorded in server logsfor instancepost can handle larger inputs and may be more secure in some scenariosbut it requires an extra transmission luckilypython' cgi module transparently handles either encoding styleso our cgi scripts don' normally need to know or care which is used notice that the action url in this example' form spells out the full address for illustration because the browser remembers where the enclosing html page came fromit works the same with just the script' filenameas shown in example - example - pp \internet\web\tutor -minimal html cgi first user interactionforms enter your nameit may help to remember that urls embedded in form action tags and hyperlinks are directions to the browser firstnot to the script the tutor py script itself doesn' care which url form is used to trigger it--minimal or complete in factall parts of url climbing the cgi learning curve
5,718
as the browser knows which server to contactthe url will work on the other handurls submitted outside of page ( typed into browser' address field or sent to the python urllib request module we'll revisit laterusually must be completely specifiedbecause there is no notion of prior page response script so farwe've created only static page with an input field but the submit button on this page is loaded to work magic when pressedit triggers the possibly remote program whose url is listed in the form' action optionand passes this program the input data typed by the useraccording to the form' method encoding style option on the servera python script is started to handle the form' input data while the user waits for reply on the clientthat script is shown in example - example - pp \internet\web\cgi-bin\tutor py #!/usr/bin/python ""runs on the serverreads form inputprints htmlurl=""import cgi form cgi fieldstorage(print('content-typetext/html'parse form data plus blank line html ""tutor py greetings % ""if not 'userin formprint(html 'who are you?'elseprint(html ('hello% form['user'value)as beforethis python cgi script prints html to generate response page in the client' browser but this script does bit moreit also uses the standard cgi module to parse the input data entered by the user on the prior web page (see figure - luckilythis is automatic in pythona call to the standard library cgi module' field storage class does all the work of extracting form data from the input stream and environment variablesregardless of how that data was passed--in post style stream or in get style parameters appended to the url inputs sent in both styles look the same to python scripts server-side scripting
5,719
when it is calledwe get back an object that looks like dictionary--user input fields from the form (or urlshow up as values of keys in this object for examplein the scriptform['user'is an object whose value attribute is string containing the text typed into the form' text field if you flip back to the form page' htmlyou'll notice that the input field' name option was user--the name in the form' html has become key we use to fetch the input' value from dictionary the object returned by fieldstorage supports other dictionary operationstoo--for instancethe in expression may be used to check whether field is present in the input data before exitingthis script prints html to produce result page that echoes back what the user typed into the form two string-formatting expressions (%are used to insert the input text into reply stringand the reply string into the triple-quoted html string block the body of the script' output looks like thistutor py greetings helloking arthur in browserthe output is rendered into page like the one in figure - figure - tutor py result for parameters in form passing parameters in urls notice that the url address of the script that generated this page shows up at the top of the browser we didn' type this url itself--it came from the action tag of the prior page' form html howevernothing is stopping us from typing the script' url explicitly in our browser' address field to invoke the scriptjust as we did for our earlier cgi script and html file examples climbing the cgi learning curve
5,720
pagethat isif we type the cgi script' url ourselveshow does the input field get filled inearlierwhen we talked about url formatsi mentioned that the get encoding scheme tacks input parameters onto the end of urls when we type script addresses explicitlywe can also append input values on the end of urlswhere they serve the same purpose as fields in forms moreoverthe python cgi module makes url and form inputs look identical to scripts for instancewe can skip filling out the input form page completely and directly invoke our tutor py script by visiting url of this form (type this in your browser' address field)in this urla value for the input named user is specified explicitlyas if the user had filled out the input page when called this waythe only constraint is that the parameter name user must match the name expected by the script (and hardcoded in the form' htmlwe use just one parameter herebut in generalurl parameters are typically introduced with and are followed by one or more name=value assignmentsseparated by characters if there is more than one figure - shows the response page we get after typing url with explicit inputs figure - tutor py result for parameters in url in facthtml forms that specify the get encoding style also cause inputs to be added to urls this way try changing example - to use method=getand submit the form-the name input in the form shows up as query parameter in the reply page address fieldjust like the url we manually entered in figure - forms can use the post or get style manually typed urls with parameters use get generallyany cgi script can be invoked either by filling out and submitting form page or by passing inputs at the end of url although hand-coding parameters in server-side scripting
5,721
programs can automate the construction process when cgi scripts are invoked with explicit input parameters this wayit' not too difficult to see their similarity to functionsalbeit ones that live remotely on the net passing data to scripts in urls is similar to keyword arguments in python functionsboth operationally and syntactically in factsome advanced web frameworks such as zope make the relationship between urls and python function calls even more literalurls become more direct calls to python functions incidentallyif you clear out the name input field in the form input page ( make it emptyand press submitthe user name field becomes empty more accuratelythe browser may not send this field along with the form data at alleven though it is listed in the form layout html the cgi script detects such missing field with the dictionary in expression and produces the page captured in figure - in response figure - an empty name field producing an error page in generalcgi scripts must check to see whether any inputs are missingpartly because they might not be typed by user in the formbut also because there may be no form at all--input fields might not be tacked onto the end of an explicitly typed or constructed get-style url for instanceif we type the script' url without any parameters at all--by omitting the text from the and beyondand visiting tutor py with an explicitly entered url--we get this same error response page since we can invoke any cgi through form or urlscripts must anticipate both scenarios testing outside browsers with the module urllib request once we understand how to send inputs to forms as query string parameters at the end of urls like thisthe python urllib request module we met in and becomes even more useful recall that this module allows us to fetch the reply generated climbing the cgi learning curve
5,722
its contents but when it names cgi scriptthe effect is to run the remote script and fetch its output this notion opens the door to web serviceswhich generate useful xml in response to input parametersin simpler rolesthis allows us to test remote scripts for examplewe can trigger the script in example - directlywithout either going through the tutor html web page or typing url in browser' address fieldc:\pp \internet\webpython from urllib request import urlopen reply urlopen(reply 'tutor py\ngreetings\ \nhellobrian \ \nprint(reply decode()tutor py greetings hellobrian url conn urlopen(urlreply conn read(print(reply decode()tutor py greetings who are yourecall from that urllib request urlopen gives us file object connected to the generated reply stream reading this file' output returns the html that would normally be intercepted by web browser and rendered into reply page the reply comes off of the underlying socket as bytes in xbut can be decoded to str strings as needed when fetched directly this waythe html reply can be parsed with python text processing toolsincluding string methods like split and findthe re pattern-matching moduleor the html parser html parsing module--all tools we'll explore in extracting text from the reply like this is sometimes informally called screen scraping-- way to use website content in other programs screen scraping is an alternative to more complex web services frameworksthough brittle onesmall changes in the page' format can often break scrapers that rely on it the reply text can also be simply inspected--urllib request allows us to test cgi scripts from the python interactive prompt or other scriptsinstead of browser more generallythis technique allows us to use server-side script as sort of function call for instancea client-side gui can call the cgi script and parse the generated reply page similarlya cgi script that updates database may be invoked programmatically with urllib requestoutside the context of an input form page this also opens the server-side scripting
5,723
remote machineand compare their reply text to the expected output ss we'll see url lib request in action again in later examples before we move onhere are few advanced urllib request usage notes firstthis module also supports proxiesalternative transmission modesthe client side of secure httpscookiesredirectionsand more for instanceproxies are supported transparently with environment variables or system settingsor by using proxyhandler objects in this module (see its documentation for details and examplesmoreoveralthough it normally doesn' make difference to python scriptsit is possible to send parameters in both the get and the put submission modes described earlier with urllib request the get modewith parameters in the query string at the end of url as shown in the prior listingis used by default to invoke postpass parameters in as separate argumentfrom urllib request import urlopen from urllib parse import urlencode params urlencode({'user''brian'}params 'user=brianprint(urlopen('tutor py greetings hellobrian finallyif your web application depends on client-side cookies (discussed laterthese are supported by urllib request automaticallyusing python' standard library cookie support to store cookies locallyand later return them to the server it also supports redirectionauthenticationand morethe client side of secure http transmissions (httpsis supported if your computer has secure sockets support available (most dosee the python library manual for details we'll explore both cookies later in this and introduce secure https in the next using tables to lay out forms now let' move on to something bit more realistic in most cgi applicationsinput pages are composed of multiple fields when there is more than oneinput labels and fields are typically laid out in tableto give the form well-structured appearance the html file in example - defines form with two input fields ss if your job description includes extensive testing of server-side scriptsyou may also want to explore twilla python-based system that provides little language for scripting the client-side interface to web applications search the web for details climbing the cgi learning curve
5,724
cgi second user interactiontables enter your nameenter your agethe tag defines column like but also tags it as header columnwhich generally means it is rendered in bold font by placing the input fields and labels in table like thiswe get an input page like that shown in figure - labels and inputs are automatically lined up vertically in columnsmuch as they were by the tkinter gui geometry managers we met earlier in this book figure - form laid out with table tags server-side scripting
5,725
causes the script in example - to be executed on the server machinewith the inputs typed by the user example - pp \internet\web\cgi-bin\tutor py #!/usr/bin/python ""runs on the serverreads form inputprints htmlurl ""import cgisys sys stderr sys stdout form cgi fieldstorage(print('content-typetext/html\ 'errors to browser parse form data plus blank line class dummydef __init__(selfs)self value form {'user'dummy('bob')'age':dummy(' ')html ""tutor py greetings % % % ""if not 'userin formline 'who are you?elseline 'hello% form['user'value line "you're talking to % server sys platform line "if 'agein formtryline "your age squared is % !(int(form['age'value* exceptline "sorryi can' compute % * form['age'value print(html (line line line )the table layout comes from the html filenot from this python cgi script in factthis script doesn' do much new--it uses string formatting to plug input values into the response page' html triple-quoted template string as beforethis time with one line per input field when this script is run by submitting the input form pageits output produces the new reply page shown in figure - climbing the cgi learning curve
5,726
as usualwe can pass parameters to this cgi script at the end of urltoo figure - shows the page we get when passing user and age explicitly in this urlfigure - reply page from tutor py for parameters in url notice that we have two parameters after the this timewe separate them with also note that we've specified blank space in the user value with this is common url encoding convention on the server sidethe is automatically replaced with space again it' also part of the standard escape rule for url stringswhich we'll revisit later server-side scripting
5,727
highlight few new coding tricks worth notingespecially regarding cgi script debugging and security let' take quick look converting strings in cgi scripts just for funthe script echoes back the name of the server platform by fetching sys platform along with the square of the age input field notice that the age input' value must be converted to an integer with the built-in int functionin the cgi worldall inputs arrive as strings we could also convert to an integer with the built-in eval function conversion (and othererrors are trapped gracefully in try statement to yield an error lineinstead of letting our script die but you should never use eval to convert strings that were sent over the internetlike the age field in this exampleunless you can be absolutely sure that the string does not contain even potentially malicious code for instanceif this example were available on the general internetit' not impossible that someone could type value into the age field (or append an age parameter to the urlwith value that invokes system shell command given the appropriate context and process permissionswhen passed to evalsuch string might delete all the files in your server script directoryor worseunless you run cgi scripts in processes with limited permissions and machine accessstrings read off the web can be dangerous to run as code in cgi scripting you should never pass them to dynamic coding tools like eval and execor to tools that run arbitrary shell commands such as os popen and os systemunless you can be sure that they are safe always use simpler tools for numeric conversion like int and floatwhich recognize only numbersnot arbitrary python code debugging cgi scripts errors happeneven in the brave new world of the internet generally speakingdebugging cgi scripts can be much more difficult than debugging programs that run on your local machine not only do errors occur on remote machinebut scripts generally won' run without the context implied by the cgi model the script in example - demonstrates the following two common debugging trickserror message trapping this script assigns sys stderr to sys stdout so that python error messages wind up being displayed in the response page in the browser normallypython error messages are written to stderrwhich generally causes them to show up in the web server' console window or logfile to route them to the browserwe must make stderr reference the same file object as stdout (which is connected to the browser in cgi scriptsif we don' do this assignmentpython errorsincluding program errors in our scriptnever show up in the browser climbing the cgi learning curve
5,728
the dummy class definitioncommented out in this final versionwas used to debug the script before it was installed on the net besides not seeing stderr messages by defaultcgi scripts also assume an enclosing context that does not exist if they are tested outside the cgi environment for instanceif run from the system command linethis script has no form input data uncomment this code to test from the system command line the dummy class masquerades as parsed form field objectand form is assigned dictionary containing two form field objects the net effect is that form will be plug-and-play compatible with the result of cgi fieldstorage call as usual in pythonobject interfacesnot datatypesare all we must adhere to here are few general tips for debugging your server-side cgi scriptsrun the script from the command line it probably won' generate html as isbut running it standalone will detect any syntax errors in your code recall that python command line can run source code files regardless of their extensionfor examplepython somescript cgi works fine assign sys stderr to sys stdout as early as possible in your script this will generally make the text of python error messages and stack dumps appear in your client browser when accessing the scriptinstead of the web server' console window or logs short of wading through server logs or manual exception handlingthis may be the only way to see the text of error messages after your script aborts mock up inputs to simulate the enclosing cgi context for instancedefine classes that mimic the cgi inputs interface (as done with the dummy class in this scriptto view the script' output for various test cases by running it from the system command line |setting environment variables to mimic form or url inputs sometimes helpstoo (we'll see how later in this call utilities to display cgi context in the browser the cgi module includes utility functions that send formatted dump of cgi environment variables and input values to the browserto view in reply page for instancecgi print_form(formprints all the input parameters sent from the clientand cgi test(prints environment variablesthe formthe directoryand more sometimes this is enough to resolve connection or input problems we'll use some of these in the webmail case study in the next show exceptions you catchprint tracebacks if you catch an exception that python raisesthe python error message won' be printed to stderr (that is normal behaviorin such casesit' up to your script to |this technique isn' unique to cgi scriptsby the way in we briefly met systems that embed python code inside htmlsuch as python server pages there is no good way to test such code outside the context of the enclosing system without extracting the embedded python code (perhaps by using the html parser html parser that comes with pythoncovered in and running it with passed-in mock-up of the api that it will eventually use server-side scripting
5,729
available in the built-in sys modulefrom sys exc_info(in additionpython' traceback module can be used to manually generate stack traces on your reply page for errorstracebacks show source-code lines active when an exception occurred we'll use this later in the error page in pymailcgi (add debugging prints you can always insert tracing print statements in your codejust as in normal python programs be sure you print the content-type header line firstthoughor your prints may not show up on the reply page in the worst caseyou can also generate debugging and trace messages by opening and writing to local text file on the serverprovided you access that file laterthis avoids having to format the trace messages according to html reply stream conventions run it live of courseonce your script is at least half workingyour best bet is likely to start running it live on the serverwith real inputs coming from browser running server locally on your machineas we're doing in this can help by making changes go faster as you test adding common input devices so farwe've been typing inputs into text fields html forms support handful of input controls (what we' call widgets in the traditional gui worldfor collecting user inputs let' look at cgi program that shows all the common input controls at once as usualwe define both an html file to lay out the form page and python cgi script to process its inputs and generate response the html file is presented in example - example - pp \internet\web\tutor html cgi common input devices please complete the following form and click send nameshoe sizesmall medium large occupationclimbing the cgi learning curve
5,730
developer manager student evangelist other political affiliationspythonista perlmonger tcler commentsenter text here when rendered by browserthe page in figure - appears figure - input form page generated by tutor html server-side scripting
5,731
input area all have name option in the html filewhich identifies their selected value in the data sent from client to server when we fill out this form and click the send submit buttonthe script in example - runs on the server to process all the input data typed or selected in the form example - pp \internet\web\cgi-bin\tutor py #!/usr/bin/python ""runs on the serverreads form inputprints html ""import cgisys form cgi fieldstorage(print("content-typetext/html"parse form data plus blank line html ""tutor py greetings your name is %(name) you wear rather %(shoesize) shoes your current job%(job) you program in %(language) you also said%(comment) ""data {for field in ('name''shoesize''job''language''comment')if not field in formdata[field'(unknown)elseif not isinstance(form[field]list)data[fieldform[fieldvalue elsevalues [ value for in form[field]data[fieldand join(valuesprint(html datathis python script doesn' do muchit mostly just copies form field information into dictionary called data so that it can be easily inserted into the triple-quoted response template string few of its techniques merit explanationfield validation as usualwe need to check all expected fields to see whether they really are present in the input datausing the dictionary in expression any or all of the input fields may be missing if they weren' entered on the form or appended to an explicit url climbing the cgi learning curve
5,732
we're using dictionary key references in the format string this time--recall that (name) means pull out the value for the key name in the data dictionary and perform to-string conversion on its value multiple-choice fields we're also testing the type of all the expected fieldsvalues to see whether they arrive as list rather than the usual string values of multiple-choice input controlslike the language choice field in this input pageare returned from cgi fieldstorage as list of objects with value attributesrather than simple single object with value this script copies simple field values to the dictionary verbatimbut it uses list comprehension to collect the value fields of multiple-choice selectionsand the string join method to construct single string with an and inserted between each selection value ( python and tclthe script' list comprehension is equivalent to the call map(lambda xx valueform[field]not shown herethe fieldstorage object' alternative methods getfirst and getlist can also be used to treat fields as single and multiple itemswhether they were sent that way or not (see python' library manualsand as we'll see laterbesides simple strings and listsa third type of form input object is returned for fields that specify file uploads to be robustthe script should really also escape the echoed text inserted into the html replylest it contain html operatorswe will discuss escapes in detail later when the form page is filled out and submittedthe script creates the response shown in figure - --essentially just formatted echo of what was sent changing input layouts suppose that you've written system like that in the prior sectionand your usersclientsand significant other start complaining that the input form is difficult to read don' worry because the cgi model naturally separates the user interface (the html input page definitionfrom the processing logic (the cgi script)it' completely painless to change the form' layout simply modify the html filethere' no need to change the cgi code at all for instanceexample - contains new definition of the input that uses tables bit differently to provide nicer layout with borders example - pp \internet\web\tutor html cgi common input devicesalternative layout use the same tutor py server side scriptbut change the layout of the form itself notice the separation of user interface and processing logic herethe cgi script is independent of the html used to interact with the user/client server-side scripting
5,733
please complete the following form and click submit nameshoe sizesmall medium large occupationdeveloper manager student evangelist other political affiliationspythonista perlmonger tcler commentsenter spam here climbing the cgi learning curve
5,734
when we visit this alternative page with browserwe get the interface shown in figure - figure - form page created by tutor html nowbefore you go blind trying to detect the differences in this and the prior html filei should note that the html differences that produce this page are much less important for this book than the fact that the action fields in these two pagesforms reference identical urls pressing this version' submit button triggers the exact same and totally unchanged python cgi script againtutor py (example - that isscripts are completely independent of both the transmission mode (url query parameters of form fieldsand the layout of the user interface used to send them information changes in the response page require changing the scriptof coursebecause the html of the reply page is still embedded in the cgi script but we can change the input page' html as much as we like without affecting the server-side python code figure - shows the response page produced by the script this time around server-side scripting
5,735
keeping display and logic separate in factthis illustrates an important point in the design of larger websitesif we are careful to keep the html and script code separatewe get useful division of display and logic--each part can be worked on independentlyby people with different skill sets web page designersfor examplecan work on the display layoutwhile programmers can code business logic although this section' example is fairly smallit already benefits from this separation for the input page in some casesthe separation is harder to accomplishbecause our example scripts embed the html of reply pages with just little more workthoughwe can usually split the reply html off into separate files that can also be developed independently of the script' logic the html string in tutor py (example - )for instancemight be stored in text file and loaded by the script when run in larger systemstools such as server-side html templating languages help make the division of display and logic even easier to achieve the python server pages system and frameworks such as zope and djangofor instancepromote the separation of display and logic by providing reply page description languages that are expanded to include portions generated by separate python program logic in senseserver-side templating languages embed python in html--the opposite of cgi scripts that embed html in python--and may provide cleaner division of laborprovided the python climbing the cgi learning curve
5,736
be used for separation of layout and login in the guis we studied earlier in this bookbut they also usually require larger frameworks or models to achieve passing parameters in hardcoded urls earlierwe passed parameters to cgi scripts by listing them at the end of url typed into the browser' address field--in the query string parameters part of the urlafter the but there' nothing sacred about the browser' address field in particularnothing is stopping us from using the same url syntax in hyperlinks that we hardcode or generate in web page definitions for examplethe web page from example - defines three hyperlinks (the text between the and tags)which trigger our original tutor py script again (example - )but with three different precoded sets of parameters example - pp \internet\web\tutor html cgi common input devicesurl parameters this demo invokes the tutor py server-side script againbut hardcodes input data to the end of the script' urlwithin simple hyperlink (instead of packaging up form' inputsclick your browser' "show page sourcebutton to view the links associated with each list item below this is really more about cgi than pythonbut notice that python' cgi module handles both this form of input (which is also produced by get form actions)as well as post-ed formsthey look the same to the python cgi script in other wordscgi module users are independent of the method used to submit data also notice that urls with appended input values like this can be generated as part of the page output by another cgi scriptto direct next user click to the right place and contexttogether with type 'hiddeninput fieldsthey provide one way to save state between clicks send bobsmall send tompython server-side scripting
5,737
is fully specifiedbut all work similarly (againthe target script doesn' carewhen we visit this file' urlwe see the page shown in figure - it' mostly just page for launching canned calls to the cgi script ( 've reduced the text font size here to fit in this bookrun this live if you have trouble reading it here figure - hyperlinks page created by tutor html clicking on this page' second link creates the response page in figure - this link invokes the cgi scriptwith the name parameter set to "tomand the language parameter set to "python,simply because those parameters and values are hardcoded in the url listed in the html for the second hyperlink as suchhyperlinks with parameters like this are sometimes known as stateful links--they automatically direct the next script' operation the net effect is exactly as if we had manually typed the line shown at the top of the browser in figure - notice that many fields are missing herethe tutor py script is smart enough to detect and handle missing fields and generate an unknown message in the reply page it' also worth pointing out that we're reusing the python cgi script again the script itself is completely independent of both the user interface format of the submission pageas well as the technique used to invoke it--from submitted form or hardcoded url with query parameters by separating such user interface details from processing logiccgi scripts become reusable software componentsat least within the context of the cgi environment climbing the cgi learning curve
5,738
the query parameters in the urls embedded in example - were hardcoded in the page' html but such urls can also be generated automatically by cgi script as part of reply page in order to provide inputs to the script that implements next step in user interaction they are simple way for web-based applications to "rememberthings for the duration of session hidden form fieldsup nextserve some of the same purposes passing parameters in hidden form fields similar in spirit to the prior sectioninputs for scripts can also be hardcoded in page' html as hidden input fields such fields are not displayed in the pagebut are transmitted back to the server when the form is submitted example - for instanceallows job field to be enteredbut fills in name and language parameters automatically as hidden input fields example - pp \internet\web\tutor html cgi common input deviceshidden form fields this demo invokes the tutor py server-side script againbut hardcodes input data in the form itself as hidden input fieldsinstead of as parameters at the end of url hyperlinks as beforethe text of this formincluding the hidden fieldscan be generated as part of the page output by another cgi server-side scripting
5,739
form fields provide another way to save state between pages <input type=hidden name=name value=sue<input type=text name=job value="enter job"when example - is opened in browserwe get the input page in figure - figure - tutor html input form page when submittingwe trigger our original tutor py script once again (example - )but some of the inputs have been provided for us as hidden fields the reply page is captured in figure - much like the query parameters of the prior sectionhere again we've hardcoded and embedded the next page' inputs in the input page' html itself unlike query parametershidden input fields don' show up in the next page' address like query parameterssuch input fields can also be generated on the fly as part of the reply from cgi script when they arethey serve as inputs for the next pageand so are sort of memory--session state passed from one script to the next to fully understand how and why this is necessarywe need to next take short diversion into state retention alternatives climbing the cgi learning curve
5,740
saving state information in cgi scripts one of the most unusual aspects of the basic cgi modeland one of its starkest contrasts to the gui programming techniques we studied in the prior part of this bookis that cgi scripts are stateless--each is standalone programnormally run autonomouslywith no knowledge of any other scripts that may run before or after there is no notion of things such as global variables or objects that outlive single step of interaction and retain context each script begins from scratchwith no memory of where the prior left off this makes web servers simple and robust-- buggy cgi script won' interfere with the server process in facta flaw in cgi script generally affects only the single page it implementsnot the entire web-based application but this is very different model from callback-handler functions in single process guiand it requires extra work to remember things longer than single script' execution lack of state retention hasn' mattered in our simple examples so farbut larger systems are usually composed of multiple user interaction steps and many scriptsand they need way to keep track of information gathered along the way as suggested in the server-side scripting
5,741
input pages sent as replies are two simple ways for cgi script to pass data to the next script in the application when clicked or submittedsuch parameters send preprogrammed selection or session information back to another server-side handler script in sensethe content of the generated reply page itself becomes the memory space of the application for examplea site that lets you read your email may present you with list of viewable email messagesimplemented in html as list of hyperlinks generated by another script each hyperlink might include the name of the message viewer scriptalong with parameters identifying the selected message numberemail server nameand so on-as much data as is needed to fetch the message associated with particular link retail site may instead serve up generated list of product linkseach of which triggers hardcoded hyperlink containing the product numberits priceand so on alternativelythe purchase page at retail site may embed the product selected in prior page as hidden form fields in factone of the main reasons for showing the techniques in the last two sections is that we're going to use them extensively in the larger case study in the next for instancewe'll use generated stateful urls with query parameters to implement lists of dynamically generated selections that "knowwhat to do when clicked hidden form fields will also be deployed to pass user login data to the next page' script from more general perspectiveboth techniques are ways to retain state information between pages--they can be used to direct the action of the next script to be run generating url parameters and hidden form fields works well for retaining state information across pages during single session of interaction some scenarios require morethough for instancewhat if we want to remember user' login name from session to sessionor what if we need to keep track of pages at our site visited by user in the pastbecause such information must be longer lived than the pages of single session of interactionquery parameters and hidden form fields won' suffice in some casesthe required state information might also be too large to embed in reply page' html in generalthere are variety of ways to pass or retain state information between cgi script executions and across sessions of interactionurl query parameters session state embedded in generated reply pages hidden form fields session state embedded in generated reply pages cookies smaller information stored on the client that may span sessions server-side databases larger information that might span sessions saving state information in cgi scripts
5,742
persistent processessession managementand so on we'll explore most of these in later examplesbut since this is core idea in server-side scriptinglet' take brief look at each of these in turn url query parameters we met these earlier in this hardcoded url parameters in dynamically generated hyperlinks embedded in input pages produced as replies by including both processing script name and input to itsuch links direct the operation of the next page when selected the parameters are transmitted from client to server automaticallyas part of get-style request coding query parameters is straightforward--print the correctly formatted url to standard output from your cgi script as part of the reply page (albeit following some escaping conventions we'll meet later in this here' an example drawn from the next webmail case studyscript "onviewlistlink pyuser 'bobmnum pswd 'xxxsite pop myisp netprint('view % (scriptuserpswdmnumsitemnum)the resulting url will have enough information to direct the next script when clickedview query parameters serve as memoryand they pass information between pages as suchthey are useful for retaining state across the pages of single session of interaction since each generated url may have different attached parametersthis scheme can provide context per user-selectable action each link in list of selectable alternativesfor examplemay have different implied action coded as different parameter value moreoverusers can bookmark link with parametersin order to return to specific state in an interaction because their state retention is lost when the page is abandonedthoughthey are not useful for remembering state from session to session moreoverthe data appended as url query parameters is generally visible to users and may appear in server logfilesin some applicationsit may have to be manually encrypted to avoid display or forgery hidden form input fields we met these in the prior section as wellhidden form input fields that are attached to form data and are embedded in reply web pagesbut are not displayed in web pages or their url addresses when the form is submittedall the hidden fields are transmitted server-side scripting
5,743
context for an entire input formnot particular hyperlink an already entered usernamepasswordor selectionfor instancecan be implied by the values of hidden fields in subsequently generated pages in terms of codehidden fields are generated by server-side scripts as part of the reply page' html and are later returned by the client with all of the form' input data previewing the next usage againprint('urlrootprint('msgnumprint('userprint('siteprint('pswdlike query parametershidden form fields can also serve as sort of memoryretaining state information from page to page also like query parametersbecause this kind of memory is embedded in the page itselfhidden fields are useful for state retention among the pages of single session of interactionbut not for data that spans multiple sessions and like both query parameters and cookies (up next)hidden form fields may be visible to users--though hidden in rendered pages and urlstheir values still are displayed if the page' raw html source code is displayed as resulthidden form fields are not secureencryption of the embedded data may again be required in some contexts to avoid display on the client or forgery in form submissions http "cookiescookiesan oextension to the http protocol underlying the web modelare way for server-side applications to directly store information on the client computer because this information is not embedded in the html of web pagesit outlives the pages of single session as suchcookies are ideal for remembering things that must span sessions things like usernames and preferencesfor exampleare prime cookie candidates-they will be available the next time the client visits our site howeverbecause cookies may have space limitationsare seen by some as intrusiveand can be disabled by users on the clientthey are not always well suited to general data storage needs they are often best used for small pieces of noncritical cross-session state informationand websites that aim for broad usage should generally still be able to operate if cookies are unavailable operationallyhttp cookies are strings of information stored on the client machine and transferred between client and server in http message headers server-side scripts generate http headers to request that cookie be stored on the client as part of the script' reply stream laterthe client web browser generates http headers that send back all the cookies matching the server and page being contacted in effectcookie saving state information in cgi scripts
5,744
it is contained in http headersnot in page' html moreovercookie data can be stored permanently on the clientand so it outlives both pages and interactive sessions for web application developerspython' standard library includes tools that simplify the task of sending and receivinghttp cookiejar does cookie handling for http clients that talk to web serversand the module http cookies simplifies the task of creating and receiving cookies in server-side scripts moreoverthe module urllib request we've studied earlier has support for opening urls with automatic cookie handling creating cookie web browsers such as firefox and internet explorer generally handle the client side of this protocolstoring and sending cookie data for the purpose of this we are mainly interested in cookie processing on the server cookies are created by sending special http headers at the start of the reply streamcontent-typetext/html set-cookiefoo=barthe full format of cookie' header is as followsset-cookiename=valueexpires=datepath=pathnamedomain=domainnamesecure the domain defaults to the hostname of the server that set the cookieand the path defaults to the path of the document or script that set the cookie--these are later matched by the client to know when to send cookie' value back to the server in pythoncookie creation is simplethe following in cgi script stores last-visited time cookieimport http cookiestime cook http cookies simplecookie(cook['visited'str(time time()print(cook output()print('content-typetext/html\ ' dictionary prints "set-cookievisited= the simplecookie call here creates dictionary-like cookie object whose keys are strings (the names of the cookies)and whose values are "morselobjects (describing the cookie' valuemorsels in turn are also dictionary-like objects with one key per cookie propertypath and domainexpires to give the cookie an expiration date (the default is the duration of the browser session)and so on morsels also have attributes--for instancekey and value give the name and value of the cookierespectively assigning string to cookie key automatically creates morsel from the stringand the cookie object' output method returns string suitable for use as an http headerprinting the object directly has the same effectdue to its __str__ operator overloading here is more comprehensive example of the interface in actionimport http cookiestime cooks http cookies simplecookie( server-side scripting
5,745
cooks['username''bobcooks['username']['path''/myscriptcooks['visited'value 'tue jun : : print(cooks['visited']set-cookievisited="tue jun : : print(cooksset-cookieusername=bobpath=/myscript set-cookievisited="tue jun : : receiving cookie nowwhen the client visits the page again in the futurethe cookie' data is sent back from the browser to the server in http headers againin the form "cookiename =value name =value for examplecookievisited= roughlythe browser client returns all cookies that match the requested server' domain name and path in the cgi script on the serverthe environment variable http_cookie contains the raw cookie data headers string uploaded from the clientit can be extracted in python as followsimport oshttp cookies cooks http cookies simplecookie(os environ get("http_cookie")vcook cooks get("visited" morsel dictionary if vcook !nonetime vcook value herethe simplecookie constructor call automatically parses the passed-in cookie data string into dictionary of morsel objectsas usualthe dictionary get method returns default none if key is absentand we use the morsel object' value attribute to extract the cookie' value string if sent using cookies in cgi scripts to help put these pieces togetherexample - lists cgi script that stores clientside cookie when first visited and receives and displays it on subsequent visits example - pp \internet\web\cgi-bin\cookies py ""create or use client-side cookie storing usernamethere is no input form data to parse in this example ""import http cookiesos cookstr os environ get("http_cookie"cookies http cookies simplecookie(cookstrusercook cookies get("user"fetch if sent if usercook =nonecreate first time saving state information in cgi scripts
5,746
print set-cookie hdr cookies['user''brianprint(cookiesgreeting 'his name shall be %scookies['user'elsegreeting 'welcome back%susercook value print('content-typetext/html\ 'print(greetingplus blank line now and the actual html assuming you are running this local web server from example - you can invoke this script with url such as your browser' address fieldor submit it interactively with the module url lib requestthe first time you visit the scriptthe script sets the cookie within its reply' headersand you'll see reply page with this messagehis name shall be set-cookieuser=brian thereafterrevisiting the script' url in the same browser session (use your browser' reload buttonproduces reply page with this messagewelcome backbrian this occurs because the client is sending the previously stored cookie value back to the scriptat least until you kill and restart your web browser--the default expiration of cookie is the end of browsing session in realistic programthis sort of structure might be used by the login page of web applicationa user would need to enter his name only once per browser session handling cookies with the urllib request module as mentioned earlierthe urllib request module provides an interface for reading the reply from urlbut it uses the http cookiejar module to also support storing and sending cookies on the client howeverit does not support cookies "out of the box for examplehere it is in action testing the last section' cookie-savvy script--cookies are not echoed back to the server when script is revisitedfrom urllib request import urlopen reply urlopen(print(replyb'his name shall be set-cookieuser=brian\nreply urlopen(print(replyb'his name shall be set-cookieuser=brian\nto support cookies with this module properlywe simply need to enable the cookiehandler classthe same is true for other optional extensions in this module againcontacting the prior section' scriptimport urllib request as urllib opener urllib build_opener(urllib httpcookieprocessor()urllib install_opener(opener server-side scripting
5,747
reply urllib urlopen(print(replyb'his name shall be set-cookieuser=brian\nreply urllib urlopen(print(replyb'welcome backbrian\nreply urllib urlopen(print(replyb'welcome backbrian\nthis works because urllib request mimics the cookie behavior of web browser on the client--it stores the cookie when so requested in the headers of script' replyand adds it to headers sent back to the same script on subsequent visits also just as in browserthe cookie is deleted if you exit python and start new session to rerun this code see the library manual for more on this module' interfaces although easy to usecookies have potential downsides for onethey may be subject to size limitations ( kb per cookie totaland per domain are one common limitfor anotherusers can disable cookies in most browsersmaking them less suited to critical data some even see them as intrusivebecause they can be abused to track user behavior (many sites simply require cookies to be turned onfinessing the issue completely finallybecause cookies are transmitted over the network between client and serverthey are still only as secure as the transmission stream itselfthis may be an issue for sensitive data if the page is not using secure http transmissions between client and server we'll explore secure cookies and server concepts in the next for more details on the cookie modules and the cookie protocol in generalsee python' library manualand search the web for resources it' not impossible that future mutations of html may provide similar storage solutions server-side databases for more industrial-strength state retentionpython scripts can employ full-blown database solutions in the server we will study these options in depth in python scripts have access to variety of server-side data storesincluding flat filespersistent object pickles and shelvesobject-oriented databases such as zodband relational sql-based databases such as mysqlpostgresqloracleand sqlite besides data storagesuch systems may provide advanced tools such as transaction commits and rollbacksconcurrent update synchronizationand more full-blown databases are the ultimate storage solution they can be used to represent state both between the pages of single session (by tagging the data with generated per-session keysand across multiple sessions (by storing data under per-user keysgiven user' login namefor examplecgi scripts can fetch all of the context we have gathered in the past about that user from the server-side database server-side databases saving state information in cgi scripts
5,748
databases outlive both pages and sessions because data is kept explicitlythere is no need to embed it within the query parameters or hidden form fields of reply pages because the data is kept on the serverthere is no need to store it on the client in cookies and because such schemes employ general-purpose databasesthey are not subject to the size constraints or optional nature of cookies in exchange for their added utilityfull-blown databases require more in terms of installationadministrationand coding as we'll see in luckily the extra coding part of that trade-off is remarkably simple in python moreoverpython' database interfaces may be used in any applicationweb-based or otherwise extensions to the cgi model finallythere are more advanced protocols and frameworks for retaining state on the serverwhich we won' cover in this book for instancethe zope web application frameworkdiscussed briefly in provides product interfacewhich allows for the construction of web-based objects that are automatically persistent other schemessuch as fastcgias well as server-specific extensions such as mod_python for apachemay attempt to work around the autonomousone-shot nature of cgi scriptsor otherwise extend the basic cgi model to support long-lived memory stores for examplefastcgi allows web applications to run as persistent processeswhich receive input data from and send reply streams to the http web server over inter-process communication (ipcmechanisms such as sockets this differs from normal cgiwhich communicates inputs and outputs with environment variablesstandard streamsand command-line argumentsand assumes scripts run to completion on each request because fastcgi process may outlive single pageit can retain state information from page to pageand avoids startup performance costs mod_python extends the open source apache web server by embedding the python interpreter within apache python code is executed directly within the apache servereliminating the need to spawn external processes this package also supports the concept of sessionswhich can be used to store data between pages session data is locked for concurrent access and can be stored in files or in memorydepending on whether apache is running in multiprocess or multithreaded mode mod_python also includes web development toolssuch as the python server pages (pspserver-side templating language for html generation mentioned in and earlier in this such models are not universally supportedthoughand may come with some added cost in complexity--for exampleto synchronize access to persistent data with locks moreovera failure in fastcgi-style web application impacts the entire application server-side scripting
5,749
more on persistent cgi modelsand support in python for things such as fastcgisearch the web or consult web-specific resources combining techniques naturallythese techniques may be combined to achieve variety of memory strategiesboth for interaction sessions and for more permanent storage needs for examplea web application may use cookies to store per-user or per-session key on the clientand later use that key to index into server-side database to retrieve the user' or session' full state information even for short-lived session informationurl query parameters or hidden form fields may similarly be used to pass key identifying the session from page to pageto be used by the next script to index server-side database moreoverurl query parameters and hidden fields may be generated for temporary state memory that spans pageseven though cookies and databases are used for retention that must span sessions the choice of technique is driven by the application' storage needs although not as straightforward as the in-memory variables and objects of single process gui programs running on clientwith creativitycgi script state retention is entirely possible the hello world selector let' get back to writing some code again it' time for something bit more useful than the examples we've seen so far (wellmore entertainingat leastthis section presents program that displays the basic syntax required by various programming languages to print the string "hello world,the classic language benchmark to keep it simplethis example assumes that the string is printed to the standard output stream in the selected languagenot to gui or web page it also gives just the output command itselfnot complete programs the python version happens to be complete programbut we won' hold that against its competitors here structurallythe first cut of this example consists of main page html filealong with python-coded cgi script that is invoked by form in the main html page because no state or database data is stored between user clicksthis is still fairly simple example in factthe main html page implemented by example - is mostly just one big pull-down selection list within form example - pp \internet\web\languages html languages hello world selector the hello world selector
5,750
programming languagessyntax to keep this simpleonly the output command is shown (it takes more code to make complete program in some of these languages)and only text-based solutions are given (no gui or html construction logic is includedthis page is simple html filethe one you see after pressing the button below is generated by python cgi script which runs on the server pointersto see this page' htmluse the 'view sourcecommand in your browser to view the python cgi script on the serverclick here or here to see an alternative version that generates this page dynamicallyclick here select programming languageall python python perl tcl scheme smalltalk java +basic fortran pascal other for the momentlet' ignore some of the hyperlinks near the middle of this filethey introduce bigger concepts like file transfers and maintainability that we will explore in the next two sections when visited with browserthis html file is downloaded to the client and is rendered into the new browser page shown in figure - that widget above the submit button is pull-down selection list that lets you choose one of the tag values in the html file as usualselecting one of these language names and pressing the submit button at the bottom (or pressing your enter keysends the selected language name to an instance of the server-side cgi script program named in the form' action option example - contains the python script that is run by the web server upon submission server-side scripting
5,751
example - pp \internet\web\cgi-bin\languages py #!/usr/bin/python ""show hello world syntax for input language namenote that it uses rraw strings so that '\nin the table are left intactand cgi escape(on the string so that things like '<<don' confuse browsers--they are translated to valid html codeany language name can arrive at this scriptsince explicit urls "can be typed in web browser or sent by script (urllib request urlopencaveatsthe languages list appears in both the cgi and html files--could import from single file if selection list generated by cgi script too""debugme false inputkey 'languagetrue=test from cmd line input parameter name hellos 'python'rprint('hello world'"'python 'rprint 'hello world"'perl'rprint "hello world\ "''tcl'rputs "hello world''scheme' (display "hello world"(newline''smalltalk' 'hello worldprint "'java'rsystem out println("hello world")'' 'rprintf("hello world\ ")'' ++'rcout <"hello world<endl''basic' print "hello world''fortran'rprint *'hello world"'pascal'rwriteln('hello world')the hello world selector
5,752
def __init__(selfstr)self value str import cgisys if debugmeform {inputkeydummy(sys argv[ ])elseform cgi fieldstorage(print('content-typetext/html\ 'print('languages'print('syntax'mocked-up input obj name on cmd line parse real inputs adds blank line def showhello(form)html for one language choice form[inputkeyvalue print('%schoicetryprint(cgi escape(hellos[choice])except keyerrorprint("sorry-- don' know that language"print(''if not inputkey in form or form[inputkeyvalue ='all'for lang in hellos keys()mock {inputkeydummy(lang)showhello(mockelseshowhello(formprint(''and as usualthis script prints html code to the standard output stream to produce response page in the client' browser not much is new to speak of in this scriptbut it employs few techniques that merit special focusraw strings and quotes notice the use of raw strings (string constants preceded by an "rcharacterin the language syntax dictionary recall that raw strings retain backslash characters in the string literallyinstead of interpreting them as string escape-code introductions without themthe \ newline character sequences in some of the language' code snippets would be interpreted by python as line feedsinstead of being printed in the html reply as \ the code also uses double quotes for strings that embed an unescaped single-quote characterper python' normal string rules escaping text embedded in html and urls this script takes care to format the text of each language' code snippet with the cgi escape utility function this standard python utility automatically translates characters that are special in html into html escape code sequencesso that they are not treated as html operators by browsers formallycgi escape translates characters to escape code sequencesaccording to the standard html conventionand become &lt;&gt;and &ampif you pass second true argumentthe double-quote character ("is translated to &quot server-side scripting
5,753
pair of html escape codes because printing each code snippet effectively embeds it in the html response streamwe must escape any special html characters it contains html parsers (including python' standard html parser module presented in translate escape codes back to the original characters when page is rendered more generallybecause cgi is based upon the notion of passing formatted strings across the netescaping special characters is ubiquitous operation cgi scripts almost always need to escape text generated as part of the reply to be safe for instanceif we send back arbitrary text input from user or read from data source on the serverwe usually can' be sure whether it will contain html charactersso we must escape it just in case in later exampleswe'll also find that characters inserted into url address strings generated by our scripts may need to be escaped as well literal in url is specialfor exampleand must be escaped if it appears embedded in text we insert into url howeverurl syntax reserves different special characters than html codeand so different escaping conventions and tools must be used as we'll see later in this cgi escape implements escape translations in html codebut urllib parse quote (and its relativesescapes characters in url strings mocking up form inputs here againform inputs are "mocked up(simulated)both for debugging and for responding to request for all languages in the table if the script' global debugme variable is set to true valuefor instancethe script creates dictionary that is plug-and-play compatible with the result of cgi fieldstorage call--its "languageskey references an instance of the dummy mock-up class this class in turn creates an object that has the same interface as the contents of cgi field storage result--it makes an object with value attribute set to passed-in string the net effect is that we can test this script by running it from the system command linethe generated dictionary fools the script into thinking it was invoked by browser over the net similarlyif the requested language name is "all,the script iterates over all entries in the languages tablemaking mocked-up form dictionary for each (as though the user had requested each language in turnthis lets us reuse the existing showhello logic to display each language' code in single page as always in pythonobject interfaces and protocols are what we usually code fornot specific datatypes the showhello function will happily process any object that responds to the syntax form['language'value notice that #if you are reading closelyyou might notice that this is the second time we've used mock-ups in this (see the earlier tutor cgi exampleif you find this technique generally usefulit would probably make sense to put the dummy classalong with function for populating form dictionary on demandinto module so that it can be reused in factwe will do that in the next section even for two-line classes like thistyping the same code the third time around will do much to convince you of the power of code reuse the hello world selector
5,754
cost of introducing special case in its code now back to interacting with this program if we select particular languageour cgi script generates an html reply of the following sort (along with the required contenttype header and blank line preambleuse your browser' view source option to seelanguages syntax scheme (display "hello world"(newlineprogram code is marked with tag to specify preformatted text (the browser won' reformat it like normal text paragraphthis reply code shows what we get when we pick scheme figure - shows the page served up by the script after selecting "pythonin the pull-down selection list (whichfor the purposes of both this edition and the expected future at largeof coursereally means python xfigure - response page created by languages py our script also accepts language name of "alland interprets it as request to display the syntax for every language it knows about for examplehere is the html that is generated if we set the global variable debugme to true and run from the system command line with single argumentall this output is the same as what is printed to the client' web browser in response to an "allselection*we also get the "allreply if debugme is set to false when we run the script from the command line instead of throwing an exceptionthe cgi fieldstorage call returns an empty dictionary if called outside the cgi environmentso the test for missing key kicks in it' likely safer to not rely on this behaviorhowever server-side scripting
5,755
content-typetext/html languages syntax printf("hello world\ ")java system out println("hello world") +cout &lt;&lt"hello world&lt;&ltendlperl print "hello world\ "fortran print *'hello worldbasic print "hello worldscheme (display "hello world"(newlinesmalltalk 'hello worldprint python print('hello world'pascal writeln('hello world')tcl puts "hello worldpython print 'hello worldeach language is represented here with the same code pattern--the showhello function is called for each table entryalong with mocked-up form object notice the way that +code is escaped for embedding inside the html streamthis is the cgi escape call' handiwork your web browser translates the &ltescapes to characters when the page is rendered when viewed with browserthe "allresponse page is rendered as shown in figure - the order in which languages are listed is pseudorandombecause the dictionary used to record them is not sequence the hello world selector
5,756
checking for missing and invalid inputs so farwe've been triggering the cgi script by selecting language name from the pulldown list in the main html page in this contextwe can be fairly sure that the script will receive valid inputs noticethoughthat there is nothing to prevent client from passing the requested language name at the end of the cgi script' url as an explicit query parameterinstead of using the html page form for instancea url of the following kind typed into browser' address field or submitted with the module urllib requestyields the same "pythonresponse page shown in figure - howeverbecause it' always possible for user to bypass the html file and use an explicit urla user could invoke our script with an unknown language nameone that is not in the html file' pull-down list (and so not in our script' tablein factthe script might be triggered with no language input at all if someone explicitly submits its url with no language parameter (or no parameter valueat the end such an erroneous url could be entered into browser' address field or be sent by another script using the urllib request module techniques described earlier in this for instancevalid requests work normally server-side scripting
5,757
request reply urlopen(requestread(print(reply decode()languages syntax python print('hello world'to be robustthoughthe script also checks for both error cases explicitlyas all cgi scripts generally should here is the html generated in response to request for the fictitious language guido (againyou can also see this by selecting your browser' view source option after typing the url manually into your browser' address field)request reply urlopen(requestread(print(reply decode()languages syntax guido sorry-- don' know that language if the script doesn' receive any language name inputit simply defaults to the "allcase (this case is also triggered if the url ends with just ?languageand no language name value)reply urlopen(print(reply decode()languages syntax printf("hello world\ ")java system out println("hello world") +cout &lt;&lt"hello world&lt;&ltendlmore if we didn' detect these caseschances are that our script would silently die on python exception and leave the user with mostly useless half-complete page or with default error page (we didn' assign stderr to stdout hereso no python error message would be displayedfigure - shows the page generated and rendered by browser if the script is invoked with an explicit url like thisthe hello world selector
5,758
to test this error case interactivelythe pull-down list includes an "othernamewhich produces similar error page reply adding code to the script' table for the cobol "hello worldprogram (and other languages you might recall from your sordid development pastis left as an exercise for the reader for more example invocations of our languages py scriptturn back to its role in the examples near the end of therewe used it to test script invocation from raw http and urllib client-side scriptsbut you should now have better idea of what those scripts invoke on the server refactoring code for maintainability let' step back from coding details for just moment to gain some design perspective as we've seenpython codeby and largeautomatically lends itself to systems that are easy to read and maintainit has simple syntax that cuts much of the clutter of other tools on the other handcoding styles and program design can often affect maintainability as much as syntax for examplethe "hello worldselector pages of the preceding section work as advertised and were very easy and fast to throw together but as currently codedthe languages selector suffers from substantial maintainability flaws imaginefor instancethat you actually take me up on that challenge posed at the end of the last sectionand attempt to add another entry for cobol if you add cobol to the cgi script' tableyou're only half donethe list of supported languages lives redundantly in two places--in the html for the main page as well as in the script' syntax dictionary changing one does not change the other in factthis is something witnessed firsthand when adding "python in this edition (and initially forgot to server-side scripting
5,759
might fail the scrutiny of rigorous code reviewselection list as just mentionedthe list of languages supported by this program lives in two placesthe html file and the cgi script' tableand redundancy is killer for maintenance work field name the field name of the input parameterlanguageis hardcoded into both files as well you might remember to change it in the other if you change it in onebut you might not form mock-ups we've redundantly coded classes to mock-up form field inputs twice in this alreadythe "dummyclass here is clearly mechanism worth reusing html code html embedded in and generated by the script is sprinkled throughout the program in print call statementsmaking it difficult to implement broad web page layout changes or delegate web page design to nonprogrammers this is short exampleof coursebut issues of redundancy and reuse become more acute as your scripts grow larger as rule of thumbif you find yourself changing multiple source files to modify single behavioror if you notice that you've taken to writing programs by cut-and-paste copying of existing codeit' probably time to think about more rational program structures to illustrate coding styles and practices that are friendlier to maintainerslet' rewrite (that isrefactorthis example to fix all of these weaknesses in single mutation step sharing objects between pages-- new input form we can remove the first two maintenance problems listed earlier with simple transformationthe trick is to generate the main page dynamicallyfrom an executable scriptrather than from precoded html file within scriptwe can import the input field name and selection list values from common python module fileshared by the main and reply page generation scripts changing the selection list or field name in the common module changes both clients automatically firstwe move shared objects to common module fileas shown in example - example - pp \internet\web\cgi-bin\languages common py ""common objects shared by main and reply page scriptsneed change only this file to add new language ""inputkey 'languageinput parameter name refactoring code for maintainability
5,760
'python'rprint('hello world'"'python 'rprint 'hello world"'perl'rprint "hello world\ "''tcl'rputs "hello world''scheme' (display "hello world"(newline''smalltalk' 'hello worldprint "'java'rsystem out println("hello world")'' 'rprintf("hello world\ ")'' ++'rcout <"hello world<endl''basic' print "hello world''fortran'rprint *'hello world"'pascal'rwriteln('hello world')the module languages common contains all the data that needs to agree between pagesthe field name as well as the syntax dictionary the hellos syntax dictionary isn' quite html codebut its keys list can be used to generate html for the selection list on the main page dynamically notice that this module is stored in the same cgi-bin directory as the cgi scripts that will use itthis makes import search paths simple--the module will be found in the script' current working directorywithout path configuration in generalexternal references in cgi scripts are resolved as followsmodule imports will be relative to the cgi script' current working directory (cgibin)plus any custom path setting in place when the script runs when using minimal urlsreferenced pages and scripts in links and form actions within generated html are relative to the prior page' location as usual for cgi scriptsuch minimal urls are relative to the location of the generating script itself filenames referenced in query parameters and passed into scripts are normally relative to the directory containing the cgi script (cgi-binhoweveron some platforms and servers they may be relative to the web server' directory instead for our local web serverthe latter case applies to prove some of these points to yourselfsee and run the cgi script in the examples package identified by url filenames are relative to the parent directory where the web server is running (newly created files appear therehere is this script' codeif you need to gauge how paths are mapped for your server and platformthis server-specific treatment of relative filenames may not be idea for portabilitybut this is just one of many details that can vary per serverimport languages common open('test-context-output txt'' ' write(languages common inputkeyf close(print('context-typetext/html\ \ndone \ ' server-side scripting from my dir in server dir
5,761
the response html with values imported from the common module file in the previous example example - pp \internet\web\cgi-bin\languages py #!/usr/bin/python ""generate html for main page dynamically from an executable python scriptnot precoded html filethis lets us import the expected input field name and the selection table values from common python module filechanges in either now only have to be made in one placethe python module file""reply """content-typetext/html languages hello world selector similar to file languages htmlbut this page is dynamically generated by python cgi scriptusing selection list and input field names imported from common python module on the server only the common module must be maintained as new languages are addedbecause it is shared with the reply script to see the code that generates this page and the replyclick hereherehereand here select programming languageall % other ""from languages common import hellosinputkey options [for lang in hellosoptions append('langoptions '\ \tjoin(optionsprint(reply (inputkeyoptions)we could sort keys too wrap table keys in html code field name and values from module againignore the getfile hyperlinks in this file for nowwe'll learn what they mean in later section you should noticethoughthat the html page definition becomes printed python string here (named reply)with % format targets where we plug in refactoring code for maintainability
5,762
file' codewhen we visit this script' urlwe get similar pageshown in figure - but this timethe page is generated by running script on the server that populates the pull-down selection list from the keys list of the common syntax table use your browser' view source option to see the html generatedit' nearly identical to the html file in example - though the order of languages in the list may differ due to the behavior of dictionary keys figure - alternative main page made by languages py one maintenance note herethe content of the reply html code template string in example - could be loaded from an external text file so that it could be worked on independently of the python program logic in generalthoughexternal text files are no more easily changed than python scripts in factpython scripts are text filesand this is major feature of the language--it' easy to change the python scripts of an installed system on sitewithout recompile or relink steps howeverexternal html files could be checked out separately in source-control systemif this matters in your environment step reusable form mock-up utility moving the languages table and input field name to module file solves the first two maintenance problems we noted but if we want to avoid writing dummy field mockup class in every cgi script we writewe need to do something more againit' merely matter of exploiting the python module' affinity for code reuselet' move the dummy class to utility moduleas in example - server-side scripting
5,763
""tools for simulating the result of cgi fieldstorage(calluseful for testing cgi scripts outside the web ""class fieldmockupdef __init__(selfstr)self value str mocked-up input object def formmockup(**kwargs)pass field=value args mockup {multichoice[valuefor (keyvaluein kwargs items()if type(value!listsimple fields have value mockup[keyfieldmockup(str(value)elsemultichoice have list mockup[key[to dofile upload fields for pick in valuemockup[keyappend(fieldmockup(pick)return mockup def selftest()use this form if fields can be hardcoded form formmockup(name='bob'job='hacker'food=['spam''eggs''ham']print(form['name'valueprint(form['job'valuefor item in form['food']print(item valueend='use real dict if keys are in variables or computed print(form {'name'fieldmockup('brian')'age'fieldmockup( )or dict(for key in form keys()print(form[keyvalueif __name__ ='__main__'selftest(when we place our mock-up class in the module formmockup pyit automatically becomes reusable tool and may be imported by any script we care to write for readabilitythe dummy field simulation class has been renamed fieldmockup here for conveniencewe've also added formmockup utility function that builds up an entire form dictionary from passed-in keyword arguments assuming you can hardcode the names of the form to be fakedthe mock-up can be created in single call this module includes self-test function invoked when the file is run from the command linewhich demonstrates how its exports are used here is its test outputgenerated by making and querying two form mock-up objectsassumingof coursethat this module can be found on the python module search path when those scripts are run since python searches the current directory for imported modules by defaultthis generally works without sys path changes if all of our files are in our main web directory for other applicationswe may need to add this directory to pythonpath or use package (directory pathimports refactoring code for maintainability
5,764
bob hacker spam eggs ham brian since the mock-up now lives in modulewe can reuse it anytime we want to test cgi script offline to illustratethe script in example - is rewrite of the tutor py example we saw earlierusing the form mock-up utility to simulate field inputs if we had planned aheadwe could have tested the script like this without even needing to connect to the net example - pp \internet\web\cgi-bin\tutor _mockup py #!/usr/bin/python ""run tutor logic with formmockup instead of cgi fieldstorage(to testpython tutor _mockup py temp htmland open temp html ""from formmockup import formmockup form formmockup(name='bob'shoesize='small'language=['python'' ++''html']comment='ninini'rest same as originalless form assignment running this script from simple command line shows us what the html response stream will look likec:\pp \internet\web\cgi-binpython tutor _mockup py content-typetext/html tutor py greetings your name is bob you wear rather small shoes your current job(unknownyou program in python and +and html you also saidninini running it live yields the page in figure - field inputs are hardcodedsimilar in spirit to the tutor extension that embedded input parameters at the end of hyperlink urls herethey come from form mock-up objects created in the reply script that cannot be changed without editing the script because python code runs immediatelythoughmodifying python script during the debug cycle goes as quickly as you can type server-side scripting
5,765
step putting it all together-- new reply script there' one last step on our path to software maintenance nirvanawe must recode the reply page script itself to import data that was factored out to the common module and import the reusable form mock-up module' tools while we're at itwe move code into functions (in case we ever put things in this file that we' like to import in another script)and all html code to triple-quoted string blocks the result is example - changing html is generally easier when it has been isolated in single strings like thisinstead of being sprinkled throughout program example - pp \internet\web\cgi-bin\languages reply py #!/usr/bin/python ""samebut for easier maintenanceuse html template stringsget the language table and input key from common module fileand get reusable form field mockup utilities module for testing ""import cgisys from formmockup import fieldmockup from languages common import hellosinputkey debugme false input field simulator get common tablename hdrhtml """content-typetext/html\ languages refactoring code for maintainability
5,766
langhtml ""% % ""def showhello(form)html for one language choice form[inputkeyvalue escape lang name too tryprint(langhtml (cgi escape(choice)cgi escape(hellos[choice]))except keyerrorprint(langhtml (cgi escape(choice)"sorry-- don' know that language")def main()if debugmeform {inputkeyfieldmockup(sys argv[ ])elseform cgi fieldstorage(name on cmd line parse real inputs print(hdrhtmlif not inputkey in form or form[inputkeyvalue ='all'for lang in hellos keys()mock {inputkeyfieldmockup(lang)not dict( =vhereshowhello(mockelseshowhello(formprint(''if __name__ ='__main__'main(when global debugme is set to truethe script can be tested offline from simple command line as beforec:\pp \internet\web\cgi-binpython languages reply py python content-typetext/html languages syntax python print('hello world'when run online using either the page in figure - or an explicitly typed url with query parameterswe get the same reply pages we saw for the original version of this example (we won' repeat them here againthis transformation changed the program' architecturenot its user interface architecturallythoughboth the input and reply pages are now created by python cgi scriptsnot static html files server-side scripting
5,767
test-drive these pagesthe only differences you'll find are the urls at the top of your browser (they're different filesafter all)extra blank lines in the generated html (ignored by the browser)and potentially different ordering of language names in the main page' pull-down selection list againthis selection list ordering difference arises because this version relies on the order of the python dictionary' keys listnot on hardcoded list in an html file dictionariesyou'll recallarbitrarily order entries for fast fetchesif you want the selection list to be more predictablesimply sort the keys list before iterating over it using the list sort method or the sorted function introduced in python for lang in sorted(hellos)mock {inputkeyfieldmockup(lang)dict iterator instead of keys(faking inputs with shell variables if you're familiar with shellsyou might also be able to test cgi scripts from the command line on some platforms by setting the same environment variables that http servers setand then launching your script for examplewe might be able to pretend to be web server by storing input parameters in the query_string environment variableusing the same syntax we employ at the end of url string after the ?setenv query_string "name=mel&job=trainer,+writerpython tutor py content-typetext/html tutor py greetings your name is mel you wear rather (unknownshoes your current jobtrainerwriter you program in (unknownyou also said(unknownherewe mimic the effects of get style form submission or explicit url http servers place the query string (parametersin the shell variable query_string python' cgi module finds them there as though they were sent by browser post-style inputs can be simulated with shell variables toobut it' more complex--so much so that you may be better off not bothering to learn how in factit may be more robust in general to mock up inputs with python objects ( as in formmockup pybut some cgi scripts may have additional environment or testing constraints that merit unique treatment more on html and url escapes perhaps the subtlest change in the last section' rewrite is thatfor robustnessthis version' reply script (example - also calls cgi escape for the language namenot more on html and url escapes
5,768
impossible that someone could pass the script language name with an embedded html character as query parameter for examplea url such asembeds in the language name parameter (the name is <bwhen submittedthis version uses cgi escape to properly translate the for use in the reply htmlaccording to the standard html escape conventions discussed earlierhere is the reply text generatedlanguages syntax &lt; sorry-- don' know that language the original version in example - doesn' escape the language namesuch that the embedded < is interpreted as an html tag (which makes the rest of the page render in bold font!as you can probably tell by nowtext escapes are pervasive in cgi scripting--even text that you may think is safe must generally be escaped before being inserted into the html code in the reply stream in factbecause the web is text-based medium that combines multiple language syntaxesmultiple formatting rules may applyone for urls and another for html we met html escapes earlier in this urlsand combinations of html and urlsmerit few additional words url escape code conventions notice that in the prior sectionalthough it' wrong to embed an unescaped in the html code replyit' perfectly all right to include it literally in the url string used to trigger the reply in facthtml and urls define completely different characters as special for instancealthough must be escaped as &ampinside html codewe have to use other escaping schemes to code literal within url string (where it normally separates parametersto pass language name like & to our scriptwe have to type the following urlhere% represents &--the is replaced with followed by the hexadecimal value ( of its ascii code value ( similarlyas we suggested at the end of to name +as query parameter in an explicit urlmust be escaped as % bsending +unescaped will not workbecause is special in url syntax--it represents space by url standardsmost nonalphanumeric characters are supposed to be server-side scripting
5,769
this convention is known as the application/ -www-form-urlencoded query string formatand it' part of the magic behind those bizarre urls you often see at the top of your browser as you surf the web python html and url escape tools if you're like meyou probably don' have the hexadecimal value of the ascii code for committed to memory (though python' hex(ord( )can helpluckilypython provides tools that automatically implement url escapesjust as cgi escape does for html escapes the main thing to keep in mind is that html code and url strings are written with entirely different syntaxand so employ distinct escaping conventions web users don' generally careunless they need to type complex urls explicitly-browsers handle most escape code details internally but if you write scripts that must generate html or urlsyou need to be careful to escape characters that are reserved in either syntax because html and urls have different syntaxespython provides two distinct sets of tools for escaping their text in the standard python librarycgi escape escapes text to be embedded in html urllib parse quote and quote_plus escape text to be embedded in urls the urllib parse module also has tools for undoing url escapes (unquoteunquote_plus)but html escapes are undone during html parsing at large ( by python' html parser moduleto illustrate the two escape conventions and toolslet' apply each tool set to few simple examples somewhat inexplicablypython developers have opted to move and rename the cgi escape function used throughout this book to html escapeto make use of its longstanding original name deprecatedand to alter its quoting behavior slightly this is despite the fact that this function has been around for ages and is used in almost every python cgi-based web scripta glaring case of small group' notion of aesthetics trouncing widespread practice in and breaking working code in the process you may need to use the new html escape name in future python versionthat isunless python users complain loudly enough (yeshint!escaping html code as we saw earliercgi escape translates code for inclusion within html we normally call this utility from cgi scriptbut it' just as easy to explore its behavior interactivelyimport cgi cgi escape(' "spam"' more on html and url escapes
5,770
cgi escape(" hello" ' &lt; &lt; &gt;hello&lt;/ &gt;python' cgi module automatically converts characters that are special in html syntax according to the html convention it translates and with an extra true argument"into escape sequences of the form & ;where the is mnemonic that denotes the original character for instance&ltstands for the "less thanoperator (<and &ampdenotes literal ampersand (&there is no unescaping tool in the cgi modulebecause html escape code sequences are recognized within the context of an html parserlike the one used by your web browser when page is downloaded python comes with full html parsertooin the form of the standard module html parser we won' go into details on the html parsing tools here (they're covered in in conjunction with text processing)but to illustrate how escape codes are eventually undonehere is the html parser module at work reading back the preceding outputimport cgihtml parser cgi escape(" hello" ' &lt; &lt; &gt;hello&lt;/ &gt;html parser htmlparser(unescape( ' hellothis uses utility method on the html parser class to unquote in we'll see that using this class for more substantial work involves subclassing to override methods run as callbacks during the parse upon detection of tagsdataentitiesand more for more on full-blown html parsingwatch for the rest of this story in escaping urls by contrasturls reserve other characters as special and must adhere to different escape conventions as resultwe use different python library tools to escape urls for transmission python' urllib parse module provides two tools that do the translation work for usquotewhich implements the standard %xx hexadecimal url escape code sequences for most nonalphanumeric charactersand quote_pluswhich additionally translates spaces to signs the urllib parse module also provides functions for unescaping quoted characters in url stringunquote undoes %xx escapesand unquote_plus also changes plus signs back to spaces here is the module at workat the interactive promptimport urllib parse urllib parse quote(" # "' % % % % % % % server-side scripting
5,771
' % % cstuff% cspam txtx urllib parse quote_plus(" # " ' +% + +% % +curllib parse unquote_plus( ' #curl escape sequences embed the hexadecimal values of nonsafe characters following sign (this is usually their ascii codesin urllib parsenonsafe characters are usually taken to include everything except lettersdigitsand handful of safe special characters (any in ' -')but the two tools differ on forward slashesand you can extend the set of safe characters by passing an extra string argument to the quote calls to customize the translationsurllib parse quote_plus("uploads/index txt"'uploads% findex txturllib parse quote("uploads/index txt"'uploads/index txturllib parse quote_plus("uploads/index txt"'/''uploads/index txturllib parse quote("uploads/index txt"'/''uploads/index txturllib parse quote("uploads/index txt"'''uploads% findex txturllib parse quote_plus("uploads\index txt"'uploads% cindex txturllib parse quote("uploads\index txt"'uploads% cindex txturllib parse quote_plus("uploads\index txt"'\\''uploads\\index txtnote that python' cgi module also translates url escape sequences back to their original characters and changes signs to spaces during the process of extracting input information internallycgi fieldstorage automatically calls urllib parse tools which unquote if needed to parse and unescape parameters passed at the end of urls the upshot is that cgi scripts get back the originalunescaped url stringsand don' need to unquote values on their own as we've seencgi scripts don' even need to know that inputs came from url at all escaping urls embedded in html code we've seen how to escape text inserted into both html and urls but what do we do for urls inside htmlthat ishow do we escape when we generate and embed text inside urlwhich is itself embedded inside generated html codesome of our earlier examples used hardcoded urls with appended input parameters inside more on html and url escapes
5,772
urlbecause the url here is embedded in htmlit must at least be escaped according to html conventions ( any characters must become &lt;)and any spaces should be translated to signs per url conventions cgi escape(urlcall followed by the string url replace(""+"would take us this farand would probably suffice for most cases that approach is not quite enough in generalthoughbecause html escaping conventions are not the same as url conventions to robustly escape urls embedded in html codeyou should instead call urllib parse quote_plus on the url stringor at least most of its componentsbefore adding it to the html text the escaped result also satisfies html escape conventionsbecause urllib parse translates more characters than cgi escapeand the in url escapes is not special to html html and url conflictsbut there is one more astonishingly subtle (and thankfully rarewrinkleyou may also have to be careful with characters in url strings that are embedded in html code ( within hyperlink tagsthe symbol is both query parameter separator in urls (? = & = and the start of escape codes in html (&lt;consequentlythere is potential for collision if query parameter name happens to be the same as an html escape sequence code the query parameter name ampfor instancethat shows up as &amp= in parameters two and beyond on the url may be treated as an html escape by some html parsersand translated to &= even if parts of the url string are url-escapedwhen more than one parameter is separated by &the separator might also have to be escaped as &ampaccording to html conventions to see whyconsider the following html hyperlink tag with query parameter names namejobampsectand lthello when rendered in most browsers testedincluding internet explorer on windows this url link winds up looking incorrectly like this (the character in the first of these is really non-ascii section marker)file py?name= &job= &=cs= <= file py?name= &job= &= % = % = result in ie result in chrome ( is <the first two parameters are retained as expected (name=ajob= )because name is not preceded with an and &job is not recognized as valid html character escape code howeverthe &amp&sectand &lt parts are interpreted as special characters because they do name valid html escape codeseven without trailing semicolon to see this for yourselfopen the example package' test-escapes html file in your browserand highlight or select its linkthe query names may be taken as html server-side scripting
5,773
described earlier (unless the parts in question also end in semicolon)that might help for replies fetched manually with urllib requestbut not when rendered in browsersfrom html parser import htmlparser html open('test-escapes html'read(htmlparser(unescape(html'\nhello\navoiding conflicts what to do thento make this work as expected in all casesthe separators should generally be escaped if your parameter names may clash with an html escape codehello browsers render this fully escaped link as expected (open test-escapes html to test)and python' html parser does the right thing as wellfile py?name= &job= &amp= &sect= &lt= result in both ie and chrome 'hellohtmlparser(unescape( 'hellobecause of this conflict between html and url syntaxmost server tools (including python' urlib parse query-parameter parsing tools employed by python' cgi modulealso allow semicolon to be used as separator instead of the following linkfor exampleworks the same as the fully escaped urlbut does not require an extra html escaping step (at least not for the ;)file py?name= ;job= ;amp= ;sect= ;lt= python' html parser unescape tool allows the semicolons to pass unchangedtoosimply because they are not significant in html code to fully test all three of these link forms for yourself at onceplace them in an html fileopen the file in your browser using its html file in example - will suffice example - pp \internet\web\badlink html < href"cgi-bin/badlink py?name= &job= &amp= &sect= &lt= ">unescaped < href"cgi-bin/badlink py?name= &amp;job= &amp;amp= &amp;sect= &amp;lt= ">escaped < href"cgi-bin/badlink py?name= ;job= ;amp= ;sect= ;lt= ">alternative more on html and url escapes
5,774
script displays the inputs sent from the client on the standard error stream to avoid any additional translations (for our locally running web server in example - this routes the printed text to the server' console windowexample - pp \internet\web\cgi-bin\badlink py import cgisys form cgi fieldstorage(print all inputs to stderrstodout=reply page for name in form keys()print('[% :% ](nameform[namevalue)end='file=sys stderrfollowing is the (edited for spaceoutput we get in our local python-coded web server' console window for following each of the three links in the html page in turn using internet explorer the second and third yield the correct parameters set on the server as result of the html escaping or url conventions employedbut the accidental html escapes cause serious issues for the first unescaped link--the client' html parser translates these in unintended ways (results are similar under chromebut the first link displays the non-ascii section mark character with different escape sequence)mark-vaio [ /jun/ : : '[: \xa = <= [job: [name:amark-vaio [ /jun/ : : cgi script exited ok mark-vaio [ /jun/ : : '[amp: [job: [lt: [name: [sect: ]mark-vaio [ /jun/ : : cgi script exited ok mark-vaio [ /jun/ : : '[amp: [job: [lt: [name: [sect: ]mark-vaio [ /jun/ : : cgi script exited ok the moral of this story is that unless you can be sure that the names of all but the leftmost url query parameters embedded in html are not the same as the name of any html character escape code like ampyou should generally either use semicolon as separatorif supported by your toolsor run the entire url through cgi escape after escaping its parameter names and values with urllib parse quote_pluslink 'file py?name= &job= &amp= &sect= &lt=eescape for html import cgi cgi escape(link'file py?name= &amp;job= &amp;amp= &amp;sect= &amp;lt=eescape for url import urllib parse elink urllib parse quote_plus(linkelink 'file py% fname% da% job% db% amp% dc% sect% dd% lt% deurl satisfies html toosame cgi escape(elink'file py% fname% da% job% db% amp% dc% sect% dd% lt% de server-side scripting
5,775
separators embedded within html simply because their url parameter names are known not to conflict with html escapes in factthis concern is likely to be rare in practicesince your program usually controls the set of parameter names it expects this is nothoweverthe most general solutionespecially if parameter names may be driven by dynamic databasewhen in doubtescape much and often "how learned to stop worrying and love the weblest the html and url formatting rules sound too clumsy (and send you screaming into the night!)note that the html and url escaping conventions are imposed by the internet itselfnot by python (as you've learned by nowpython has different mechanism for escaping special characters in string constants with backslashes these rules stem from the fact that the web is based on the notion of shipping formatted text strings around the planetand are almost surely influenced by the tendency of different interest groups to develop very different notations you can take heartthoughin the fact that you often don' need to think in such cryptic termswhen you dopython automates the translation process with library tools just keep in mind that any script that generates html or urls dynamically probably needs to call python' escaping tools to be robust we'll see both the html and the url escape tool sets employed frequently in later examples in this and the next moreoverweb development frameworks and tools such as zope and others aim to get rid of some of the low-level complexities that cgi scripters face and as usual in programmingthere is no substitute for brainsamazing technologies like the internet come at an inevitable cost in complexity transferring files to clients and servers it' time to explain bit of html code that' been lurking in the shadows did you notice those hyperlinks on the language selector examplesmain pages for showing the cgi script' source code (the links told you to ignore)normallywe can' see such script source codebecause accessing cgi script makes it execute--we can see only its html outputgenerated to make the new page the script in example - referenced by hyperlink in the main language html pageworks around that by opening the source file and sending its text as part of the html response the text is marked with as preformatted text and is escaped for transmission inside html with cgi escape example - pp \internet\web\cgi-bin\languages-src py #!/usr/bin/python "display languages py script code without running it import cgi filename 'cgi-bin/languages pytransferring files to clients and servers
5,776
wrap up in html print('languages'print("source code'% 'filenameprint(''print(cgi escape(open(filenameread())decode per platform default print(''here againthe filename is relative to the server' directory for our web server on windows (see the prior discussion of thisand delete the cgi-bin portion of its path on other platformswhen we visit this script on the web via the first source hyperlink in example - or manually typed urlthe script delivers response to the client that includes the text of the cgi script source file it' captured in figure - figure - source code viewer page note that heretooit' crucial to format the text of the file with cgi escapebecause it is embedded in the html code of the reply if we don'tany characters in the text that mean something in html code are interpreted as html tags for examplethe +operator character within this file' text may yield bizarre results if not properly escaped the cgi escape utility converts it to the standard sequence &ltfor safe embedding server-side scripting
5,777
almost immediately after writing the languages source code viewer script in the preceding exampleit occurred to me that it wouldn' be much more workand would be much more usefulto write generic version--one that could use passed-in filename to display any file on the site it' straightforward mutation on the server sidewe merely need to allow filename to be passed in as an input the getfile py python script in example - implements this generalization it assumes the filename is either typed into web page form or appended to the end of the url as parameter remember that python' cgi module handles both cases transparentlyso there is no code in this script that notices any difference example - pp \internet\web\cgi-bin\getfile py #!/usr/bin/python ""#################################################################################display any cgi (or otherserver-side file without running it the filename can be passed in url param or form field (use "localhostas the server if local)users can cut-and-paste or "view sourceto save file locally on ierunning the text/plain version (formatted=falsesometimes pops up notepadbut end-lines are not always in dos formatnetscape shows the text correctly in the browser page instead sending the file in text/html mode works on both browsers--text is displayed in the browser response page correctly we also check the filename here to try to avoid showing private filesthis may or may not prevent access to such files in generaldon' install this script if you can' otherwise secure source#################################################################################""import cgiossys formatted true privates ['pymailcgi/cgi-bin/secret py'trysamefile os path samefile exceptdef samefile(path path )apath os path abspath(path lower(apath os path abspath(path lower(return apath =apath true=wrap text in html don' show these checks deviceinode numbers not available on windows do close approximation normalizes pathsame case html ""getfile response source code for'% % ""transferring files to clients and servers
5,778
for path in privatesif samefile(pathfilename)return true unify all paths by os stat else returns none=false tryform cgi fieldstorage(filename form['filename'value exceptfilename 'cgi-bin\getfile pyurl param or form field else default filename tryassert not restricted(filenameload unless private filetext open(filenameread(platform unicode encoding except assertionerrorfiletext '(file access denied)exceptfiletext '(error opening file% )sys exc_info()[ if not formattedprint('content-typetext/plain\ 'send plain text print(filetextworks on nsnot ieelseprint('content-typetext/html\ 'wrap up in html print(html (filenamecgi escape(filetext))this python server-side script simply extracts the filename from the parsed cgi inputs object and reads and prints the text of the file to send it to the client browser depending on the formatted global variable settingit sends the file in either plain text mode (using text/plain in the response headeror wrapped up in an html page definition (texthtmlboth modes (and otherswork in general under most browsersbut internet explorer doesn' handle the plain text mode as gracefully as netscape does--during testingit popped up the notepad text editor to view the downloaded textbut end-of-line characters in unix format made the file appear as one long line (netscape instead displays the text correctly in the body of the response web page itself html display mode works more portably with current browsers more on this script' restricted file logic in moment let' launch this script by typing its url at the top of browseralong with desired filename appended after the script' name figure - shows the page we get by visiting the following url (the second source link in the language selector page of example - has similar effect but different file)the body of this page shows the text of the server-side file whose name we passed at the end of the urlonce it arriveswe can view its textcut-and-paste to save it in file on the clientand so on in factnow that we have this generalized source code server-side scripting
5,779
viewerwe could replace the hyperlink to the script languages-src py in language htmlwith url of this form ( included both for illustration)subtle thingnotice that the query parameter in this url and others in this book use backslash as the windows directory separator on windowsand using both the local python web server of example - and internet explorerwe can also use the two url-escaped forms at the start of the followingbut the literal forward slash of the last in following fails (in url escapes% is and % is /)ok too ok too fails this reflects change since the prior edition of this book (which used the last of these for portability)and may or may not be ideal behavior (though like working directory contextsthis is one of set of server and platform differences you're likely to encounter when working on the webit seems to stem from the fact that the urllib parse module' quote considers safebut quote_plus no longer does if you care about url portability in this contextthe second of the preceding forms may be betterthough arguably cryptic to remember if you have to type it manually (escaping tools can automate thisif notyou may have to double-up on backslashes to avoid clashes with other string escapesbecause of the way url parameter data is handledsee the links to this script in example - for an example involving \ transferring files to clients and servers
5,780
to our python scriptwith filename parameters passed explicitly--we're using the script much like subroutine located elsewhere in cyberspace which returns the text of file we wish to view as we've seenparameters passed in urls are treated the same as field inputs in formsfor conveniencelet' also write simple web page that allows the desired file to be typed directly into formas shown in example - example - pp \internet\web\getfile html getfiledownload page type name of server file to be viewed view script code figure - shows the page we receive when we visit this file' url we need to type only the filename in this pagenot the full cgi script addressnotice that can use forward slashes here because the browser will escape on transmission and python' open allows either type of slash on windows (in query parameters created manuallyit' up to coders or generators to do the right thingfigure - source code viewer selection page when we press this page' download button to submit the formthe filename is transmitted to the serverand we get back the same page as beforewhen the filename was appended to the url (it' the same as figure - albeit with different directory separator slashin factthe filename will be appended to the url heretoothe get method in the form' html instructs the browser to append the filename to the url server-side scripting
5,781
page' address fieldeven though we really typed it into form clicking the link at the bottom of figure - opens the file-getter script' source in the same waythough the url is explicit +handling private files and errors as long as cgi scripts have permission to open the desired server-side filethis script can be used to view and locally save any file on the server for instancefigure - shows the page we're served after asking for the file path pymailcgi/pymailcgi html-an html text file in another application' subdirectorynested within the parent directory of this script (we explore pymailcgi in the next users can specify both relative and absolute paths to reach file--any path syntax the server understands will do figure - viewing files with relative paths more generallythis script will display any file path for which the username under which the cgi script runs has read access on some serversthis is often the user "nobody"- predefined username with limited permissions just about every server-side file used in web applications will be accessiblethoughor else they couldn' be referenced from browsers in the first place when running our local web serverevery file on the computer can be inspectedc:\users\mark\stuff\websites\public_html\index html works fine when entered in the form of figure - on my laptopfor example +you may notice another difference in the response pages produced by the form and an explicitly typed urlfor the formthe value of the "filenameparameter at the end of the url in the response may contain url escape codes for some characters in the file path you typed browsers automatically translate some non-ascii characters into url escapes (just like urllib parse quoteurl escapes were discussed earlier in this we'll see an example of this automatic browser escaping at work in an upcoming screenshot transferring files to clients and servers
5,782
server on remote machine what if we don' want users to be able to view some files on the serverfor examplein the next we will implement an encryption module for email account passwords on our serverit is in fact addressable as pymailcgi/cgi-bin/secret py allowing users to view that module' source code would make encrypted passwords shipped over the net much more vulnerable to cracking to minimize this potentialthe getfile script keeps listprivatesof restricted filenamesand uses the os path samefile built-in to check whether requested filename path points to one of the names on privates the samefile call checks to see whether the os stat built-in returns the same identifying information (device and inode numbersfor both file paths as resultpathnames that look different syntactically but reference the same file are treated as identical for exampleon the server used for this book' second editionthe following paths to the encryptor module were different stringsbut yielded true result from os path samefile/pymailcgi/secret py /home/crew/lutz/public_html/pymailcgi/secret py unfortunatelythe os path samefile call is supported on unixlinuxand macsbut not on windows to emulate its behavior in windowswe expand file paths to be absoluteconvert to common caseand compare ( shortened paths in the following with for display here)import os os path samefile attributeerror'moduleobject has no attribute 'samefileos getcwd(' :\\\pp \\dev\\examples\\pp \\internet\\webx os path abspath(/web/pymailcgi/cgi-bin/secret py'lower( os path abspath('pymailcgi/cgi-bin/secret py'lower( os path abspath(/pymailcgi/cgi-bin/cgi-bin/secret py'lower( ' :\\\pp \\dev\\examples\\pp \\internet\\web\\pymailcgi\\cgi-bin\\secret pyy ' :\\\pp \\dev\\examples\\pp \\internet\\web\\pymailcgi\\cgi-bin\\secret pyz ' :\\\pp \\dev\\examples\\pp \\internet\\web\\pymailcgi\\cgi-bin\\secret pyx =yy = (truetrueaccessing any of the three paths expanded here generates an error page like that in figure - notice how the names of secret files are global data in this moduleon the assumption that they pertain to files viewable across an entire sitethough we could allow for customization per sitechanging the script' globals per site is likely just as convenient as changing per-site customization files also notice that bona fide file errors are handled differently permission problems and attempts to access nonexistent filesfor exampleare trapped by different exception server-side scripting
5,783
sys exc_info--to give additional context figure - shows one such error page figure - accessing private files figure - file errors display as general rule of thumbfile-processing exceptions should always be reported in detailespecially during script debugging if we catch such exceptions in our scriptsit' up to us to display the details (assigning sys stderr to sys stdout won' help if python doesn' print an error messagethe current exception' typedataand traceback objects are always available in the sys module for manual display do not install the getfile py script if you truly wish to keep your files privatethe private files list check it uses attempts to prevent the encryption module from being viewed directly with this scriptbut it may or may not handle all possible attemptsespecially on windows this book isn' about securityso we won' go into further details hereexcept to say that on the interneta little paranoia is often good thing especially for systems installed on the general internet at largeyou should generally assume that the worst case scenario might eventually happen transferring files to clients and servers
5,784
the getfile script lets us view server files on the clientbut in some senseit is generalpurpose file download tool although not as direct as fetching file by ftp or over raw socketsit serves similar purposes users of the script can either cut-and-paste the displayed code right off the web page or use their browser' view source option to view and cut as described earlierscripts that contact the script with urllib can also extract the file' text with python' html parser module but what about going the other way--uploading file from the client machine to the serverfor instancesuppose you are writing web-based email systemand you need way to allow users to upload mail attachments this is not an entirely hypothetical scenariowe will actually implement this idea in the next when we develop the pymailcgi webmail site as we saw in uploads are easy enough to accomplish with client-side script that uses python' ftp support module yet such solution doesn' really apply in the context of web browserwe can' usually ask all of our program' clients to start up python ftp script in another window to accomplish an upload moreoverthere is no simple way for the server-side script to request the upload explicitlyunless an ftp server happens to be running on the client machine (not at all the usual caseusers can email files separatelybut this can be inconvenientespecially for email attachments so is there no way to write web-based program that lets its users upload files to common serverin factthere isthough it has more to do with html than with python itself html tags also support type=file optionwhich produces an input fieldalong with button that pops up file-selection dialog the name of the clientside file to be uploaded can either be typed into the control or selected with the popup dialog to demonstratethe html file in example - defines page that allows any client-side file to be selected and uploaded to the server-side script named in the form' action option example - pp \internet\web\putfile html putfileupload page <form enctype="multipart/form-datamethod=post action="cgi-bin/putfile py"select client file to be uploaded view script code one constraint worth notingforms that use file type inputs should also specify multipart/form-data encoding type and the post submission methodas shown in this server-side scripting
5,785
the url doesn' make sensewhen we visit this html filethe page shown in figure - is delivered pressing its browse button opens standard file-selection dialogwhile upload sends the file figure - file upload selection page on the client sidewhen we press this page' upload buttonthe browser opens and reads the selected file and packages its contents with the rest of the form' input fields (if anywhen this information reaches the serverthe python script named in the form action tag is run as alwaysas listed in example - example - pp \internet\web\cgi-bin\putfile py #!/usr/bin/python ""#################################################################################extract file uploaded by http from web browserusers visit putfile html to get the upload form pagewhich then triggers this script on serverthis is very powerfuland very dangerousyou will usually want to check the filenameetcthis may only work if file or dir is writablea unix 'chmod uploadsmay sufficefile pathnames may arrive in client' path formathandle herecaveatcould open output file in text mode to wite receiving platform' line ends since file content always str from the cgi modulebut this is temporary solution anyhow--the cgi module doesn' handle binary file uploads in at all#################################################################################""import cgiossys import posixpathntpathmacpath debugmode false for client paths true=print form info transferring files to clients and servers
5,786
uploaddir /uploadstrue=read file at once dir to store files sys stderr sys stdout form cgi fieldstorage(print("content-typetext/html\ "if debugmodecgi print_form(formshow error msgs parse form data with blank line print form fields html templates html ""putfile response page putfile response page % ""goodhtml html ""your file'% 'has been saved on the server as '%san echo of the file' contents received and saved appears below % ""process form data def splitpath(origpath)for pathmodule in [posixpathntpathmacpath]basename pathmodule split(origpath)[ if basename !origpathreturn basename return origpath get file at end try all clients may be any server lets spaces pass failed or no dirs def saveonserver(fileinfo)use file input form data basename splitpath(fileinfo filenamename without dir path srvrname os path join(uploaddirbasenamestore in dir if set srvrfile open(srvrname'wb'always write bytes here if loadtextautofiletext fileinfo value reads text into string if isinstance(filetextstr)python hack filedata filetext encode(srvrfile write(filedatasave in server file elseelse read line by line numlinesfiletext ' for huge files while truecontent always str here line fileinfo file readline(or for loop and iterator if not linebreak if isinstance(linestr)python hack line line encode(srvrfile write(linefiletext +line decode(ditto numlines + filetext ('[lines=% ]\nnumlinesfiletext srvrfile close( server-side scripting
5,787
return filetextsrvrname make writableowned by 'nobodydef main()if not 'clientfilein formprint(html 'errorno file was received'elif not form['clientfile'filenameprint(html 'errorfilename is missing'elsefileinfo form['clientfile'tryfiletextsrvrname saveonserver(fileinfoexcepterrmsg 'error% %stuple(sys exc_info()[: ]print(html errmsgelseprint(goodhtml (cgi escape(fileinfo filename)cgi escape(srvrname)cgi escape(filetext))main(within this scriptthe python-specific interfaces for handling uploaded files are employed they aren' very newreallythe file comes into the script as an entry in the parsed form object returned by cgi fieldstorageas usualits key is clientfilethe input control' name in the html page' code this timethoughthe entry has additional attributes for the file' name on the client moreoveraccessing the value attribute of an uploaded file input object will automatically read the file' contents all at once into string on the server for very large fileswe can instead read line by line (or in chunks of bytesto avoid overflowing memory space internallypython' cgi module stores uploaded files in temporary files automaticallyreading them in our script simply reads from that temporary file if they are very largethoughthey may be too long to store as single string in memory all at once for illustration purposesthe script implements either schemebased on the setting of the loadtextauto global variableit either asks for the file contents as string or reads it line by line in generalthe cgi module gives us back objects with the following attributes for file upload controlsfilename the name of the file as specified on the client file file object from which the uploaded file' contents can be read value the contents of the uploaded file (read from the file on attribute accessadditional attributes are not used by our script files represent third input field objectas we've also seenthe value attribute is string for simple input fieldsand we may receive list of objects for multiple-selection controls transferring files to clients and servers
5,788
serversmust have write access to the enclosing directory if the file doesn' yet existor to the file itself if it does to help isolate uploadsthe script stores all uploads in whatever server directory is named in the uploaddir global on one linux serveri had to give this directory mode of (universal read/write/execute permissionswith chmod to make uploads work in general this is nonissue with the local web server used in this but your mileage may varybe sure to check permissions if this script fails the script also calls os chmod to set the permission on the server file such that it can be read and written by everyone if it is created anew by an uploadthe file' owner will be "nobodyon some serverswhich means anyone out in cyberspace can view and upload the file on one linux serverthoughthe file will also be writable only by the user "nobodyby defaultwhich might be inconvenient when it comes time to change that file outside the web (naturallythe degree of pain can vary per file operationisolating client-side file uploads by placing them in single directory on the server helps minimize security risksexisting files can' be overwritten arbitrarily but it may require you to copy files on the server after they are uploadedand it still doesn' prevent all security risks-mischievous clients can still upload huge fileswhich we would need to trap with additional logic not present in this script as is such traps may be needed only in scripts open to the internet at large if both client and server do their partsthe cgi script presents us with the response page shown in figure - after it has stored the contents of the client file in new or existing file on the server for verificationthe response gives the client and server file pathsas well as an echo of the uploaded filewith line count in line-by-line reader mode notice that this echo display assumes that the file' content is text it turns out that this is safe assumption to makebecause the cgi module always returns file content as str stringsnot bytes less happilythis also stems from the fact that binary file uploads are not supported in the cgi module in (more on this limitation in an upcoming notethis file uploaded and saved in the uploads directory is identical to the original (run an fc command on windows to verify thisincidentallywe can also verify the upload with the getfile program we wrote in the prior section simply access the selection page to type the pathname of the file on the serveras shown in figure - if the file upload is successfulthe resulting viewer page we will obtain looks like figure - since the user "nobody(cgi scriptswas able to write the file"nobodyshould be able to view it as well (bad grammar perhapsbut true nonetheless server-side scripting
5,789
figure - verifying putfile with getfile--selection notice the url in this page' address field--the browser translated the character we typed into the selection page to % hexadecimal escape code before adding it to the end of the url as parameter we met url escape codes like this earlier in this in this casethe browser did the translation for usbut the end result is as if we had manually called one of the urllib parse quoting functions on the file path string technicallythe % escape code here represents the standard url translation for nonascii charactersunder the default encoding scheme browsers employ spaces are transferring files to clients and servers
5,790
usually translated to characters as well we can often get away without manually translating most non-ascii characters when sending paths explicitly (in typed urlsbut as we saw earlierwe sometimes need to be careful to escape characters ( &that have special meaning within url strings with urllib parse tools handling client path formats in the endthe putfile py script stores the uploaded file on the server within hardcoded uploaddir directoryunder the filename at the end of the file' path on the client ( less its client-side directory pathnoticethoughthat the splitpath function in this script needs to do extra work to extract the base name of the file on the right some browsers may send up the filename in the directory path format used on the client machinethis path format may not be the same as that used on the server where the cgi script runs this can vary per browserbut it should be addressed for portability the standard way to split up pathsos path splitknows how to extract the base namebut only recognizes path separator characters used on the platform on which it is running that isif we run this cgi script on unix machineos path split chops up paths around separator if user uploads from dos or windows machinehoweverthe separator in the passed filename is \not browsers running on some macintosh platforms may send path that is more different still to handle client paths genericallythis script imports platform-specific path-processing modules from the python library for each client it wishes to supportand tries to split the path with each until filename on the right is found for instanceposixpath handles paths sent from unix-style platformsand ntpath recognizes dos and windows client paths we usually don' import these modules directly since os path split is automatically loaded with the correct one for the underlying platformbut in this casewe server-side scripting
5,791
have instead coded the path splitter logic like this to avoid some split callsdef splitpath(origpath)basename os path split(origpath)[ if basename =origpathif '\\in origpathbasename origpath split('\\')[- elif '/in origpathbasename origpath split('/')[- return basename get name at end try server paths didn' change ittry dos clients try unix clients but this alternative version may fail for some path formats ( dos paths with drive but no backslashesas isboth options waste time if the filename is already base name ( has no directory paths on the left)but we need to allow for the more complex cases generically this upload script works as plannedbut few caveats are worth pointing out before we close the book on this examplefirstlyputfile doesn' do anything about cross-platform incompatibilities in filenames themselves for instancespaces in filename shipped from dos client are not translated to nonspace charactersthey will wind up as spaces in the serverside file' namewhich may be legal but are difficult to process in some scenarios secondlyreading line by line means that this cgi script is biased toward uploading text filesnot binary datafiles it uses wb output open mode to retain the binary content of the uploaded filebut it assumes the data is text in other placesincluding the reply page see for more about binary file modes this is all largely moot point in python thoughas binary file uploads do not work at all (see "cgi file upload limitations in ")in future releasethoughthis would need to be addressed if you run into any of these limitationsyou will have crossed over into the domain of suggested exercises cgi file upload limitations in regrettablyi need to document the fact that python' standard library support for cgi file uploads is partially broken in python the version used for this edition in shortthe cgi module' internal parsing step fails today with an exception if any binary file data or incompatible text file data is uploaded this exception occurs before the script has chance to intervenemaking simple workarounds nonviable cgi uploads worked in python because strings handled bytesbut fail in today this regression stems in part from the fact that the cgi module uses the email package' parser to extract incoming multipart data for filesand is thus crippled by some of the very same email package issues we explored in detail in --its email parser requires str for the full text of message to be parsedbut this is invalid for some cgi upload data as mentioned in the data transmitted for cgi file uploads might have mixed text and binary data--including raw binary data that is not transferring files to clients and servers
5,792
current email package' requirement to decode this to str for parsing is utterly incompatiblethough the cgi module' own code seems suspect for some cases as well if you want to see for yourself how data is actually uploaded by browserssee and run the html and python files named test-cgiu-uploads-bugin the examples package to upload textbinaryand mixed type filestest-cgi-uploads-bug html/py attempts to parse normallywhich works for some text files but always fails for binary files with unicode decoding error test-cgi-uploads-bug html/py tries binary mode for the input streambut always fails with type errors for both text and binary because of email' str requirement test-cgi-uploads-bug html/py saves the input stream for single file test-cgi-uploads-bug html/py saves the input stream for multiple files the last two of these scripts simply read the data in binary mode and save it in binary mode to file for inspectionand display two headers passed in environment variables which are used for parsing ( "multipart/form-datacontent type and boundaryalong with content lengthtrying to parse the saved input data with the cgi module fails unless the data is entirely text that is compatible with that module' encoding assumptions reallybecause the data can mix text and raw binary arbitrarilya correct parser will need to read it as bytes and switch between text and binary processing freely it seems likely that this will be improved in the futurebut perhaps not until python or later nearly two years after ' releasethoughthis book project has found itself playing the role of beta tester more often than it probably should this primarily derives from the fact that implications of the python str/bytes dichotomy were not fully resolved in python' own libraries prior to release this isn' meant to disparage people who have contributed much time and effort to alreadyof course as someone who remembers xthoughthis situation seems less than ideal writing replacement for the cgi module and the email package code it uses--the only true viable workaround--is not practical given this book project' constraints for nowthe cgi scripts that perform file uploads in this book will only work with text filesand then only with text files of compatible encodings this extends to email attachments uploaded to the pymailcgi webmail case study of the next -yet another reason why that example was not expanded with new functionality in this edition as much as the preceding pymailgui being unable to attach images to emails this way is severe functional limitationwhich limits scope in general for updates on the probable fix for this issue in the futurewatch this book' website (described in the prefacea fix seems likely to be incompatible with current library module apisbut short of writing every new system from scratchsuch is reality in the real world of software development (and no"running away moreis not an option server-side scripting
5,793
finallylet' discuss some context we've seen three getfile scripts at this point in the book the one in this is different from the other two we wrote in earlier but it accomplishes similar goalthis getfile is server-side cgi script that displays files over the http protocol (on port in we built clientand server-side getfile to transfer with raw sockets (on port in we implemented client-side getfile to ship over ftp (on port reallythe getfile cgi script in this simply displays files onlybut it can be considered download tool when augmented with cut-and-paste operations in web browser moreoverthe cgiand http-based putfile script here is also different from the ftp-based putfile in but it can be considered an alternative to both socket and ftp uploads the point to notice is that there are variety of ways to ship files around the internet-socketsftpand http (web pagescan move files between computers technically speakingwe can transfer files with other techniques and protocolstoo--post office protocol (popemailnetwork news transfer protocol (nntpnewstelnetand so on each technique has unique properties but does similar work in the endmoving bits over the net all ultimately run over sockets on particular portbut protocols like ftp and http add additional structure to the socket layerand application models like cgi add both structure and programmability in the next we're going to use what we've learned here to build more substantial application that runs entirely on the web--pymailcgia web-based email toolwhich allows us to send and view emails in browserprocess email attachmentsand more at the end of the daythoughit' mostly just bytes over socketswith user interface transferring files to clients and servers
5,794
in example - we wrote script named getfile pya python cgi program designed to display any public server-side filewithin web browser (or other recipienton the requesting client machine it uses content type of text/plain or text/html to make the requested file' text show up properly inside browser in the descriptionwe compared getfile py to generalized cgi download toolwhen augmented with cutand-paste or save-as interactions while truegetfile py was intended to mostly be file display tool onlynot cgi download demo if you want to truly and directly download file by cgi (instead of displaying it in browser or opening it with an application)you can usually force the browser to pop up save as dialog for the file on the client by supplying the appropriate content-type line in the cgi reply browsers decide what to do with file using either the file' suffix ( xxx jpg is interpreted as an image)or the content-type line ( text/html is html codeby using various mime header line settingsyou can make the datatype unknown and effectively render the browser clueless about data handling for instancea content type of application/octet-stream in the cgi reply generally triggers the standard save as dialog box in browser this strategy is sometimes frowned onthoughbecause it leaves the true nature of the file' data ambiguous--it' usually better to let the user/client decide how to handle downloaded datarather than force the save as behavior it also has very little to do with pythonfor more detailsconsult cgi-specific textor try web search on "cgi download server-side scripting
5,795
the pymailcgi server "things to do when visiting chicagothis is the fifth in our survey of python internet programmingand it continues ' discussion therewe explored the fundamentals of server-side common gateway interface (cgiscripting in python armed with that knowledgethis moves on to larger case study that underscores advanced cgi and server-side web scripting topics this presents pymailcgi-- "webmailwebsite for reading and sending email that illustrates security conceptshidden form fieldsurl generationand more because this system is similar in spirit to the pymailgui program we studied in this example also serves as comparison of the web and nonweb application models this case study is founded on basic cgi scriptingbut it implements complete website that does something more useful than ' examples as usual in this bookthis splits its focus between application-level details and python programming concepts for instancebecause this is fairly large case studyit illustrates system design concepts that are important in actual projects it also says more about cgi scripts in generalpymailcgi expands on the notions of state retention and security concerns and encryption the system presented here is neither particularly flashy nor feature rich as websites go (in factthe initial cut of pymailcgi was thrown together during layover at chicago' 'hare airportalasyou will find neither dancing bears nor blinking lights at this site on the other handit was written to serve real purposespeaks more to us about cgi scriptingand hints at just how far python server-side programs can take us as outlined at the start of this part of the bookthere are higher-level frameworkssystemsand tools that build upon ideas we will apply here for nowlet' have some fun with python on the web
5,796
in we built program called pymailgui that implements complete python+tkinter email client gui (if you didn' read that you may want to take quick glance at it nowherewe're going to do something of the samebut on the webthe system presented in this sectionpymailcgiis collection of cgi scripts that implement simple web-based interface for sending and reading email in any browser in effectit is webmail system--though not as powerful as what may be available from your internet service provider (isp)its scriptability gives you control over its operation and future evolution our goal in studying this system is partly to learn few more cgi trickspartly to learn bit about designing larger python systems in generaland partly to underscore the trade-offs between systems implemented for the web (the pymailcgi serverand systems written to run locally (the pymailgui clientthis hints at some of these trade-offs along the way and returns to explore them in more depth after the presentation of this system implementation overview at the top levelpymailcgi allows users to view incoming email with the post office protocol (popinterface and to send new mail by simple mail transfer protocol (smtpusers also have the option of replying toforwardingor deleting an incoming email while viewing it as implementedanyone can send email from pymailcgi sitebut to view your emailyou generally have to install pymailcgi on your own computer or web server accountwith your own mail server information (due to security concerns described laterviewing and sending email sounds simple enoughand we've already coded this few times in this book but the required interaction involves number of distinct web pageseach requiring cgi script or html file of its own in factpymailcgi is fairly linear system--in the most complex user interaction scenariothere are six states (and hence six web pagesfrom start to finish because each page is usually generated by distinct file in the cgi worldthat also implies six source files technicallypymailcgi could also be described as state machinethough very little state is transferred from state to state scripts pass user and message information to the next script in hidden form fields and query parametersbut there are no client-side cookies or server-side databases in the current version stillalong the way we'll encounter situations where more advanced state retention tools could be an advantage to help keep track of how all of pymailcgi' source files fit into the overall systemi jotted down the file in example - before starting any real programming it informally sketches the user' flow through the system and the files invoked along the way you can certainly use more formal notations to describe the flow of control and information the pymailcgi server
5,797
this file gets the job done example - pp \internet\web\pymailcgi\pageflow txt file or script creates [pymailcgi html=[onrootviewlink py=[onviewpswdsubmit py=[onviewlistlink py=[onviewpageaction py=[oneditpagesend py=back to root root window pop password window list window (loads all pop mailview window pick=del|reply|fwd (fetchedit windowor delete+confirm (delconfirmation (sends smtp mail=[onrootsendlink py=[oneditpagesend py=back to root edit window confirmation (sends smtp mailthis file simply lists all the source files in the systemusing =and indentation to denote the scripts they trigger for instancelinks on the pymailcgi html root page invoke onrootviewlink py and onrootsendlink pyboth executable scripts the script onrootviewlink py generates password pagewhose submit button in turn triggers onviewpswdsubmit pyand so on notice that both the view and the send actions can wind up triggering oneditpagesend py to send new mailview operations get there after the user chooses to reply to or forward an incoming mail in system such as thiscgi scripts make little sense in isolationso it' good idea to keep the overall page flow in mindrefer to this file if you get lost for additional contextfigure - shows the overall contents of this siteviewed as directory listings under cygwin on windows in shell window when you install this siteall the files you see here are uploaded to pymailcgi subdirectory of your web directory on your server' machine besides the page-flow html and cgi script files invoked by user interactionpymailcgi uses handful of utility modulescommonhtml py provides library of html tools externs py isolates access to modules imported from other places loadmail py encapsulates mailbox fetches for future expansion secret py implements configurable password encryption the pymailcgi website
5,798
pymailcgi also reuses parts of the mailtools module package and mailconfig py module we wrote in the former of these is accessible to imports from the pp package rootand the latter is largely copied by local version in the pymailcgi directory so that it can differ between pymailgui and pymailcgi the externs py module is intended to hide these modulesactual locationsin case the install structure varies on some machines in factthis system again demonstrates the powers of code reuse in practical way in this editionit gets great deal of logic for free from the new mailtools package of --message loadingsendingdeletingparsingcomposingdecoding and encodingand attachments--even though that package' modules were originally developed for the pymailgui program when it came time to update pymailcgi latertools for handling complex things such as attachments and message text searches were already in place see for mailtools source code as usualpymailcgi also uses variety of standard library modulessmtplibpoplibemail *cgiurllib *and the like thanks to the reuse of both custom and standard library codethis system achieves much in minimal amount of code all toldpymailcgi consists of just lines of new codeincluding whitespacecommentsand the top-level html file (see file linecounts xls in this system' source directory for detailsthe prior edition' version claimed to be some new linesthis compares favorably to the size of the pymailgui client-side "desktopprogram in but most of this difference owes to the vastly more limited functionality in pymailcgi--there are no local save filesno transfer thread overlapno message cachingno inbox synchronization tests or recoveryno multiple-message selectionsno raw mail text viewsand so on moreoveras the next section describespymailcgi' unicode policies are substantially more limited in this releaseand although arbitrary the pymailcgi server
5,799
in the current version because of python issue in other wordspymailcgi is really something of prototypedesigned to illustrate web scripting and system design concepts in this bookand serve as springboard for future work as isit' nowhere near as far along the software evolutionary scale as pymailgui stillwe'll see that pymailcgi' code factoring and reuse of existing modules allow it to implement much in surprisingly small amount of code new in this fourth edition (version in this fourth editionpymailcgi has been ported to run under python in additionthis version inherits and employs variety of new features from the mailtools moduleincluding mail header decoding and encodingmain mail text encodingthe ability to limit mail headers fetchedand more notablythere is new support for unicode and internationalized character sets as followsfor displayboth mail' main text and its headers are decoded prior to viewingper emailmimeand unicode standardstext is decoded per mail headers and headers are decoded per their content for sendsa mail' main texttext attachmentsand headers are all encoded per the same standardsusing utf- as the default encoding if required for replies and forwardsheaders copied into the quoted message text are also decoded for display note that this version relies upon web browsersability to display arbitrary kinds of unicode text it does not emit any sort of "metatag to declare encodings in the html reply pages generated for mail view and composition for instancea properly formed html document can often declare its encoding this waysuch headers are omitted here this is in part due to the fact that the mail might have arbitrary and even mixed types of text among is message and headerswhich might also clash with encoding in the html of the reply itself consider mail index list page that displays headers of multiple mailsbecause each mail' subject and from might be encoding in different character set (one russianone chineseand so on) single encoding declaration won' suffice (though utf- ' generality can often come to the rescueresolving such mixed character set cases is left to the browserwhich may ultimately require assistance from the user in the form of encoding choices such displays work in pymailgui because we pass decoded unicode text to the tkinter text widgetwhich handles arbitrary unicode code points well in pymailcgiwe're largely finessing this issue to keep this example short the pymailcgi website