id
int64
0
25.6k
text
stringlengths
0
4.59k
5,800
form and opened by filename in browsers when their links are clickedrelying again on browsers to do the right thing text attachments for sends are also subject to the cgi upload limitations described in the note just ahead beyond all thispython appears to have an issue printing some types of unicode text to the standard output stream in the cgi contextwhich necessitates workaround in the main utilities module here that opens stdout in binary mode and writes text as encoded bytes (see the code for more detailsthis unicode/ support is substantially less rich than that in pymailgui howevergiven that we can' prompt for encodings hereand given that this book is running short on time and space in generalimproving this for cases and browsers where it might matter is left as suggested exercise for more on specific fourth-edition changes madesee the comments marked with " in the program code files listed ahead in additionall the features added for the prior edition are still hereas described in the next section limitation on sending attachments in this edition if you haven' already done sosee "cgi file upload limitations in on page in briefin python the cgi moduleas well as the email package' parser which it usesfail with exceptions when requests submitted by web browsers include raw binary data or incompatibly encoded text added for uploaded files unfortunatelybecause this pymailcgi system relies on cgi uploads for attachmentsthis limitation means that this system does not currently support sending emails with binary email attachments such as images and audio files it did support this in the prior edition under python such sent attachments still work in ' pymailgui desktop applicationsimply because attachment file data can be read directly from local files (using binary mode if requiredand mime encoding if needed for inclusion in emailbecause the pymailcgi webmail system here relies on cgi uploads to transfer attachments to the server as an extra first stepthoughit' fully at the mercy of the currently broken cgi module' upload support coding cgi replacement is far too ambitious goal for this book fix is expected for this in the futureand may be present by the time you read these words being based on python thoughthis edition' pymailcgi simply cannot support sending such attachmentsthough they can still be freely viewed in mails fetched in factalthough this edition' pymailcgi inherits some new features from mailtools such as header decoding and encodingthis attachment send limitation is severe enough to preclude expanding this system' feature set to the same degree as this edition' pymailgui for exampleunicode policies are simple hereif not naive it' possible that some client-side scripting techniques such as ajax may be able to transfer attachment files independentlyand thus avoid cgi uploads altogether howeversuch techniques would also require deploying frameworks and technologies the pymailcgi server
5,801
structureand should probably not be necessitated by regression in python in any event rewrite (pymailria?will have to await final verdict on python cgi support fixes new in the prior edition (version in the third editionpymailcgi was upgraded to use the new mailtools module package of employ the pycrypto package for passwords if it is installedsupport viewing and sending message attachmentsand run more efficiently all these are inherited by version as well we'll meet these new features along the waybut the last two of these merit few words up front attachments are supported in simplistic but usable fashion and use existing mailtools package code for much of their operationfor viewing attachmentsmessage parts are split off the message and saved in local files on the server message view pages are then augmented with hyperlinks pointing to the temporary fileswhen clickedthey open in whatever way your web browser opens the selected part' file type for sending attachmentswe use the html upload techniques presented near the end of mail edit pages now have file-upload controlsto allow maximum of three attachments selected files are uploaded to the server by the browser with the rest of the page as usualsaved in temporary files on the serverand added to the outgoing mail from the local files on the server by mailtools as described in the note in the preceding sectionsent attachments can only be compatibly encoded text in version not binarythough this includes encodable html files both schemes would fail for multiple simultaneous usersbut since pymailcgi' configuration file scheme (described later in this already limits it to single usernamethis is reasonable constraint the links to temporary files generated for attachment viewing also apply only to the last message selectedbut this works if the page flow is followed normally improving this for multiuser scenarioas well as adding additional features such as pymailgui' local file save and open optionsare left as exercises for efficiencythis version of pymailcgi also avoids repeated exhaustive mail downloads in the prior versionthe full text of all messages in an inbox was downloaded every time you visited the list page and every time you selected single message to view in this versionthe list page downloads only the header text portion of each messageand only single message' full text is downloaded when one is selected for viewing in additionthe headers fetch limits added to mailtools in the fourth edition of this book are applied automatically to limit download time (earlier mails outside the set' size are ignoredthe pymailcgi website
5,802
in your inbox (and as confessed in have thousands in one of minea better solution would somehow cache mails to limit reloadsat least for the duration of browser session for examplewe might load headers of only newly arrived messagesand cache headers of mails already fetchedas done in the pymailgui client of due to the lack of state retention in cgi scriptsthoughthis would likely require some sort of server-side database we mightfor instancestore already fetched message headers under generated key that identifies the session ( with process number and timeand pass that key between pages as cookiehidden form fieldor url query parameter each page would use the key to fetch cached mail stored directly on the web serverinstead of loading it from the email server again presumablyloading from local cache file would be faster than loading from network connection to the mail server this would make for an interesting exercisetooif you wish to extend this system on your ownbut it would also result in more pages than this has to spend (franklyi ran out of time for this project and real estate in this long before ran out of potential enhancementspresentation overview much of the "actionin pymailcgi is encapsulated in shared utility modulesespecially one called commonhtml py as you'll see in momentthe cgi scripts that implement user interaction don' do much by themselves because of this this architecture was chosen deliberatelyto make scripts simpleavoid code redundancyand implement common look-and-feel in shared code but it means you must jump between files to understand how the whole system works to make this example easier to digestwe're going to explore its code in two chunkspage scripts firstand then the utility modules firstwe'll study screenshots of the major web pages served up by the system and the html files and top-level python cgi scripts used to generate them we begin by following send mail interactionand then trace how existing email is read and then processed most implementation details will be presented in these sectionsbut be sure to flip ahead to the utility modules listed later to understand what the scripts are really doing should also point out that this is fairly complex systemand won' describe it in exhaustive detailas for pymailgui and be sure to read the source code along the way for details not made explicit in the narrative all of the system' source code appears in this as well as in the book' examples distribution packageand we will study its key concepts here but as usual with case studies in this booki assume that you can read python code by now and that you will consult the example' source code for more details because python' syntax is so close to "executable the pymailcgi server
5,803
you have the overall design in mind running this examples the html pages and cgi scripts of pymailcgi can be installed on any web server to which you have access to keep things simple for this bookthoughwe're going to use the same policy as in --we'll be running the python-coded webserver py script from example - locallyon the same machine as the web browser client as we learned at the start of the prior that means we'll be using the server domain name "localhost(or the equivalent ip address "to access this system' pages in our browseras well as in the urllib request module start this server script on your own machine to test-drive the program ultimatelythis system must generally contact mail server over the internet to fetch or send messagesbut the web page server will be running locally on your computer one minor twist herepymailcgi' code is located in directory of its ownone level down from the webserver py script because of thatwe'll start the web server here with an explicit directory and port number in the command line used to launch itc:\pp \internet\webwebserver py pymailcgi type this sort of command into command prompt window on windows or into your system shell prompt on unix-like platforms when run this waythe server will listen for url requests on machine "localhostand socket port number it will serve up pages from the pymailcgi subdirectory one level below the script' locationand it will run cgi scripts located in the pymailcgi\cgi-bin directory below that this works because the script changes its current working directory to the one you name when it starts up subtle pointbecause we specify unique port number on the command line this wayit' ok if you simultaneously run another instance of the script to serve up the prior examples one directory upthat server instance will accept connections on port and our new instance will handle requests on port in factyou can contact either server from the same browser by specifying the desired server' port number if you have two instances of the server running in the two different directoriesto access pages and scripts of the prior use url of this formand to run this pages and scriptssimply use urls of this formyou'll see that the http and cgi log messages appear in the window of the server you're contacting for more background on why this works as it doessee the the pymailcgi website
5,804
if you do install this example' code on different serversimply replace the "localhost /cgi-binpart of the urls we'll use here with your server' nameportand path details in practicea system such as pymailcgi would be much more useful if it were installed on remote serverto allow mail processing from any web client as with pymailguiyou'll have to edit the mailconfig py module' settings to use this system to read your own email as providedthe email server information is not useful for reading email of your ownmore on this in moment carry-on software pymailcgi works as planned and illustrates more cgi and email conceptsbut want to point out few caveats up front this application was initially written during twohour layover in chicago' 'hare airport (though debugging took few hours morei wrote it to meet specific need--to be able to read and send email from any web browser while traveling around the world teaching python classes didn' design it to be aesthetically pleasing to others and didn' spend much time focusing on its efficiency also kept this example intentionally simple for this book for examplepymailcgi doesn' provide nearly as many features as the pymailgui program in and it reloads email more than it probably should because of thisits performance can be very poor if you keep your inbox large in factthis system almost cries out for more advanced state retention options as isuser and message details are passed in generated pages as hidden fields and query parametersbut we could avoid reloading mail by also using server-side deployment of the database techniques described in such extensions might eventually bring pymailcgi up to the functionality of pymailguialbeit at some cost in code complexity even sothis system also suffers from the python attachments limitation described earlierwhich would need to be addressed as well againyou should consider this system prototype and work in progressit' not yet software worth sellingand not something that you'll generally want to use as is for mail that' critical to you on the other handit does what it was intended to doand you can customize it by tweaking its python source code--something that can' be said of all software sold one downside to running local webserver py script that noticed during development for this is that on platforms where cgi scripts are run in the same process as the serveryou'll need to stop and restart the server every time you change an imported module otherwisea subsequent import in cgi script will have no effectthe module has already been imported in the process this is not an issue on windows today or on other platforms that run the cgi as separatenew process the server' classesimplementation varies over timebut if changes to your cgi scripts have no effectyour platform my fall into this categorytry stopping and restarting the locally running web server the pymailcgi server
5,805
let' start off by implementing main page for this example the file shown in example - is primarily used to publish links to the send and view functionspages it is coded as static html filebecause there is nothing to generate on the fly here example - pp \internet\web\pymailcgi\pymailcgi html pymailcgi main page pymailcgi pop/smtp web email interface version june ( january actions viewreplyforwarddelete pop mail send new email message by smtp overview < href="<img src="ppsmall gifalign=left alt="[book cover]border= hspace= this site implements simple web-browser interface to pop/smtp email accounts anyone can send email with this interfacebut for security reasonsyou cannot view email unless you install the scripts with your own email account informationin your own server account directory pymailcgi is implemented as number of python-coded cgi scripts that run on server machine (not your local computer)and generate html to interact with the client/browser see the book programming python th edition for more details notes caveatspymailcgi was initially written during -hour layover at chicago' 'hare airport this release is not nearly as fast or complete as pymailgui ( each click requires an internet transactionthere is no save operation or multithreadingand there is no caching of email headers or already-viewed messageson the other handpymailcgi runs on any web browserwhether you have python (and tkinstalled on your machine or not also note that if you use these scripts to read your own emailpymailcgi does not guarantee security for your account password see the notes in the view action page as well as the book for more information on security policies the root page
5,806
email attachments for single userand avoids some of the prior version' exhaustive mail downloads it only fetches message headers for the list pageand only downloads the full text of the single message selected for viewing new in version pymailcgi now runs on python (only)and employs many of the new features of the mailtools packagedecoding and encoding of internationalized headersdecoding of main mail textand so on due to regression in python ' cgi and email supportversion does not support sending of binary or incompatibly-encoded text attachmentsthough attachments on fetched mails can always be viewed (see and also seethe pymailgui program in the internet directorywhich implements more complete client-side python+tk email gui the pymail py program in the email directorywhich provides simple console command-line email interface the python imaplib module which supports the imap email protocol instead of pop < href="<img src="pythonpoweredsmall gifalign=left alt="[python logo]border= hspace= the file pymailcgi html is the system' root page and lives in pymailcgi subdirectory which is dedicated to this application and helps keep its files separate from other examples to access this systemstart your locally running web server as described in the preceding section and then point your browser to the following url (or do the right thing for whatever other web server you may be using)if you dothe server will ship back page such as that captured in figure - shown rendered in the google chrome web browser client on windows ' using chrome instead of internet explorer throughout this for varietyand because it tends to yield concise page which shows more details legibly open this in your own browser to see it live--this system is as portable as the webhtmland python-coded cgi scripts configuring pymailcgi nowbefore you click on the "view link in figure - expecting to read your own emaili should point out that by defaultpymailcgi allows anybody to send email from this page with the send link (as we learned earlierthere are no passwords in smtpit does nothoweverallow arbitrary users on the web to read their email the pymailcgi server
5,807
accounts without either typing an explicit and unsafe url or doing bit of installation and configuration this is on purposeand it has to do with security constraintsas we'll see laterpymailcgi is written such that it never associates your email username and password together without encryption this isn' an issue if your web server is running locallyof coursebut this policy is in place in case you ever run this system remotely across the web by defaultthenthis page is set up to read the email account shown in this book-address pp @learning-python com--and requires that account' pop password to do so since you probably can' guess the password (and wouldn' find its email all that interesting if you could!)pymailcgi is not incredibly useful as shipped to use it to read your email insteadyou'll want to change its mailconfig py mail configuration file to reflect your mail account' details we'll see this file laterfor nowthe examples here will use the book' pop email accountit works the same wayregardless of which account it accesses sending mail by smtp pymailcgi supports two main functionsas links on the root pagecomposing and sending new mail to othersand viewing incoming mail the view function leads to sending mail by smtp
5,808
function is the simplestlet' start with its pages and scripts first the message composition page the root page send function steps users through two other pagesone to edit message and one to confirm delivery when you click on the send link on the main page in figure - the python cgi script in example - runs on the web server example - pp \internet\web\pymailcgi\cgi-bin\onrootsendlink py #!/usr/bin/python ""###############################################################################on 'sendclick in main root windowdisplay composition page ###############################################################################""import commonhtml from externs import mailconfig commonhtml editpage(kind='write'headers={'from'mailconfig myaddress}nothis file wasn' truncatedthere' not much to see in this script because all the action has been encapsulated in the commonhtml and externs modules all that we can tell here is that the script calls something named editpage to generate replypassing in something called myaddress for its "fromheader that' by design--by hiding details in shared utility modules we make top-level scripts such as this much easier to read and writeavoid code redundancyand achieve common look-and-feel to all our pages there are no inputs to this script eitherwhen runit produces page for composing new messageas shown in figure - most of the composition page is self-explanatory--fill in headers and the main text of the message ( "fromheader and standard signature line are initialized from settings in the mailconfig modulediscussed further aheadthe choose file buttons open file selector dialogsfor picking an attachment this page' interface looks very different from the pymailgui client program in but it is functionally very similar also notice the top and bottom of this page--for reasons explained in the next sectionthey are going to look the same in all the pages of our system the send mail script as usualthe html of the edit page in figure - names its handler script when we click its send buttonexample - runs on the server to process our inputs and send the mail message the pymailcgi server
5,809
example - pp \internet\web\pymailcgi\cgi-bin\oneditpagesend py #!/usr/bin/python ""###############################################################################on submit in edit windowfinish writereplyor forwardin +we reuse the send tools in mailtools to construct and send the messageinstead of older manual string schemewe also inherit attachment structure composition and mime encoding for sent mails from that module cgi uploads fail in the py cgi module for binary and incompatibly-encoded textso we simply use the platform default here (cgi' parser does no better) use simple unicode encoding rules for main text and attachments too###############################################################################""import cgisyscommonhtmlos from externs import mailtools savedir 'partsuploadif not os path exists(savedir)sending mail by smtp
5,810
def saveattachments(formmaxattach= savedir=savedir)""save uploaded attachment files in local files on server from which mailtools will add to mailthe fieldstorage parser and other parts of cgi module can fail for many upload typesso we don' try very hard to handle unicode encodings here""partnames [for in range( maxattach+ )fieldname 'attach%di if fieldname in form and form[fieldnamefilenamefileinfo form[fieldnamesent and filledfiledata fileinfo value read into string filename fileinfo filename client' pathname if '\\in filenamebasename filename split('\\')[- try dos clients elif '/in filenamebasename filename split('/')[- try unix clients elsebasename filename assume dir stripped pathname os path join(savedirbasenameif isinstance(filedatastr) rb needs bytes filedata filedata encode( use encodingsavefile open(pathname'wb'savefile write(filedataor with statement savefile close(but eibti still os chmod(pathname need for some srvrs partnames append(pathnamelist of local paths return partnames gets type from name #commonhtml dumpstatepage( form cgi fieldstorage(attaches saveattachments(formparse form input data cgi print_form(formto see server name from module or get-style url smtpservername commonhtml getstandardsmtpfields(formparms assumed to be in form or url here from commonhtml import getfield from getfield(form'from'to getfield(form'to'cc getfield(form'cc'subj getfield(form'subject'text getfield(form'text'if cc ='?'cc 'fetch value attributes empty fields may not be sent headers encoded per utf within mailtools if non-ascii parser mailtools mailparser(tos parser splitaddresses(tomultiple recip lists',sept ccs (cc and parser splitaddresses(cc)or 'extrahdrs [('cc'ccs)(' -mailer''pymailcgi ') resolve main text and text attachment encodingsdefault=ascii in mailtools the pymailcgi server
5,811
trytext encode(bodyencodingexcept (unicodeerrorlookuperror)bodyencoding 'utf- try ascii first (or latin- ?else use tuf as fallback (or config?tbdthis is more limited than pymailgui use utf for all attachmentswe can' ask here attachencodings ['utf- 'len(attachesignored for non-text parts encode and send sender mailtools silentmailsender(smtpservernametrysender sendmessage(fromtossubjextrahdrstextattachesbodytextencoding=bodyencodingattachesencodings=attachencodingsexceptcommonhtml errorpage('send mail error'elsecommonhtml confirmationpage('send mail'this script gets mail header and text input information from the edit page' form (or from query parameters in an explicit urland sends the message off using python' standard smtplib modulecourtesy of the mailtools package we studied mailtools in so won' say much more about it now notethoughthat because we are reusing its send callsent mail is automatically saved in sentmail txt file on the serverthere are no tools for viewing this in pymailcgi itselfbut it serves as log new in version the saveattachments function grabs any part files sent from the browser and stores them in temporary local files on the server from which they will be added to the mail when sent we covered cgi upload in detail at the end of see that discussion for more on how the code here works (as well as its limitations in python and this edition--we're attaching simple text here to accommodatethe business of attaching the files to the mail itself is automatic in mailtools utility in commonhtml ultimately fetches the name of the smtp server to receive the message from either the mailconfig module or the script' inputs (in form field or url query parameterif all goes wellwe're presented with generated confirmation pageas captured in figure - open file sentmail txt in pymailcgi' source directory if you want to see what the resulting mail' raw text looks like when sent (or fetch the message in an email client with raw text viewsuch as pymailguiin this versioneach attachment part is mime encoded per base with utf- unicode encoding in the multipart messagebut the main text part is sent as simple ascii if it works as such as we'll seethis send mail script is also used to deliver reply and forward messages for incoming pop mail the user interface for those operations is slightly different for composing new email from scratchbut as in pymailguithe submission handler logic has been factored into the sameshared code--replies and forwards are really just mail send operations with quoted text and preset header fields sending mail by smtp
5,812
notice that there are no usernames or passwords to be found hereas we saw in smtp usually requires only server that listens on the smtp portnot user account or password as we also saw in that smtp send operations that fail either raise python exception ( if the server host can' be reachedor return dictionary of failed recipientsour mailtools package modules insulate us from these details by always raising an exception in either case error pages if there is problem during mail deliverywe get an error page such as the one shown in figure - this page reflects failed recipient and includes stack trace generated by the standard library' traceback module on errors python detectsthe python error message and extra details would be displayed it' also worth pointing out that the commonhtml module encapsulates the generation of both the confirmation and the error pages so that all such pages look the same in pymailcgi no matter where and when they are produced logic that generates the mail edit page in commonhtml is reused by the reply and forward actionstoo (but with different mail headerscommon look-and-feel in factcommonhtml makes all pages look similar--it also provides common page header (topand footer (bottomgeneration functionswhich are used everywhere in the system you may have already noticed that all the pages so far follow the same patternthey start with title and horizontal rulehave something unique in the middleand end with another rulefollowed by python icon and link at the bottom this common look-and-feel is the product of shared code in commonhtmlit generates everything but the middle section for every page in the system (except the root pagea static html file the pymailcgi server
5,813
most importantif we ever change the header and footer format functions in the commonhtml moduleall our page' headers and footers will automatically be updated if you are interested in seeing how this encapsulated logic works right nowflip ahead to example - we'll explore its code after we study the rest of the mail site' pages using the send mail script outside browser initially wrote the send script to be used only within pymailcgi using values typed into the mail edit form but as we've seeninputs can be sent in either form fields or url query parameters because the send mail script checks for inputs in cgi inputs before importing from the mailconfig moduleit' also possible to call this script outside the edit page to send email--for instanceexplicitly typing url of this nature into your browser' address field (but all on one line and with no intervening spaces)oneditpagesend py?site=smtp rmi netfrom=lutz@rmi netto=lutz@rmi netsubject=test+urltext=hello+mark;this+is+mark sending mail by smtp
5,814
url string is lot to type into browser' address fieldof coursebut it might be useful if generated automatically by another script as we saw in and the module urllib request can then be used to submit such url string to the server from within python program example - shows one way to automate this example - pp \internet\web\pymailcgi\sendurl py ""###################################################################send email by building url like this from inputsoneditpagesend py?site=smtp rmi netfrom=lutz@rmi netto=lutz@rmi netsubject=test+urltext=hello+mark;this+is+mark ###################################################################""from urllib request import urlopen from urllib parse import quote_plus url 'url +'?site=%squote_plus(input('site>')url +'&from=%squote_plus(input('from>')url +'&to=%squote_plus(input('to >')url +'&subject=%squote_plus(input('subj>')url +'&text=%squote_plus(input('text>')or input loop print('reply html:'print(urlopen(urlread(decode()confirmation or error page html running this script from the system command line is yet another way to send an email message--this timeby contacting our cgi script on web server machine to do all the work the script sendurl py runs on any machine with python and socketslets us input mail parameters interactivelyand invokes another python script that lives on possibly remote machine it prints html returned by our cgi scriptc:\pp \internet\web\pymailcgisendurl py site>smtpout secureserver net from>pp @learning-python com to >lutz@learning-python com subj>testing sendurl py text>but sirit' only wafer-thin reply htmlpymailcgiconfirmation page (pp epymailcgi confirmation send mail operation was successful press the link below to return to the main page < href="<img src=/pythonpoweredsmall gifalign=left alt="[python logo]border= hspace= the pymailcgi server
5,815
the html reply printed by this script would normally be rendered into new web page if caught by browser such cryptic output might be less than idealbut you could easily search the reply string for its components to determine the result ( using the string find method or an in membership test to look for "successful")parse out its components with python' standard html parse or re modules (covered in )and so on the resulting mail message--viewedfor varietywith ' pymailgui program--shows up in this book' email account as seen in figure - (it' single text-part messagefigure - sendurl py result of coursethere are otherless remote ways to send email from client machine for instancethe python smtplib module (used by mailtoolsitself depends only upon the client and smtp server connections being operationalwhereas this script also depends on the web server machine and cgi script (requests go from client to web server to cgi script to smtp serverbecause our cgi script supports general urlsthoughit can do more than mailtohtml tag and can be invoked with urllib request outside the context of running web browser for instanceas discussed in scripts like sendurl py can be used to invoke and test server-side programs reading pop email so farwe've stepped through the path the system follows to send new mail let' now see what happens when we try to view incoming pop mail reading pop email
5,816
if you flip back to the main page in figure - you'll see view linkpressing it triggers the script in example - to run on the server example - pp \internet\web\pymailcgi\cgi-bin\onrootviewlink py #!/usr/bin/python ""###############################################################################on view link click on main/root html pagemake pop password input pagethis could almost be an html file because there are likely no input params yetbut wanted to use standard header/footer functions and display the site/user names which must be fetchedon submissiondoes not send the user along with password hereand only ever sends both as url params or hidden fields after the password has been encrypted by user-uploadable encryption module###############################################################################""page template pswdhtml ""please enter pop account password belowfor user "%sand site "%ssecurity notethe password you enter above will be transmitted over the internet to the server machinebut is not displayedis never transmitted in combination with username unless it is encrypted or obfuscatedand is never stored anywherenot on the server (it is only passed along as hidden fields in subsequent pages)and not on the client (no cookies are generatedthis is still not guaranteed to be totally safeuse your browser' back button to back out of pymailcgi at any time ""generate the password input page import commonhtml userpswdsite commonhtml getstandardpopfields({}commonhtml pageheader(kind='pop password input'print(pswdhtml (commonhtml urlrootusersite)commonhtml pagefooter(usual parms casefrom module herefrom html|url later this script is almost all embedded htmlthe triple-quoted pswdhtml string is printedwith string formatting to insert valuesin single step but because we need to fetch the username and server name to display on the generated pagethis is coded as an executable scriptnot as static html file the module commonhtml either loads usernames and server names from script inputs ( appended as query parameters to the script' urlor imports them from the mailconfig fileeither waywe don' want to hardcode them into this script or its htmlso simple html file won' do againin the cgi worldwe embed html code in python code and fill in its values this way the pymailcgi server
5,817
embedded in html code instead and run to produce valuessince this is scriptwe can also use the commonhtml page header and footer routines to render the generated reply page with common look-and-feelas shown in figure - figure - pymailcgi view password login page at this pagethe user is expected to enter the password for the pop email account of the user and server displayed notice that the actual password isn' displayedthe input field' html specifies type=passwordwhich works just like normal text fieldbut shows typed input as stars (see also the pymail program in for doing this at console and pymailgui in for doing this in tkinter gui the mail selection list page after you fill out the last page' password field and press its submit buttonthe password is shipped off to the script shown in example - example - pp \internet\web\pymailcgi\cgi-bin\onviewpswdsubmit py #!/usr/bin/python ""###############################################################################on submit in pop password input windowmake mail list view pagein we only fetch mail headers hereand fetch full message later upon requestwe still fetch all headers each time the index page is madecaching messages would require server-side(?database and session keyor other decode headers for list displaythough printer and browser must handle###############################################################################reading pop email
5,818
import cgi import loadmailcommonhtml from externs import mailtools from secret import encode maxhdr user-defined encoder module max length of email hdrs in list only pswd comes from page hererest usually in module formdata cgi fieldstorage(mailusermailpswdmailsite commonhtml getstandardpopfields(formdataparser mailtools mailparser(trynewmails loadmail loadmailhdrs(mailsitemailusermailpswdmailnum maillist [or use enumerate(for mail in newmailslist of hdr text msginfo [hdrs parser parseheaders(mailemail message message addrhdrs ('from''to''cc''bcc'decode names only for key in ('subject''from''date')rawhdr hdrs get(key'?'if key not in addrhdrsdechdr parser decodeheader(rawhdr decode for display elseencoded on sends dechdr parser decodeaddrheader(rawhdremail names only msginfo append(dechdr[:maxhdr]msginfo join(msginfomaillist append((msginfocommonhtml urlroot 'onviewlistlink py'{'mnum'mailnum'user'mailuserdata params 'pswd'encode(mailpswd)pass in url 'site'mailsite})not inputs mailnum + commonhtml listpage(maillist'mail selection list'exceptcommonhtml errorpage('error loading mail index'this script' main purpose is to generate selection list page for the user' email accountusing the password typed into the prior page (or passed in urlas usual with encapsulationmost of the details are hidden in other filesloadmail loadmailhdrs reuses the mailtools module package from to fetch email with the pop protocolwe need message count and mail headers here to display an index list in this versionthe software fetches only mail header text to save timenot full mail messages (provided your server supports the top command of the pop interfaceand most do--if notsee mailconfig to disable this the pymailcgi server
5,819
generates html to display passed-in list of tuples (texturlparameterdictionaryas list of hyperlinks in the reply pageparameter values show up as query parameters at the end of urls in the response the maillist list built here is used to create the body of the next page-- clickable email message selection list each generated hyperlink in the list page references constructed url that contains enough information for the next script to fetch and display particular email message as we learned in the preceding this is simple kind of state retention between pages and scripts if all goes wellthe mail selection list page html generated by this script is rendered as in figure - if your inbox is as large as some of mineyou'll probably need to scroll down to see the end of this page this page follows the common look-and-feel for all pymailcgi pagesthanks to commonhtml figure - pymailcgi view selection list pagetop if the script can' access your email account ( because you typed the wrong password)its try statement handler instead produces commonly formatted error page reading pop email
5,820
figure - shows one that gives the python exception and details as part of the reply after python-raised exception is caughtas usualthe exception details are fetched from sys exc_infoand python' traceback module is used to generate stack trace passing state information in url link parameters the central mechanism at work in example - is the generation of urls that embed message numbers and mail account information clicking on any of the view links in the selection list triggers another scriptwhich uses information in the link' url parameters to fetch and display the selected email as mentioned in because the list' links are programmed to "knowhow to load particular messagethey effectively remember what to do next figure - shows part of the html generated by this script (use your web browser view source option to see this for yourself-- did save as and then opened the result which invoked internet explorer' source viewer on my laptopdid you get all the details in figure - you may not be able to read generated html like thisbut your browser can for the sake of readers afflicted with human-parsing the pymailcgi server
5,821
limitationshere is what one of those link lines looks likereformatted with line breaks and spaces to make it easier to understand< href="onviewlistlink pypswd=wtgmpsjeb mnum= user=pp % learning-python comsite=pop secureserver net">view among our weapons are these cardinal@hotmail com fri may : pymailcgi generates relative minimal urls (server and pathname values come from the prior pageunless set in commonhtmlclicking on the word view in the hyperlink rendered from this html code triggers the onviewlistlink script as usualpassing it all the parameters embedded at the end of the urlthe pop usernamethe pop message number of the message associated with this linkand the pop password and site information these values will be available in the object returned by cgi fieldstorage in the next script run note that the mnum pop message number parameter differs in each link because each opens different message when clicked and that the text after comes from message headers extracted by the mailtools packageusing the email package the commonhtml module escapes all of the link parameters with the urllib parse modulenot cgi escapebecause they are part of url this can matter in the pswd password parameter--its value might be encrypted and arbitrary bytesbut urllib parse additionally escapes nonsafe characters in the encrypted string per url convention (it translates to %xx character sequencesit' ok if the encryptor yields odd--even nonprintable--characters because url encoding makes them legible for transmission when the password reaches the next scriptcgi fieldstorage undoes url escape sequencesleaving the encrypted password string without escapes it' instructive to see how commonhtml builds up the stateful link parameters earlierwe learned how to use the urllib parse quote_plus call to escape string for inclusion in urlsreading pop email
5,822
urllib parse quote_plus("there' bugger all down here on earth"'there% +bugger+all+down+here+on+earththe module commonhtmlthoughcalls the higher-level urllib parse urlencode functionwhich translates dictionary of name:value pairs into complete url query parameter stringready to add after marker in url for instancehere is urlencode in action at the interactive promptparmdict {'user''brian''pswd''#!/spam''text''say no moresquire!'urllib parse urlencode(parmdict'text=say+no+more% +squire% &pswd=% % % fspam&user=brian"% ?% ("'internallyurlencode passes each name and value in the dictionary to the built-in str function (to make sure they are strings)and then runs each one through url lib parse quote_plus as they are added to the result the cgi script builds up list of similar dictionaries and passes it to commonhtml to be formatted into selection list page in broader termsgenerating urls with parameters like this is one way to pass state information to the next script (along with cookieshidden form input fieldsand server databasesdiscussed in without such state informationusers would have to reenter the usernamepasswordand site name on every page they visit along the way incidentallythe list generated by this script is not radically different in functionality from what we built in the pymailgui program in though the two differ cosmetically figure - shows this strictly client-side gui' view on the same email list displayed in figure - it' important to keep in mind that pymailgui uses the tkinter gui library to build up user interface instead of sending html to browser it also runs entirely on the client and talks directly to email serversdownloading mail from the pop server to the client machine over sockets on demand because it retains memory for the duration of the sessionpymailgui can easily minimize mail server access after the initial header loadit needs to load only newly arrived email headers on subsequent load requests moreoverit can update its email index in-memory on deletions instead of reloading anew from the serverand it has enough state to perform safe deletions of messages that check for server inbox matches pymailgui also remembers emails you've already viewed-they need not be reloaded again while the program runs technicallyagainyou should generally escape separators in generated url links by running the url through cgi escapeif any parameter' name could be the same as that of an html character escape code ( &amp=highsee for more detailsthey aren' escaped here because there are no clashes between url and html the pymailcgi server
5,823
in contrastpymailcgi runs on the web server machine and simply displays mail text on the client' browser--mail is downloaded from the pop server machine to the web serverwhere cgi scripts are run due to the autonomous nature of cgi scriptspymailcgi by itself has no automatic memory that spans pages and may need to reload headers and already viewed messages during single session these architecture differences have some important ramificationswhich we'll discuss later in this security protocols in onviewpswdsubmit' source code (example - )notice that password inputs are passed to an encode function as they are added to the parameters dictionarythis causes them to show up encrypted or otherwise obfuscated in hyperlinked urls they are also url encoded for transmission (with escapes if neededand are later decoded and decrypted within other scripts as needed to access the pop account the password encryption stepencodeis at the heart of pymailcgi' security policy in python todaythe standard library' ssl module supports secure sockets layer (sslwith its socket wrapper callif the required library is built into your python ssl automatically encrypts transmitted data to make it safe to pass over the net unfortunatelyfor reasons we'll discuss when we reach the secret py module later in this (see example - )this wasn' universal solution for pymailcgi' password data in shortthe python-coded web server we're using doesn' directly support its end of secure http encrypted dialoghttps because of thatan alternative scheme was reading pop email
5,824
net in transit here' how it works when this script is invoked by the password input page' formit gets only one input parameterthe password typed into the form the username is imported from mailconfig module installed on the serverit is not transmitted together with the unencrypted password because such combination could be harmful if intercepted to pass the pop username and password to the next page as state informationthis script adds them to the end of the mail selection list urlsbut only after the password has been encrypted or obfuscated by secret encode-- function in module that lives on the server and may vary in every location that pymailcgi is installed in factpymailcgi was written to not have to know about the password encryptor at allbecause the encoder is separate moduleyou can provide any flavor you like unless you also publish your encoder modulethe encoded password shipped with the username won' mean much if seen the upshot is that normally pymailcgi never sends or receives both username and password values together in single transactionunless the password is encrypted or obfuscated with an encryptor of your choice this limits its utility somewhat (since only single account username can be installed on the server)but the alternative of popping up two pages--one for password entry and one for username--seems even less friendly in generalif you want to read your mail with the system as codedyou have to install its files on your serveredit its mailconfig py to reflect your account detailsand change its secret py encoder and decoder as desired reading mail with direct urls one exceptionsince any cgi script can be invoked with parameters in an explicit url instead of form field valuesand since commonhtml tries to fetch inputs from the form object before importing them from mailconfigit is possible for any person to use this script if installed at an accessible address to check his or her mail without installing and configuring copy of pymailcgi of their own for examplea url such as the following typed into your browser' address field or submitted with tools such as url lib request (but without the line break used to make it fit here)onviewpswdsubmit py?user=lutz&pswd=guess&site=pop earthlink net will actually load email into selection list page such as that in figure - using whatever userpasswordand mail site names are appended to the url from the selection listyou may then viewreplyforwardand delete email notice that at this point in the interactionthe password you send in url of this form is not encrypted later scripts expect that the password inputs will be sent encryptedthoughwhich makes it more difficult to use them with explicit urls (you would need to match the encrypted or obfuscated form produced by the secret module on the the pymailcgi server
5,825
listand they remain encoded in urls and hidden form fields thereafter but you shouldn' use url like thisunless you don' care about exposing your email password sending your unencrypted mail user id and password strings across the net in url such as this is unsafe and open to interception in factit' like giving away your email--anyone who intercepts this url or views it in server logfile will have complete access to your email account it is made even more treacherous by the fact that this url format appears in book that will be distributed all around the world if you care about security and want to use pymailcgi on remote serverinstall it on your server and configure mailconfig and secret that should at least guarantee that both your user and password information will never be transmitted unencrypted in single transaction this scheme still may not be foolproofso be careful out there without secure http and socketsthe internet is "use at your own riskmedium the message view page back to our page flowat this pointwe are still viewing the message selection list in figure - when we click on one of its generated hyperlinksthe stateful url invokes the script in example - on the serversending the selected message number and mail account information (userpasswordand siteas parameters on the end of the script' url example - pp \internet\web\pymailcgi\cgi-bin\onviewlistlink py #!/usr/bin/python ""###############################################################################on user click of message link in main selection listmake mail view pagecgi fieldstorage undoes any urllib parse escapes in link' input parameters (%xx and '+for spaces already undone)in we only fetch mail herenot the entire list againin we also find mail' main text part intelligently instead of blindly displaying full text (with any attachments)and we generate links to attachment files saved on the serversaved attachment files only work for user and messagemost enhancements inherited from mailtools pkg mailtools decodes the message' full-text bytes prior to email parsing for displaymailtools decodes main textcommonhtml decodes message hdrs###############################################################################""import cgi import commonhtmlsecret from externs import mailtools #commonhtml dumpstatepage( reading pop email
5,826
""save fetched email' parts to files on server to be viewed in user' web browser ""import os if not os path exists(savedir)in cgi script' cwd on server os mkdir(savedirwill open per your browser for filename in os listdir(savedir)clean up last messagetempdirpath os path join(savedirfilenameos remove(dirpathtypesandnames parser saveparts(savedirmessagefilenames [fname for (ctypefnamein typesandnamesfor filename in filenamesos chmod(filename some srvrs may need read/write return filenames form cgi fieldstorage(userpswdsite commonhtml getstandardpopfields(formpswd secret decode(pswdtrymsgnum form['mnum'value parser mailtools mailparser(fetcher mailtools silentmailfetcher(siteuserpswdfulltext fetcher downloadmessage(int(msgnum)message parser parsemessage(fulltextparts saveattachments(messageparsermtypecontent parser findmaintext(messagecommonhtml viewpage(msgnummessagecontentformpartsexceptcommonhtml errorpage('error loading message'from url link don' evalemail pkg message for url links first txt part encoded pswd againmuch of the work here happens in the commonhtml modulelisted later in this section (see example - this script adds logic to decode the input password (using the configurable secret encryption moduleand extract the selected mail' headers and text using the mailtools module package from again the full text of the selected message is ultimately fetchedparsedand decoded by mailtoolsusing the standard library' poplib module and email package although we'll have to refetch this message if viewed againversion and later do not grab all mails to get just the one selected +also new in version the saveattachments function in this script splits off the parts of fetched message and stores them in directory on the web server machine this was discussed earlier in this -the view page is then augmented with url links that point at the saved part files your web browser will open them according to their filenames and content all the work of part extractiondecodingand naming is +notice that the message number arrives as string and must be converted to an integer in order to be used to fetch the message but we're careful not to convert with eval heresince this is string passed over the net and could have arrived embedded at the end of an arbitrary url (remember that earlier warning? the pymailcgi server
5,827
message is fetched they are also currently stored in single directory and so apply to only single user if the message can be loaded and parsed successfullythe result pageshown in figure - allows us to viewbut not editthe mail' text the function commonhtml view page generates "read-onlyhtml option for all the text widgets in this page if you look closelyyou'll notice that this is the mail we sent to ourselves in figure - and which showed up at the end of the list in figure - figure - pymailcgi view page view pages like this have pull-down action selection list near the bottomif you want to do moreuse this list to pick an action (replyforwardor deleteand click on the next button to proceed to the next screen if you're just in browsing frame of mindclick the "back to root pagelink at the bottom to return to the main pageor use your browser' back button to return to the selection list page as mentionedfigure - displays the mail we sent earlier in this being viewed after being fetched notice its "parts:links--when clickedthey trigger urls that open the temporary part files on the serveraccording to your browser' rules for reading pop email
5,828
the file type for instanceclicking on the txtfile will likely open it in either the browser or text editor in other mailsclicking on jpgfiles may open an image viewerpdfmay open adobe readerand so on figure - shows the result of clicking the pyattachment part of figure - ' message in chrome passing state information in html hidden input fields what you don' see on the view page in figure - is just as important as what you do see we need to defer to example - for coding detailsbut something new is going on here the original message numberas well as the pop user and (still encodedpassword information sent to this script as part of the stateful link' urlwind up being copied into the html used to create this view pageas the values of hidden input fields in the form the hidden field generation code in commonhtml looks like thisprint('urlrootprint('msgnumprint('userfrom page|url print('sitefor deletes print('pswdpswd encoded as we've learnedmuch like parameters in generated hyperlink urlshidden fields in page' html allow us to embed state information inside this web page itself unless you view that page' sourceyou can' see this state information because hidden fields are never displayed but when this form' submit button is clickedhidden field values are automatically transmitted to the next script along with the visible fields on the form the pymailcgi server
5,829
figure - shows part of the source code generated for another message' view pagethe hidden input fields used to pass selected mail state information are embedded near the top the net effect is that hidden input fields in htmljust like parameters at the end of generated urlsact like temporary storage areas and retain state between pages and user interaction steps both are the web' simplest equivalent to programming language variables they come in handy anytime your application needs to remember something between pages hidden fields are especially useful if you cannot invoke the next script from generated url hyperlink with parameters for instancethe next action in our script is form submit button (next)not hyperlinkso hidden fields are used to pass state as beforewithout these hidden fieldsusers would need to reenter pop account details somewhere on the view page if they were needed by the next script (in our examplethey are required if the next action is deletereading pop email
5,830
notice that everything you see on the message view page' html in figure - is escaped with cgi escape header fields and the text of the mail itself might contain characters that are special to html and must be translated as usual for instancebecause some mailers allow you to send messages in html formatit' possible that an email' text could contain tagwhich might throw the reply page hopelessly out of sync if not escaped one subtlety herehtml escapes are important only when text is sent to the browser initially by the cgi script if that text is later sent out again to another script ( by sending reply mail)the text will be back in its originalnonescaped format when received again on the server the browser parses out escape codes and does not put them back again when uploading form dataso we don' need to undo escapes later for examplehere is part of the escaped text area sent to browser during reply transaction (use your browser' view source option to see this live)textmore stuff --mark lutz ([pymailcgi &gtoriginal message----&gtfromlutz@rmi net &gttolutz@rmi net &gtdatetue may : : &gt&gt&lt;table&gt;&lt;textarea&gt&gt&lt;/textarea&gt;&lt;/table&gt&gt--mark lutz (&gt&gt&gt&gtoriginal message [pymailcgi after this reply is deliveredits text looks as it did before escapes (and exactly as it appeared to the user in the message edit web page)more stuff --mark lutz (original message----fromlutz@rmi net tolutz@rmi net datetue may : : --mark lutz ([pymailcgi the pymailcgi server [pymailcgi
5,831
original message beyond the normal textthe password gets special html escapes treatment as well though not shown in our examplesthe hidden password field of the generated html screenshot (figure - can look downright bizarre when encryption is applied it turns out that the pop password is still encrypted when placed in hidden fields of the html for securitythey have to be values of page' hidden fields can be seen with browser' view source optionand it' not impossible that the text of this page could be saved to file or intercepted off the net the password is no longer url encoded when put in the hidden fieldhowevereven though it was when it appeared as query parameter at the end of stateful url in the mail list page depending on your encryption modulethe password might now contain nonprintable characters when generated as hidden field value herethe browser doesn' careas long as the field is run through cgi escape like everything else added to the html reply stream the commonhtml module is careful to route all text and headers through cgi escape as the view page is constructed as comparisonfigure - shows what the mail message captured in figure - looks like when viewed in pymailguithe client-side "desktoptkinter-based email tool from in that programmessage parts are listed with the parts button and are extractedsavedand opened with the split buttonwe also get quickaccess buttons to parts and attachments just below the message headers the net effect is similar from an end user' perspective figure - pymailgui viewersame message as figure - reading pop email
5,832
need to care about things such as passing state in urls or hidden fields (it saves state in python in-process variables and memory)and there' no notion of escaping html and url strings (there are no browsersand no network transmission steps once mail is downloadedit also doesn' have to rely on temporary server file links to give access to message parts--the message is retained in memory attached to window object and lives on between interactions on the other handpymailgui does require python to be installed on the clientbut we'll return to that in few pages processing fetched mail at this point in our pymailcgi web interactionwe are viewing an email message (figure - that was chosen from the selection list page on the message view pageselecting an action from the pull-down list and clicking the next button invokes the script in example - on the server to perform replyforwardor delete operation for the selected message viewed example - pp \internet\web\pymailcgi\cgi-bin\onviewpageaction py #!/usr/bin/python ""###############################################################################on submit in mail view windowaction selected=(fwdreplydelete)in +we reuse the mailtools delete logic originally coded for pymailgui###############################################################################""import cgicommonhtmlsecret from externs import mailtoolsmailconfig from commonhtml import getfield def quotetext(form)""note that headers come from the prior page' form herenot from parsing the mail message againthat means that commonhtml viewpage must pass along date as hidden field ""parser mailtools mailparser(addrhdrs ('from''to''cc''bcc'decode name only quoted '\noriginal message\nfor hdr in ('from''to''date')rawhdr getfield(formhdrif hdr not in addrhdrsdechdr parser decodeheader(rawhdr decode for display elseencoded on sends dechdr parser decodeaddrheader(rawhdremail names only quoted +'% % \ (hdrdechdrquoted +'\ngetfield(form'text'quoted '\nquoted replace('\ ''\ 'return quoted the pymailcgi server
5,833
userpswdsite commonhtml getstandardpopfields(formpswd secret decode(pswdtryif form['action'value ='reply'headers {'from'mailconfig myaddress commonhtml decodes 'to'getfield(form'from')'cc'mailconfig myaddress'subject''regetfield(form'subject')commonhtml editpage('reply'headersquotetext(form)elif form['action'value ='forward'headers {'from'mailconfig myaddress commonhtml decodes 'to''''cc'mailconfig myaddress'subject''fwdgetfield(form'subject')commonhtml editpage('forward'headersquotetext(form)elif form['action'value ='delete'mnum field is required here msgnum int(form['mnum'valuebut not eval()may be code fetcher mailtools silentmailfetcher(siteuserpswdfetcher deletemessages([msgnum]commonhtml confirmationpage('delete'elseassert false'invalid view action requestedexceptcommonhtml errorpage('cannot process view action'this script receives all information about the selected message as form input field data (some hidden and possibly encryptedsome notalong with the selected action' name the next step in the interaction depends upon the action selectedreply and forward actions generate message edit page with the original message' lines automatically quoted with leading delete actions trigger immediate deletion of the email being viewedusing tool imported from the mailtools module package from all these actions use data passed in from the prior page' formbut only the delete action cares about the pop username and password and must decode the password received (it arrives here from hidden form input fields generated in the prior page' htmlreply and forward if you select reply as the next actionthe message edit page in figure - is generated by the script text on this page is editableand pressing this page' send button again triggers the send mail script we saw in example - if all goes wellwe'll receive the processing fetched mail
5,834
same confirmation page we got earlier when writing new mail from scratch (figure - forward operations are virtually the sameexcept for few email header differences all of this busy-ness comes "for free,because reply and forward pages are generated by calling commonhtml editpagethe same utility used to create new mail composition page herewe simply pass preformatted header line strings to the utility ( replies add "re:to the subject textwe applied the same sort of reuse trick in pymailguibut in different context in pymailcgione script handles three pagesin pymailguione superclass and callback method handles three buttonsbut the architecture is similar in spirit delete selecting the delete action on message view page and pressing next will cause the onviewpageaction script to immediately delete the message being viewed deletions are performed by calling reusable delete utility function coded in ' mail the pymailcgi server
5,835
silent call that prevents print call statements in the utility from showing up in the html reply stream (they are just status messagesnot html codein this versionwe get the same capability from the "silentclasses in mailtools figure - shows delete operation in action figure - pymailcgi view pagedelete selected by the waynotice the varied type of attachment parts on the mail' page in figure - in version we can send only text attachments due to the python cgi uploads parsing regression described earlierbut we can still view arbitrary attachment types in fetched mails received from other senders this includes images and pdfs such attachments open according to your browser' conventionsfigure - shows how chrome handles click on the monkeys jpg link at the bottom of the pymailcgi page in figure - --it' the same image we sent by ftp in and via pymailgui in but here it has been extracted by pymailcgi cgi script and is being returned by locally running web server back to our pending deletion as mentioneddelete is the only action that uses the pop account information (userpasswordand sitethat was passed in from hidden fields on the prior message view page by contrastthe reply and forward actions processing fetched mail
5,836
format an edit pagewhich ultimately sends message to the smtp serverno pop information is needed or passed but at this point in the interactionthe pop password has racked up more than few frequent flyer miles in factit may have crossed phone linessatellite linksand continents on its journey from machine to machine let' trace through the voyage input (client)the password starts life by being typed into the login page on the client (or being embedded in an explicit url)unencrypted if typed into the input form in web browsereach character is displayed as star (* fetch index (client to cgi server to pop server)it is next passed from the client to the cgi script on the serverwhich sends it on to your pop server in order to load mail index the client sends only the passwordunencrypted list page urls (cgi server to client)to direct the next script' behaviorthe password is embedded in the mail selection list web page itself as hyperlink url query parametersencrypted (or otherwise obfuscatedand url encoded fetch message (client to cgi server to pop server)when an email is selected from the listthe password is sent to the next script named within the link' urlthe cgi script decodes it and passes it on to the pop server to fetch the selected message the pymailcgi server
5,837
password is embedded in the view page itself as html hidden input fieldsencrypted or obfuscatedand html escaped delete message (client to cgi server to pop server)finallythe password is again passed from client to cgi serverthis time as hidden form field valuesthe cgi script decodes it and passes it to the pop server to delete along the wayscripts have passed the password between pages as both url query parameter and an html hidden input fieldeither waythey have always passed its encrypted or obfuscated string and have never passed an unencoded password and username together in any transaction upon delete requestthe password must be decoded here using the secret module before passing it to the pop server if the script can access the pop server again and delete the selected messageanother confirmation page appearsas shown in figure - (there is currently no verification for the deleteso be carefulfigure - pymailcgi delete confirmation one subtlety for replies and forwardsthe onviewpageaction mail action script builds up >-quoted representation of the original messagewith original "from:""to:"and "date:header lines prepended to the mail' original text noticethoughthat the original message' headers are fetched from the cgi form inputnot by reparsing the original mail (the mail is not readily available at this pointin other wordsthe script gets mail header values from the form input fields of the view page because there is no "datefield on the view pagethe original message' date is also passed along to the action script as hidden input field to avoid reloading the message try tracing through the code in this listings ahead to see whether you can follow dates from page to page processing fetched mail
5,838
note that you probably should click the "back to root pagelink in figure - after successful deletion--don' use your browser' back button to return to the message selection list at this point because the delete has changed the relative numbers of some messages in the list the pymailgui client program worked around this problem by automatically updating its in-memory message cache and refreshing the index list on deletionsbut pymailcgi doesn' currently have way to mark older pages as obsolete if your browser reruns server-side scripts as you press your back buttonyou'll regenerate and hence refresh the list anyhow if your browser displays cached pages as you go backthoughyou might see the deleted message still present in the list worseclicking on view link in an old selection list page may not bring up the message you think it shouldif it appears in the list after message that was deleted this is property of pop email in generalwhich we have discussed before in this bookincoming mail simply adds to the mail list with higher message numbersbut deletions remove mail from arbitrary locations in the list and hence change message numbers for all mail following the ones deleted inbox synchronization error potential as we saw in even the pymailgui client has the potential to get some message numbers wrong if mail is deleted by another program while the gui is open-in second pymailgui instancefor exampleor in simultaneously running pymailcgi server session this can also occur if the email server automatically deletes message after the mail list has been loaded--for instancemoving it from inbox to undeliverable on errors this is why pymailgui went out of its way to detect server inbox synchronization errors on loads and deletesusing mailtools package utilities its deletionsfor instancematch saved email headers with those for the corresponding message number in the server' inboxto ensure accuracy similar test is performed on loads on mismatchesthe mail index is automatically reloaded and updated unfortunatelywithout additional state informationpymailcgi cannot detect such errorsit has no email list to compare against when messages are viewed or deletedonly the message number in link or hidden form field in the worst casepymailcgi cannot guarantee that deletes remove the intended mail-it' unlikely but not impossible that mail earlier in the list may have been deleted between the time message numbers were fetched and mail is deleted at the server without extra state information on the serverpymailcgi cannot use the safe deletion or synchronization error checks in the mailtools modules to check whether subject message numbers are still valid to guarantee safe deletespymailcgi would require state retentionwhich maps message numbers passed in pages to saved mail headers fetched when the numbers were the pymailcgi server
5,839
three sections outline suggested improvements and potential exercises alternativepassing header text in hidden input fields (pymailcgi_ perhaps the simplest way to guarantee accurate deletions is to embed the displayed message' full header text in the message view page itselfas hidden form fieldsusing the following schemeonviewlistlink py embed the header text in hidden form fieldsescaped per html conventions with cgi escape (with its quote argument set to true to translate any nested quotes in the header textonviewpageaction py retrieve the embedded header text from the form' input fieldsand pass it along to the safe deletion call in mailtools for header matching this would be small code changebut it might require an extra headers fetch in the first of these scripts (it currently loads the full mail text)and it would require building phony list to represent all mailsheaders (we would have headers for and delete only one mail herealternativelythe header text could be extracted from the fetched full mail textby splitting on the blank line that separates headers and message body text moreoverthis would increase the size of the data transmitted both from client and server--mail header text is commonly greater than kb in sizeand it may be larger this is small amount of extra data in modern termsbut it' possible that this may run up against size limitations in some client or server systems and reallythis scheme is incomplete it addresses only deletion accuracy and does nothing about other synchronization errors in general for examplethe system still may fetch and display the wrong message from message list pageafter deletions of mails earlier in the inbox performed elsewhere in factthis technique guarantees only that the message displayed in view window will be the one deleted for that view window' delete action it does not ensure that the mail displayed or deleted in the view window corresponds to the selection made by the user in the mail index list more specificallybecause this scheme embeds headers in the html of view windowsits header matching on deletion is useful only if messages earlier in the inbox are deleted elsewhere after mail has already been opened for viewing if the inbox is changed elsewhere before mail is opened in view windowthe wrong mail may be fetched from the index page in that eventthis scheme avoids deleting mail other than the one displayed in view windowbut it assumes the user will catch the mistake and avoid deleting if the wrong mail is loaded from the index page though such cases are rarethis behavior is less than user friendly even though it is incompletethis change does at least avoid deleting the wrong email if the server' inbox changes while message is being viewed--the mail displayed will processing fetched mail
5,840
implemented in the following directory of the book' examples distributionpp \internet\web\dev\pymailcgi_ when developedit worked under the firefox web browser and it requires just more than lines of code changes among three source fileslisted here (search for "#experimentalto find the changes made in the source files yourself)onviewlistlink py hdrstext fulltext split('\ \ ')[ use blank line commonhtml viewpageencodes passwd msgnummessagecontentformhdrstextpartscommonhtml py def viewpage(msgnumheaderstextformhdrstextparts=[])delete needs hdrs text for inbox sync testscan be multi- large hdrstext cgi escape(hdrstextquote=trueescape '"too print('hdrstextonviewpageaction py fetcher mailtools silentmailfetcher(siteuserpswd#fetcher deletemessages([msgnum]hdrstext getfield(form'hdrstext''\nhdrstext hdrstext replace('\ \ ''\ 'get \ from top dummyhdrslist [nonemsgnum only one msg hdr dummyhdrslist[msgnum- hdrstext in hidden field fetcher deletemessagessafely([msgnum]dummyhdrslistexc on sync err commonhtml confirmationpage('delete'to run this version locallyrun the webserver script from example - (in with the dev subdirectory nameand unique port number if you want to run both the original and the experimental versions for instancec:\pp \internet\webwebserver py dev\pymailcgi_ command line web browser url although this version works on browsers testedit is considered tentative (and was not used for this and not updated for python in this editionbecause it is an incomplete solution in those rare cases where the server' inbox changes in ways that invalidate message numbers after server fetchesthis version avoids inaccurate deletionsbut index lists may still become out of sync messages fetches may still be inaccurateand addressing this likely entails more sophisticated state retention options note that in most casesthe message-id header would be sufficient for matching against mails to be deleted in the inboxand it might be all that is required to pass from page to page howeverbecause this field is optional and can be forged to have any valuethis might not always be reliable way to identify matched messagesfull header the pymailcgi server
5,841
more details alternativeserver-side files for headers the main limitation of the prior section' technique is that it addressed only deletions of already fetched emails to catch other kinds of inbox synchronization errorswe would have to also record headers fetched when the index list page was constructed since the index list page uses url query parameters to record stateadding large header texts as an additional parameter on the urls is not likely viable option in principlethe header text of all mails in the list could be embedded in the index page as single hidden fieldbut this might add prohibitive size and transmission overheads as perhaps more complete approacheach time the mail index list page is generated in onviewpswdsubmit pyfetched headers of all messages could be saved in flat file on the serverwith generated unique name (possibly from timeprocess idand usernamethat file' name could be passed along with message numbers in pages as an extra hidden field or query parameter on deletionsthe header' filename could be used by onviewpageaction py to load the saved headers from the flat fileto be passed to the safe delete call in mailtools on fetchesthe header file could also be used for general synchronization tests to avoid loading and displaying the wrong mail some sort of aging scheme would be required to delete the header save files eventually (the index page script might clean up old files)and we might also have to consider multiuser issues this scheme essentially uses server-side files to emulate pymailgui' in-process memorythough it is complicated by the fact that users may back up in their browser-deleting from view pages fetched with earlier list pagesattempting to refetch from an earlier list page and so on in generalit may be necessary to analyze all possible forward and backward flows through pages (it is essentially state machineheader save files might also be used to detect synchronization errors on fetches and may be removed on deletions to effectively disable actions in prior page statesthough header matching may suffice to ensure deletion accuracy alternativedelete on load as final alternativemail clients could delete all email off the server as soon as it is downloadedsuch that deletions wouldn' impact pop identifiers (microsoft outlook may use this scheme by defaultfor instancehoweverthis requires additional mechanisms for storing deleted email persistently for later accessand it means you can view fetched mail only on the machine to which it was downloaded since both pymailgui and pymailcgi are intended to be used on variety of machinesmail is kept on the pop server by default processing fetched mail
5,842
pymailcgiyou should not delete mails with it in an important accountunless you employ one of the solution schemes described or you use other tools to save mails to be deleted before deletion adding state retention to ensure general inbox synchronization may make an interesting exercisebut would also add more code than we have space for hereespecially if generalized for multiple simultaneous site users utility modules this section presents the source code of the utility modules imported and used by the page scripts shown earlier as installedall of these modules live in the same directory as the cgi scriptsto make imports simple--they are found in the current working directory there aren' any new screenshots to see here because these are utilitiesnot cgi scripts moreoverthese modules aren' all that useful to study in isolation and are included here primarily to be referenced as you go through the cgi scriptscode listed previously see earlier in this for additional details not repeated here external components and configuration when running pymailcgi out of its own directory in the book examples distribution treeit relies on number of external modules that are potentially located elsewhere because all of these are accessible from the pp package rootthey can be imported with dotted-path names as usualrelative to the root in case this setup ever changesthoughthe module in example - encapsulates the location of all external dependenciesif they ever movethis is the only file that must be changed example - pp \internet\web\pymailcgi\cgi-bin\externs py ""isolate all imports of modules that live outside of the pymailcgi directoryso that their location must only be changed here if movedwe reuse the mailconfig settings that were used for pymailgui in ch pp /' container must be on sys path to use the last import here""import sys #sys path insert( ' :\users\mark\stuff\books\ \pp \dev\examples'sys path insert( 'relative to script dir import mailconfig from pp internet email import mailtools local version mailtools package this module simply preimports all external names needed by pymailcgi into its own namespace see for more on the mailtools package modulessource code imported and reused hereas for pymailguimuch of the magic behind pymailcgi is actually implemented in mailtools the pymailcgi server
5,843
in and expanded in but it simply loads all attributes from the version we wrote in to avoid redundancyand customizes as desiredthe local version is listed in example - example - pp \internet\email\pymailcgi\cgi-bin\mailconfig py ""user configuration settings for various email programs (pymailcgi version)email scripts get their server names and other email config options from this modulechange me to reflect your machine namessigand preferences""from pp internet email mailconfig import reuse ch configs fetchlimit emaximum number headers/emails to fetch on loads (dflt= pop mail interface our next utility modulethe loadmail file in example - depends on external files and encapsulates access to mail on the remote pop server machine it currently exports one functionloadmailhdrswhich returns list of the header text (onlyof all mail in the specified pop accountcallers are unaware of whether this mail is fetched over the netlives in memoryor is loaded from persistent storage medium on the cgi server machine that is by design--because loadmail changes won' impact its clientsit is mostly hook for future expansion example - pp \internet\web\pymailcgi\cgi-bin\loadmail py ""mail list loaderfuture--change me to save mail list between cgi script runsto avoid reloading all mail each timethis won' impact clients that use the interfaces here if done wellfor nowto keep this simplereloads all mail for each list page +we now only load message headers (via top)not full msgbut still fetch all hdrs for each index list--in-memory caches don' work in stateless cgi scriptand require real (likely server-sidedatabase""from commonhtml import runsilent from externs import mailtools suppress prints (no verbose flagshared with pymailgui load all mail from number up this may trigger an exception import sys def progress(*args)not used sys stderr write(str(args'\ 'def loadmailhdrs(mailservermailusermailpswd)fetcher mailtools silentmailfetcher(mailservermailusermailpswdhdrssizesfull fetcher downloadallheaders(get list of hdr text return hdrs utility modules
5,844
mailtools silentmailfetcher class (reused here from uses the python poplib module to fetch mail over sockets the silent class prevents mailtools print call statements from going to the html reply stream (although any exceptions are allowed to propagate there normallyin this versionloadmail loads just the header text portions of all incoming email to generate the selection list page howeverit still reloads headers every time you refetch the selection list page as mentioned earlierthis scheme is better than the prior versionbut it can still be slow if you have lots of email sitting on your server server-side database techniquescombined with scheme for invalidating message lists on deletions and new receiptsmight alleviate some of this bottleneck because the interface exported by loadmail would likely not need to change to introduce caching mechanismclients of this module would likely still work unchanged pop password encryption we discussed pymailcgi' security protocols in the abstract earlier in this herewe look at their concrete implementation pymailcgi passes user and password state information from page to page using hidden form fields and url query parameters embedded in html reply pages we studied these techniques in the prior such data is transmitted as simple text over network sockets--within the html reply stream from the serverand as parameters in the request from the client as suchit is subject to security issues this isn' concern if you are running local web server on your machineas all our examples do the data is being shipped back and forth between two programs running on your computerand it is not accessible to the outside world if you want to install pymailcgi on remote web server machinethoughthis can be an issue because this data is sensitivewe' ideally like some way to hide it in transit and prevent it from being viewed in server logs the policies used to address this have varied across this book' lifespanas options have come and gonethe second edition of this book developed custom encryption module using the standard library' rotor encryption module this module was used to encrypt data inserted into the server' reply streamand then to later decrypt it when it was returned as parameter from the client unfortunatelyin python and laterthe rotor module is no longer available in the standard libraryit was withdrawn due to security concerns this seems somewhat extreme measure (rotor was adequate for simpler applications)but rotor is no longer usable solution in recent releases the third edition of this book extended the model of the secondby adding support for encrypting passwords with the third-party and open source pycrypto system regrettablythis system is available for python but still not for as write these words for the fourth edition in mid- (though some progress on the pymailcgi server
5,845
running server deployed for this book still does not support https in python -the ultimate solution to web securitywhich 'll say more about in moment because of all the foregoingthis fourth edition has legacy support for both rotor and pycrypto if they are installedbut falls back on simplistic password obfuscator which may be different at each pymailcgi installation since this release is something of prototype in generalfurther refinement of this modelincluding support for https under more robust web serversis left as exercise in generalthere are variety of approaches to encrypting information transferred back and forth between client and server unfortunately againnone is easily implemented for this examplenone is universally applicableand most involve tools or techniques that are well beyond the scope and size constraints of this text to sample some of the available optionsthoughthe sections that follow contain brief rundown of some of the common techniques in this domain manual data encryptionrotor (defunctin principlecgi scripts can manually encrypt any sensitive data they insert into reply streamsas pymailcgi did in this book' second edition with the removal of the rotor modulethoughpython ' standard library has no encryption tools for this task moreoverusing the original rotor module' code is not advisable from maintenance perspective and would not be straightforwardsince it was coded in the language (it' not simple matter of copying py file from prior releaseunless you are using an older version of pythonrotor is not real option mostly for historical interest and comparison todaythis module was used as follows it was based on an enigma-style encryption schemewe make new rotor object with key (and optionallya rotor countand call methods to encrypt and decryptimport rotor rotor newrotor('pymailcgi' encrypt('abc '\ an\ \ encrypt('spam ' ' \ \ pylen( decrypt( 'spam (key[,numrotors]may return nonprintable chars result is same len as input notice that the same rotor object can encrypt multiple stringsthat the result may contain nonprintable characters (printed as \ascii escape codes when displayed)and that the result is always the same length as the original string most importanta string encrypted with rotor can be decrypted in different process ( in later cgi scriptif we re-create the rotor objectutility modules
5,846
rotor newrotor('pymailcgi' decrypt(' \ \ py''spam can be decrypted in new process use "\asciiescapes for two chars our secret module by default simply used rotor to encrypt and did no additional encoding of its own it relies on url encoding when the password is embedded in url parameter and on html escaping when the password is embedded in hidden form fields for urlsthe following sorts of calls occurfrom secret import encodedecode encode('abc$#&+' \ \ \ \ \ \ cgi scripts do this import urllib parse urllib parse quote_plus(xy '+% % %cf% % % urlencode does this urllib parse unquote_plus(ya \ \ \ \ \ \ cgi fieldstorage does this decode( 'abc$#&+cgi scripts do this although rotor itself is not widely viable option todaythese same techniques can be used with other encryption schemes manual data encryptionpycrypto variety of encryption tools are available in the third-party public domainincluding the popular python cryptography toolkitalso known as pycrypto this package adds built-in modules for private and public key algorithms such as aesdesideaand rsa encryptionprovides python module for reading and decrypting pgp filesand much more here is an example of using aes encryptionrun after installing pycrypto on my machine with windows self-installerfrom crypto cipher import aes aes block_size mykey 'pymailcgiljust( '-'key must be or bytes mykey 'pymailcgipassword 'already got one length must be multiple of aesobj aes new(mykeyaes mode_ecbcyphertext aesobj encrypt(passwordcyphertext '\xfez\ \xb \ "\xd \xb \xe \ ~ ]aesobj aes new(mykeyaes mode_ecbaesobj decrypt(cyphertext'already got one the pymailcgi server
5,847
algorithms aes is popular private key encryption algorithm it requires fixed length key and data string to have length that is multiple of bytes unfortunatelythis is not part of standard pythonmay be subject to (and other countries'export controls in binary form at this writingand is too large and complex topic for us to address in this text this makes it less than universally applicableat the leastshipping its binary installer with this book' examples package may require legal expertise and since data encryption is core requirement of pymailcgithis seems too strong an external dependency the real showstopper for this book' fourth editionthoughis that pycrypto is xonly system not yet available for python todaythis makes it unusable with the examples in this book stillif you are able to install and learn pycryptothis can be powerful solution for more detailssearch for pycrypto on the web httpssecure http transmissions provided you are using server that supports secure httpyou can simply write html and delegate the encryption to the web server and browser as long as both ends of the transmission support this protocolit is probably the ultimate encrypting solution for web security in factit is used by most -commerce sites on the web today secure http (httpsis designated in urls by using the protocol name rather than it is encrypted with the ssl secure sockets layer https is supported by most web browsers and can be configured in most web serversincluding apache and the webserver py script that we are running locally in this if ssl support is compiled into your pythonpython sockets support it with ssl module socket wrappersand the client-side module urllib request we met in supports https unfortunatelyenabling secure http in web server requires more configuration and background knowledge than we can cover hereand it may require installing tools outside the standard python release if you want to explore this issue furthersearch the web for resources on setting up python-coded https server that supports ssl secure communications as one possible leadsee the third-party crypto package' openssl wrapper support for password encryptionhttps in urlliband morethis could be viable alternative to manual encryptionbut it is not yet available for python at this writing also see the web for more details on https in general it is not impossible that some of the https extensions for python' standard web server classes may make their way into the python standard library in the futurebut they have not in recent yearsperhaps reflecting the classesintended roles--they provide limited functionality for use in locally running servers oriented toward testingnot deployment utility modules
5,848
it' possible to replace the form fields and query parameter pymailcgi currently generates with client-side cookies marked as secure such cookies are automatically encrypted when sent unfortunately againmarking cookie as secure simply means that it can be transmitted only if the communications channel with the host is secure it does not provide any additional encryption because of thisthis option really just begs the questionit still requires an https server the secret py module as you can probably tellweb security is larger topic than we have time to address here because of thatthe secret py module in example - finesses the issueby trying variety of approaches in turnif you are able to fetch and install the third-party pycrypto system described earlierthe module will use that package' aes tools to manually encrypt password data when transmitted together with username if notit will try rotor nextif you're able to find and install the original rotor module in the version of python that you're using and finallyit falls back on very simplistic default character code shuffling obfuscation schemewhich you can replace with one of your own if you install this program on the internet at large see example - for more detailsit uses function definitions nested in if statements to generate the selected encryption scheme' functions at run time example - pp \internet\web\pymailcgi\cgi-bin\secret py ""##############################################################################pymailcgi encodes the pop password whenever it is sent to/from client over the net with usernameas hidden text fields or explicit url paramsuses encode/decode functions in this module to encrypt the pswd--upload your own version of this module to use different encryption mechanism or keypymail doesn' save the password on the serverand doesn' echo pswd as typedbut this isn' safe--this module file itself might be vulnerablehttps may be better and simpler but python web server classes don' support##############################################################################""import systime dayofweek time localtime(time time())[ forcereadablepassword false for custom schemes ##############################################################################string encoding schemes ############################################################################## the pymailcgi server
5,849
##########################################################don' do anything by defaultthe urllib parse quote or cgi escape calls in commonhtml py will escape the password as needed to embed in url or htmlthe cgi module undoes escapes automatically for us##########################################################def stringify(old)return old def unstringify(old)return old else##########################################################convert encoded string to/from string of digit charsto avoid problems with some special/nonprintable charsbut still leave the result semi-readable (but encrypted)some browsers had problems with escaped ampersandsetc ##########################################################separator '-def stringify(old)new 'for char in oldascii str(ord(char)new new separator ascii return new '-ascii-ascii-asciidef unstringify(old)new 'for ascii in old split(separator)[ :]new new chr(int(ascii)return new ##############################################################################encryption schemestry pycryptothen rotorthen simple/custom scheme ##############################################################################usecrypto userotor true tryimport crypto exceptusecrypto false tryimport rotor exceptuserotor false if usecrypto######################################################use third-party pycrypto package' aes algorithm assumes pswd has no '\ on the rightused to pad change the private key here if you install this ######################################################utility modules
5,850
from crypto cipher import aes mykey 'pymailcgi ljust( '-'key must be or bytes def do_encode(pswd)over len(pswd if overpswd +'\ ( -overpadlen must be multiple of aesobj aes new(mykeyaes mode_ecbreturn aesobj encrypt(pswddef do_decode(pswd)aesobj aes new(mykeyaes mode_ecbpswd aesobj decrypt(pswdreturn pswd rstrip('\ 'elif userotor######################################################use the standard lib' rotor module to encode pswd this does better job of encryption than code above unfortunatelyit is no longer available in py ######################################################sys stderr write('using rotor\ 'import rotor mykey 'pymailcgi def do_encode(pswd)robj rotor newrotor(mykeyreturn robj encrypt(pswduse enigma encryption def do_decode(pswd)robj rotor newrotor(mykeyreturn robj decrypt(pswdelse######################################################use our own custom scheme as last resort shuffle characters in some reversible fashion caveatvery simple -replace with one of your own ######################################################sys stderr write('using simple\ 'adder def do_encode(pswd)pswd 'vspswd ' res 'for char in pswdres +chr(ord(charadderreturn str(resdef do_decode(pswd)pswd pswd[ :- res 'for char in pswd the pymailcgi server inc each ascii code
5,851
return res ##############################################################################top-level entry points ##############################################################################def encode(pswd)return stringify(do_encode(pswd)encrypt plus string encode def decode(pswd)return do_decode(unstringify(pswd)in addition to encryptionthis module also implements an encoding method for already encrypted stringswhich transforms them to and from printable characters by defaultthe encoding functions do nothingand the system relies on straight url or html encoding of the encrypted string an optional encoding scheme translates the encrypted string to string of ascii code digits separated by dashes either encoding method makes nonprintable characters in the encrypted string printable to illustratelet' test this module' tools interactively for this testwe set forcereadablepassword to true the top-level entry points encode and decode into printable characters (for illustration purposesthis test reflects python installation where pycrypto is installed)from secret import using pycrypto data encode('spam@ +'data '------ decode(data'spam@ +but there are actually two steps to this--encryption and printable encodingraw do_encode('spam@ +'raw '/\xf \ \xaak\xf \xaf\ \xe \xf \ \ \ \xa ktext stringify(rawtext '------ len(raw)len(text( here' what the encoding looks like without the extra printable encodingraw do_encode('spam@ +'raw '/\xf \ \xaak\xf \xaf\ \xe \xf \ \ \ \xa kdo_decode(raw'spam@ +utility modules
5,852
as ispymailcgi avoids ever passing the pop account username and password across the net together in single transactionunless the password is encrypted or obfuscated according to the module secret py on the server this module can be different everywhere pymailcgi is installedand it can be uploaded anew in the future--encrypted passwords aren' persistent and live only for the duration of one mail-processing interaction session provided you don' publish your encryption code or its private keysyour data will be as secure as the custom encryption module you provide on your own server if you wish to use this system on the general internetyou'll want to tailor this code ideallyyou'll install pycrypto and change the private key string barring thatreplace example - with custom encryption coding scheme of your own or deploy one of the general techniques mentioned earliersuch as an https-capable web server in any eventthis software makes no guaranteesthe security of your password is ultimately up to you to ensure for additional information on security tools and techniquessearch the web and consult books geared exclusively toward web programming techniques as this system is prototype at largesecurity is just one of handful of limitations which would have to be more fully addressed in robust production-grade version because the encryption schemes used by pymailcgi are reversibleit is possible to reconstruct my email account' password if you happen to see its encrypted form in screenshotunless the private key listed in secret py was different when the tests shown were run to sidestep this issuethe email account used in all of this book' examples is temporary and will be deleted by the time you read these words please use an email account of your own to test-drive the system common utilities module finallythe file commonhtml py in example - is the grand central station of this application--its code is used and reused by just about every other file in the system most of it is self-explanatoryand we've already met most of its core idea earlierin conjunction with the cgi scripts that use it haven' talked about its debugging supportthough notice that this module assigns sys stderr to sys stdoutin an attempt to force the text of python error messages to show up in the client' browser (rememberuncaught exceptions print details to sys stderrthat works sometimes in pymailcgibut not always--the error text shows up in web page only if page_header call has already printed response preamble if you want to see all error messagesmake sure you call page_header (or print content-typelines manuallybefore any other processing the pymailcgi server
5,853
the browser (dumpstatepage)and that wrap calls to functions that print status messages so that their output isn' added to the html stream (runsilenta version addition also attempts to work around the fact that built-in print calls can fail in python for some types of unicode text ( non-ascii character sets in internationalized headers)by forcing binary mode and bytes for the output stream (printi'll leave the discovery of any remaining magic in the code in example - up to youthe reader you are hereby admonished to go forth and readreferand reuse example - pp \internet\web\pymailcgi\cgi-bin\commonhtml py #!/usr/bin/python ""#################################################################################generate standard page headerlistand footer htmlisolates html generation related details in this filetext printed here goes over socket to the clientto create parts of new web page in the web browseruses one print per lineinstead of string blocksuses urllib to escape params in url links auto from dictbut cgi escape to put them in html hidden fieldssome tools here may be useful outside pymailcgicould also return the html generated here instead of printing itso it could be included in other pagescould also structure as single cgi script that gets and tests next action name as hidden form fieldcaveatthis system worksbut was largely written during two-hour layover at the chicago 'hare airportthere is much room for improvement and optimization#################################################################################""import cgiurllib parsesysos python has issues printing some decoded str as text to stdout import builtins bstdout open(sys stdout fileno()'wb'def print(*argsend='\ ')trybuiltins print(*argsend=endsys stdout flush(exceptfor arg in argsbstdout write(str(argencode('utf- ')if endbstdout write(end encode('utf- ')bstdout flush(sys stderr sys stdout from externs import mailconfig from externs import mailtools parser mailtools mailparser(show error messages in browser from package somewhere on server need parser for header decoding one per process in this module my cgi address root #urlroot '#urlroot 'urlroot 'use minimalrelative paths utility modules
5,854
print('content-typetext/html\ 'print('% % page (pp )(appkind)print('% % (colorapp(info or kind))def pagefooter(root='pymailcgi html')print('< href="print('<img src=/pythonpoweredsmall gif'print('align=left alt="[python logo]border= hspace= >'print('back to root pagerootprint(''def formatlink(cgiurlparmdict)""make "%url?key=val&key=valquery link from dictionaryescapes str(of all key and val with %xxchanges to note that url escapes are different from html (cgi escape""parmtext urllib parse urlencode(parmdictcalls parse quote_plus return '% ?% (cgiurlparmtexturllib does all the work def pagelistsimple(linklist)show simple ordered list print(''for (textcgiurlparmdictin linklistlink formatlink(cgiurlparmdicttext cgi escape(textprint('\ % (linktext)print(''def pagelisttable(linklist)show list in table print(''escape text to be safe for (textcgiurlparmdictin linklistlink formatlink(cgiurlparmdicttext cgi escape(textprint('view\ % (linktext)print(''def listpage(linkslistkind='selection list')pageheader(kind=kindpagelisttable(linkslist[('text''cgiurl'{'parm':'value'})pagefooter(def messagearea(headerstextextra='')extra for readonly addrhdrs ('from''to''cc''bcc'decode names only print(''for hdr in ('from''to''cc''subject')rawhdr headers get(hdr'?'if hdr not in addrhdrsdechdr parser decodeheader(rawhdr decode for display elseencoded on sends dechdr parser decodeaddrheader(rawhdremail names only val cgi escape(dechdrquote= print('% :hdrprint(<input type=text 'print(name=% value="% % size= >(hdrvalextra) the pymailcgi server
5,855
print('extraprint('% \ (cgi escape(textor '?')if has def viewattachmentlinks(partnames)""create hyperlinks to locally saved part/attachment files when clickeduser' web browser will handle opening assumes just one useronly valid while viewing msg ""print('parts:'for filename in partnamesbasename os path basename(filenamefilename filename replace('\\''/'windows hack print('% (filenamebasename)print(''def viewpage(msgnumheaderstextformparts=[])""on view select (generated link clickvery subtle thingat this pointpswd was url encoded in the linkand then unencoded by cgi input parserit' being embedded in html hereso we use cgi escapethis usually sends nonprintable chars in the hidden field' htmlbut works on ie and ns anyhowin url?user=lutz&mnum= &pswd=% cg% % % % % % % in htmlcould urllib parse quote html field here toobut must urllib parse unquote in next script (which precludes passing the inputs in url instead of the form)can also fall back on numeric string fmt in secret py ""pageheader(kind='view'userpswdsite list(map(cgi escapegetstandardpopfields(form))print('urlrootprint('msgnumprint('userfrom page|url print('sitefor deletes print('pswdpswd encoded messagearea(headerstext'readonly'if partsviewattachmentlinks(partsonviewpageaction quotetext needs date passed in page print('headers get('date','?')print('action:'print(''print(replyforwarddelete'print(''print(''no 'resetneeded here pagefooter(def sendattachmentwidgets(maxattach= )print('attach:'for in range( maxattach+ )print('iprint(''utility modules
5,856
on sendview+select+replyview+select+fwd pageheader(kind=kindprint('<form enctype="multipart/form-datamethod=post'end='print('action="%soneditpagesend py">urlrootif mailconfig mysignaturetext '\ % \ % (mailconfig mysignaturetextmessagearea(headerstextsendattachmentwidgets(print(''print(''print(''pagefooter(def errorpage(messagestacktrace=true)pageheader(kind='error'was sys exc_type/exc_value exc_typeexc_valueexc_tb sys exc_info(print('error description'messageprint('python exception'cgi escape(str(exc_type))print('exception details'cgi escape(str(exc_value))if stacktraceprint('exception traceback'import traceback traceback print_tb(exc_tbnonesys stdoutprint(''pagefooter(def confirmationpage(kind)pageheader(kind='confirmation'print('% operation was successfulkindprint('press the link below to return to the main page 'pagefooter(def getfield(formfielddefault='')emulate dictionary get method return (field in form and form[fieldvalueor default def getstandardpopfields(form)""fields can arrive missing or 'or with real value hardcoded in urldefault to mailconfig settings ""return (getfield(form'user'mailconfig popusername)getfield(form'pswd''?')getfield(form'site'mailconfig popservername)def getstandardsmtpfields(form)return getfield(form'site'mailconfig smtpservernamedef runsilent(funcargs)""run function without writing stdout exsuppress print' in imported tools else they go to the client/browser "" the pymailcgi server
5,857
def write(selfline)pass save_stdout sys stdout sys stdout silent(tryresult func(*argsfinallysys stdout save_stdout return result send print to dummy object which has write method try to return func result but always restore stdout def dumpstatepage(exhaustive= )""for debuggingcall me at top of cgi to generate new page with cgi state details ""if exhaustivecgi test(show page with formenvironetc elsepageheader(kind='state dump'form cgi fieldstorage(show just form fields names/values cgi print_form(formpagefooter(sys exit(def selftest(showastable=false)make phony web page links [(texturl{parms})('text 'urlroot 'page cgi'{' ': })('text 'urlroot 'page cgi'{' ': ' ':' '})('text 'urlroot 'page cgi'{' ':' '' ':' < & '' ':'?'})('te 'urlroot 'page cgi'{'':''' ':''' ':none})pageheader(kind='view'if showastablepagelisttable(linkselsepagelistsimple(linkspagefooter(if __name__ ='__main__'selftest(len(sys argv when runnot imported html goes to stdout web scripting trade-offs as shown in this pymailcgi is still something of system in the makingbut it does work as advertisedwhen it is installed on remote server machineby pointing browser at the main page' urli can check and send email from anywhere happen to beas long as can find machine with web browser (and can live with the limitations of prototypein factany machine and browser will dopython doesn' have to be installed anewand don' need pop or smtp access on the client machine itself that' not the case with the pymailgui client-side program we wrote in this property is especially useful at sites that allow web access but restrict more direct protocols such as pop email web scripting trade-offs
5,858
conclusion pymailcgi versus pymailgui besides illustrating larger cgi applications in generalthe pymailgui and pymailcgi examples were chosen for this book on purpose to underscore some of the trade-offs you run into when building applications to run on the web pymailgui and pymailcgi do roughly the same things but are radically different in implementationpymailgui this is traditional "desktopuser-interface programit runs entirely on the local machinecalls out to an in-process gui api library to implement interfacesand talks to the internet through sockets only when it has to ( to load or send email on demanduser requests are routed immediately to callback handler method functions running locally and in-processwith shared variables and memory that automatically retain state between requests as mentionedbecause its memory is retained between eventspymailgui can cache messages in memory--it loads email headers and selected mails only oncefetches only newly arrived message headers on future loadsand has enough information to perform general inbox synchronization checks on deletionspymailgui can simply refresh its memory cache of loaded headers without having to reload from the server moreoverbecause pymailgui runs as single process on the local machineit can leverage tools such as multithreading to allow mail transfers to overlap in time (you can send while load is in progress)and it can more easily support extra functionality such as local mail file saves and opens pymailcgi like all cgi systemspymailcgi consists of scripts that reside and run on server machine and generate html to interact with user' web browser on the client machine it runs only in the context of web browser or other html-aware clientand it handles user requests by running cgi scripts on the web server without manually managed state retention techniques such as server-side database systemthere is no equivalent to the persistent memory of pymailgui--each request handler runs autonomouslywith no memory except that which is explicitly passed along by prior states as hidden form fieldsurl query parametersand so on because of thatpymailcgi currently must reload all email headers whenever it needs to display the selection listnaively reloads messages already fetched earlier in the sessionand cannot perform general inbox synchronization tests this can be improved by more advanced state-retention schemes such as cookies and serverside databasesbut none is as straightforward as the persistent in-process memory of pymailgui the pymailcgi server
5,859
of coursethese systemsspecific functionality isn' exactly the same--pymailcgi is roughly functional subset of pymailgui--but they are close enough to capture common trade-offs on basic levelboth of these systems use the python pop and smtp modules to fetch and send email through sockets the implementation alternatives they representthoughhave some critical ramifications that you should consider when evaluating the prospect of delivering systems on the webperformance costs networks are slower than cpus as implementedpymailcgi isn' nearly as fast or as complete as pymailgui in pymailcgievery time the user clicks submit buttonthe request goes across the network (it' routed to another program on the same machine for "localhost,but this setup is for testingnot deploymentmore specificallyevery user request incurs network transfer overheadevery callback handler may take the form of newly spawned process or thread on most serversparameters come in as text strings that must be parsed outand the lack of state information on the server between pages means that either mail needs to be reloaded often or state retention options must be employed which are slower and more complex than shared process memory in contrastuser clicks in pymailgui trigger in-process function calls rather than network traffic and program executionsand state is easily saved as python inprocess variables even with an ultra-fast internet connectiona server-side cgi system is slower than client-side program to be fairsome tkinter operations are sent to the underlying tcl library as stringstoowhich must be parsed this may change in timebut the contrast here is with cgi scripts versus gui libraries in general function calls will probably always beat network transfers some of these bottlenecks may be designed away at the cost of extra program complexity for instancesome web servers use threads and process pools to minimize process creation for cgi scripts moreoveras we've seensome state information can be manually passed along from page to page in hidden form fieldsgenerated url parametersand client-side cookiesand state can be saved between pages in concurrently accessible database to minimize mail reloads but there' no getting past the fact that routing events and data over network to scripts is slower than calling python function directly not every application must carebut some do complexity costs html isn' pretty because pymailcgi must generate html to interact with the user in web browserit is also more complex (or at leastless readablethan pymailgui in some sensecgi scripts embed html code in pythontemplating systems such as psp often take the opposite approach either waybecause the end result of this is mixture of two very different languagescreating an interface with web scripting trade-offs
5,860
gui api such as tkinter witnessfor exampleall the care we've taken to escape html and urls in this examplessuch constraints are grounded in the nature of html furthermorechanging the system to retain loaded-mail list state in database between pages would introduce further complexities to the cgi-based solution (andmost likelyyet another language such as sqleven if it only appears near the bottom of the software stackand secure http would eliminate the manual encryption complexity but would introduce new server configuration complexity functionality limitations html can say only so much html is portable way to specify simple pages and formsbut it is poor to useless when it comes to describing more complex user interfaces because cgi scripts create user interfaces by writing html back to browserthey are highly limited in terms of user-interface constructs for exampleconsider implementing an image-processing and animation program as cgi scriptshtml doesn' easily apply once we leave the domain of fill-out forms and simple interactions it is possible to generate graphics in cgi scripts they may be created and stored in temporary files on the serverwith per-session filenames referenced in image tags in the generated html reply for browsers that support the notiongraphic images may also be in-lined in html image tagsencoded in base format or similar either technique is substantially more complex than using an image in the tkinter gui librarythough moreoverresponsive animation and drawing applications are beyond the scope of protocol such as cgiwhich requires network transaction per interaction the interactive drawing and animation scripts we wrote at the end of for examplecould not be implemented as normal serverside scripts this is precisely the limitation that java applets were designed to address-programs that are stored on server but are pulled down to run on client on demand and are given access to full-featured gui api for creating richer user interfaces neverthelessstrictly server-side programs are inherently limited by the constraints of html beyond html' limitationsclient-side programs such as pymailgui also have access to tools such as multithreading which are difficult to emulate in cgi-based application (threads spawned by cgi script cannot outlive the cgi script itselfor augment its reply once sentpersistent process models for web applications such as fastcgi may provide options herebut the picture is not as clear-cut as on the client although web developers make noble efforts at emulating client-side capabilities-see the discussion of rias and html ahead--such efforts add additional complexitycan stretch the server-side programming model nearly to its breaking pointand account for much of the plethora of divergent web techniques the pymailcgi server
5,861
all you need is browser on clients on the upsidebecause pymailcgi runs over the webit can be run on any machine with web browserwhether that machine has python and tkinter installed or not that ispython needs to be installed on only one computer--the web server machine where the scripts actually live and run in factthis is probably the most compelling benefit to the web application model as long as you know that the users of your system have an internet browserinstallation is simple you still need python on the serverbut that' easier to guarantee python and tkinteryou will recallare very portabletoo--they run on all major window systems ( windowsmac)--but to run client-side python/tkinter program such as pymailguiyou need python and tkinter on the client machine itself not so with an application built as cgi scriptsit will work on macintoshlinuxwindowsand any other machine that can somehow render html web pages in this sensehtml becomes sort of portable gui api language in web scriptsinterpreted by your web browserwhich is itself kind of generalized gui for rendering guis you don' even need the source code or bytecode for the cgi scripts themselves--they run on remote server that exists somewhere else on the netnot on the machine running the browser execution requirements but you do need browser that isthe very nature of web-enabled systems can render them useless in some environments despite the pervasiveness of the internetmany applications still run in settings that don' have web browsers or internet access considerfor instanceembedded systemsreal-time systemsand secure government applications while an intranet ( local network without external connectionscan sometimes make web applications feasible in some such environmentsi have worked at more than one company whose client sites had no web browsers to speak of on the other handsuch clients may be more open to installing systems like python on local machinesas opposed to supporting an internal or external network administration requirements you really need servertoo you can' write cgi-based systems at all without access to web server furtherkeeping programs on centralized server creates some fairly critical administrative overheads simply putin pure client/server architectureclients are simplerbut the server becomes critical path resource and potential performance bottleneck if the centralized server goes downyouyour employeesand your customers may be knocked out of commission moreoverif enough clients use shared server at the same timethe speed costs of webbased systems become even more pronounced in production systemsadvanced techniques such as load balancing and fail-over servers helpbut they add new requirements web scripting trade-offs
5,862
is akin to stepping backward in time--to the time of centralized mainframes and dumb terminals some would include the emerging cloud computing model in this analysisarguably in part throwback to older computing models whichever way we stepoffloading and distributing processing to client machines at least partially avoids this processing bottleneck other approaches so what' the best way to build applications for the internet--as client-side programs that talk to the net or as server-side programs that live and breathe on the netnaturallythere is no one answer to that questionsince it depends upon each application' unique constraints moreoverthere are more possible answers to it than have been disclosed so far although the client and server programming models do imply tradeoffsmany of the common web and cgi drawbacks already have common proposed solutions for exampleclient-side solutions clientand server-side programs can be mixed in many ways for instanceapplet programs live on server but are downloaded to and run as client-side programs with access to rich gui libraries other technologiessuch as embedding javascript or python directly in html codealso support client-side execution and richer gui possibilities such scripts live in html on the server but run on the client when downloaded and access browser components through an exposed object model to customize pages the dynamic html (dhtmlextensions provide yet another client-side scripting option for changing web pages after they have been constructed and the newly emerging ajax model offers additional ways to add interactivity and responsiveness to web pagesand is at the heart of the ria model noted ahead all of these client-side technologies add extra complexities all their ownbut they ease some of the limitations imposed by straight html state retention solutions we discussed general state retention options in detail in the prior and we will study full-scale database systems for python in some web application servers ( zopenaturally support state retention between pages by providing concurrently accessible object databases some of these systems have an explicit underlying database component ( oracle and mysql)others may use flat files or python persistent shelves with appropriate locking in additionobject relational mappers (ormssuch as sqlobject allow relational databases to be processed as python classes scripts can also pass state information around in hidden form fields and generated url parametersas done in pymailcgior they can store it on the client machine itself using the standard cookie protocol as we learned in cookies are the pymailcgi server
5,863
and that are transferred back to the server when page is revisited (data is sent back and forth in http header linescookies are more complex than program variables and are somewhat controversial and optionalbut they can offload some simple state retention tasks alternative models such as fastcgi and mod_python offer additional persistence options--where supportedfastcgi applications may retain context in long-lived processesand mod_python provides session data within apache html generation solutions third-party extensions can also take some of the complexity out of embedding html in python cgi scriptsalbeit at some cost to execution speed for instancethe htmlgen system and its relatives let programs build pages as trees of python objects that "knowhow to produce html other frameworks prove an objectbased interface to reply-stream generation ( reply object with methodswhen system like this is employedpython scripts deal only with objectsnot with the syntax of html itself for instancesystems such as phppython server pages (psp)zope' dtml and zptand active server pages provide server-side templating languageswhich allow scripting language code to be embedded in html and executed on the serverto dynamically generate or determine part of the html that is sent back to client in response to requests the net result can cleanly insulate python code from the complexity of html code and promote the separation of display format and business logicbut may add complexities of its own due to the mixture of different languages generalized user interface development to cover both basessome systems attempt to separate logic from display so much as to make the choice almost irrelevant--by completely encapsulating display detailsa single program canin principlerender its user interface as either traditional gui or an html-based web page due to the vastly different architecturesthoughthis ideal is difficult to achieve well and does not address larger disparities between the client and server platforms issues such as state retention and network interfaces are much more significant than generation of windows and controlsand may impact code more other systems may try to achieve similar goals by abstracting the display representation-- common xml representationfor instancemight lend itself to both gui and an html rendering againthoughthis addresses only the rendering of the displaynot the fundamental architectural differences of clientand serverside approaches emerging technologiesrias and html finallyhigher-level approaches such as the ria (rich internet applicationtoolkits introduced in and can offer additional functionality that html lacks and can approach the utility on gui toolkits on the other handthey can web scripting trade-offs
5,864
languages to the mix though this can varythe net result is often something of web-hosted tower of babelwhose development might require simultaneously programming in pythonhtmlsqljavascripta server-side templating languagean object-relational mapping apiand moreand even nested and embedded combinations of these the resulting software stack can be more complex than python and gui toolkit moreoverrias today inherit the inherent speed degradation of network-based systems in generalalthough ajax can add interactivity to web pagesit still implies network access instead of in-process function calls ironicallymuch like desktop applicationsrias may also still require installation of browser plug-in on the client to be used at all the emerging html standard may address the plug-in constraint and ease the complexity somewhatbut it brings along with it grab bag of new complexities all its own which we won' describe here clearlyinternet technology does come with some compromisesand it is still evolving rapidly it is nevertheless an appropriate delivery context for manythough not allapplications as with every design choiceyou must be the judge while delivering systems on the web may have some costs in terms of performancefunctionalityand complexityit is likely that the significance of those overheads will continue to diminish with time see the start of for more on some systems that promise such changeand watch the web for the ever-changing internet story to unfold suggested readingthe pyerrata system now that 've told you all the reasons you might not want to design systems for the webi' going to completely contradict myself and refer you to system that almost requires web-based implementation the second edition of this book included that presented the pyerrata website-- python program that lets arbitrary people on arbitrary machines submit book comments and bug reports (usually called errataover the webusing just web browser such system must store information on serverso it can be read by arbitrary clients because of space concernsthat was cut in this book' third edition howeverwe're making its original content available as optionalsupplemental reading you can find this example' codeas well as the original file in the directory pp \internet\web\pyerrata of the book examples distribution tree (see the preface for more on the examples distributionpyerrata is in some ways simpler than the pymailcgi case study presented in this from user' perspectivepyerrata is more hierarchical than linearuser interactions are shorter and spawn fewer pages there is also little state retention in the web pages themselves in pyerrata--url parameters pass state in only one isolated caseand no hidden form fields are generated on the other handpyerrata introduces an entirely new dimensionpersistent data storage state (error and comment reportsis stored permanently by this system on the the pymailcgi server
5,865
concurrent updatessince any number of users out in cyberspace may be accessing the site at the same timeso pyerrata also introduces file-locking techniques along the way no longer maintain the website described by this extra and the material itself is slightly out of date in some ways for instancethe os open call is preferred for file locking nowi would probably use different data storage system todaysuch as zodbthe code and its may still be in python form in the examples packageand this site might be better implemented as blog or wikiconcepts and labels that arose after the site was developed stillpyerrata provides an additional python website case studyand it more closely reflects websites that must store information on the server web scripting trade-offs
5,866
tools and techniques this part of the book presents collection of additional python application topics most of the tools presented along the way can be used in wide variety of application domains you'll find the following here this covers commonly used and advanced python techniques for storing information between program executions--dbm filesobject picklingobject shelvesand python' sql database api--and briefly introduces full-blown oodbs such as zodbas well as orms such as sqlobject and sqlalchemy the python standard library' sqlite support is used for the sql examplesbut the api is portable to enterprise-level systems such as mysql this explores techniques for implementing more advanced data structures in python--stackssetsbinary search treesgraphsand the like in pythonthese take the form of object implementations this addresses python tools and techniques for parsing text-based information--string splits and joinsregular expression matchingxml parsingrecursive descent parsingand more advanced language-based topics this introduces integration techniques--both extending python with compiled libraries and embedding python code in other applications while the main focus here is on linking python with compiled codewe'll also investigate integration with javanetand more this assumes that you know how to read programsand it is intended mostly for developers responsible for implementing application integration layers this is the last technical part of the bookand it makes heavy use of tools presented earlier in the text to help underscore the notion of code reuse for instancea calculator gui (pycalcserves to demonstrate language processing and code reuse concepts
5,867
databases and persistence "give me an order of persistencebut hold the picklesso far in this bookwe've used python in the system programminggui developmentand internet scripting domains--three of python' most common applicationsand representative of its use as an application programming language at large in the next four we're going to take quick look at other major python programming topicspersistent datadata structure techniquestext and language processingand python/ integration these four topics are not really application areas themselvesbut they are techniques that span domains the database topics in this for instancecan be applied on the webin desktop gui applicationsand so on text processing is similarly general tool moreovernone of these final four topics is covered exhaustively (each could easily fill book alone)but we'll sample python in action in these domains and highlight their core concepts and tools if any of these spark your interestadditional resources are readily available in the python world persistence options in python in this our focus is on persistent data--the kind that outlives program that creates it that' not true by default for objects script constructsof coursethings like listsdictionariesand even class instance objects live in your computer' memory and are lost as soon as the script ends to make data live longerwe need to do something special in python programmingthere are today at least six traditional ways to save information in between program executionsflat files text and bytes stored directly on your computer dbm keyed files keyed access to strings stored in dictionary-like files
5,868
serialized python objects saved to files and streams shelve files pickled python objects saved in dbm keyed files object-oriented databases (oodbspersistent python objects stored in persistent dictionaries (zodbdurussql relational databases (rdbmsstable-based storage that supports sql queries (sqlitemysqlpostgresqletc object relational mappers (ormsmediators that map python classes to relational tables (sqlobjectsqlalchemyin some sensepython' interfaces to network-based object transmission protocols such as soapxml-rpcand corba also offer persistence optionsbut they are beyond the scope of this hereour interest is in techniques that allow program to store its data directly andusuallyon the local machine although some database servers may operate on physically remote machine on networkthis is largely transparent to most of the techniques we'll study here we studied python' simple (or "flat"file interfaces in earnest in and we have been using them ever since python provides standard access to both the stdio filesystem (through the built-in open function)as well as lower-level descriptor-based files (with the built-in os modulefor simple data storage tasksthese are all that many scripts need to save for use in future program runsimply write data out to newly opened file on your computer in text or binary modeand read it back from that file later as we've seenfor more advanced taskspython also supports other file-like interfaces such as pipesfifosand sockets since we've already explored flat filesi won' say more about them here the rest of this introduces the remaining topics on the preceding list at the endwe'll also meet gui program for browsing the contents of things such as shelves and dbm files before thatthoughwe need to learn what manner of beast these are fourth edition coverage notethe prior edition of this book used the mysql-python interface to the mysql relational database systemas well as the zodb object database system as update this in june neither of these is yet available for python xthe version of python used in this edition because of thatmost zodb information has been trimmedand the sql database examples here were changed to use the sqlite in-process database system that ships with python as part of its standard library the prior edition' zodb and mysql examples and overviews are still available in the examples packageas described later because python' sql database api is portablethoughthe sqlite code here should work largely unchanged on most other systems databases and persistence
5,869
flat files are handy for simple persistence tasksbut they are generally geared toward sequential processing mode although it is possible to jump around to arbitrary locations with seek callsflat files don' provide much structure to data beyond the notion of bytes and text lines dbm filesa standard tool in the python library for database managementimprove on that by providing key-based access to stored text strings they implement randomaccesssingle-key view on stored data for instanceinformation related to objects can be stored in dbm file using unique key per object and later can be fetched back directly with the same key dbm files are implemented by variety of underlying modules (including one coded in python)but if you have pythonyou have dbm using dbm files although dbm filesystems have to do bit of work to map chunks of stored data to keys for fast retrieval (technicallythey generally use technique called hashing to store data in files)your scripts don' need to care about the action going on behind the scenes in factdbm is one of the easiest ways to save information in python--dbm files behave so much like in-memory dictionaries that you may forget you're actually dealing with file at all for instancegiven dbm file objectindexing by key fetches data from the file assigning to an index stores data in the file dbm file objects also support common dictionary methods such as keys-list fetches and tests and key deletions the dbm library itself is hidden behind this simple model since it is so simplelet' jump right into an interactive example that creates dbm file and shows how the interface worksc:\pp \dbasepython import dbm file dbm open('movie'' 'file['batman''pow!file keys([ 'batman'file['batman' 'pow!get interfacebsddbgnundbmdumb make dbm file called 'moviestore string under key 'batmanget the file' key directory fetch value for key 'batmanwho ['robin''cat-woman''joker'what ['bang!''splat!''wham!'for in range(len(who))file[who[ ]what[iadd more "recordsfile keys([ 'cat-woman' 'batman' 'joker' 'robin'len(file)'robinin filefile['joker'dbm files
5,870
file close(close sometimes required internallyimporting the dbm standard library module automatically loads whatever dbm interface is available in your python interpreter (attempting alternatives in fixed order)and opening the new dbm file creates one or more external files with names that start with the string 'movie(more on the details in momentbut after the import and opena dbm file is virtually indistinguishable from dictionary in effectthe object called file here can be thought of as dictionary mapped to an external file called moviethe only obvious differences are that keys must be strings (not arbitrary immutables)and we need to remember to open to access and close after changes unlike normal dictionariesthoughthe contents of file are retained between python program runs if we come back later and restart pythonour dictionary is still available againdbm files are like dictionaries that must be openedc:\pp \dbasepython import dbm file dbm open('movie'' 'file['batman' 'pow!open existing dbm file file keys(keys gives an index list [ 'cat-woman' 'batman' 'joker' 'robin'for key in file keys()print(keyfile[key] 'cat-womanb'splat! 'batmanb'pow! 'jokerb'wham! 'robinb'bang!notice how dbm files return real list for the keys callnot shown heretheir values method instead returns an iterable view like dictionaries furtherdbm files always store both keys and values as bytes objectsinterpretation as arbitrary types of unicode text is left to the client application we can use either bytes or str strings in our code when accessing or storing keys and values--using bytes allows your keys and values to retain arbitrary unicode encodingsbut str objects in our code will be encoded to bytes internally using the utf- unicode encoding by python' dbm implementation stillwe can always decode to unicode str strings to display in more friendly fashion if desiredand dbm files have keys iterator just like dictionaries moreoverassigning and deleting keys updates the dbm fileand we should close after making changes (this ensure that changes are flushed to disk)for key in fileprint(key decode()file[keydecode()cat-woman splatbatman powjoker wham databases and persistence
5,871
file['batman''ka-boom!del file['robin'file close(change batman slot delete the robin entry close it after changes apart from having to import the interface and open and close the dbm filepython programs don' have to know anything about dbm itself dbm modules achieve this integration by overloading the indexing operations and routing them to more primitive library tools but you' never know that from looking at this python code--dbm files look like normal python dictionariesstored on external files changes made to them are retained indefinitelyc:\pp \dbasepython import dbm open dbm file again file dbm open('movie'' 'for key in fileprint(key decode()file[keydecode()cat-woman splatbatman ka-boomjoker whamas you can seethis is about as simple as it can be table - lists the most commonly used dbm file operations once such file is openedit is processed just as though it were an in-memory python dictionary items are fetched by indexing the file object by key and are stored by assigning to key table - dbm file operations python code action description import dbm import get dbm implementation file=dbm open('filename'' 'open create or open an existing dbm file for / file['key''valuestore create or change the entry for key value file['key'fetch load the value for the entry key count len(filesize return the number of entries stored index file keys(index fetch the stored keys list (not viewfound 'keyin file query see if there' an entry for key del file['key'delete remove the entry for key for key in fileiterate iterate over stored keys file close(close manual closenot always needed dbm files
5,872
despite the dictionary-like interfacedbm files really do map to one or more external files for instancethe underlying default dbm interface used by python on windows writes two files--movie dir and movie dat--when dbm file called movie is madeand saves movie bak on later opens if your python has access to different underlying keyed-file interfacedifferent external files might show up on your computer technicallythe module dbm is really an interface to whatever dbm-like filesystem you have available in your pythonwhen opening an already existing dbm filedbm tries to determine the system that created it with the dbm whichdb function instead this determination is based upon the content of the database itself when creating new filedbm today tries set of keyed-file interface modules in fixed order according to its documentationit attempts to import the interfaces dbm bsddbm gnudbm ndbmor dbm dumband uses the first that succeeds pythons without any of these automatically fall back on an all-python and always-present implementation called dbm dumbwhich is not really "dumb,or coursebut may not be as fast or robust as other options future pythons are free to change this selection orderand may even add additional alternatives to it you normally don' need to care about any of thisthoughunless you delete any of the files your dbm createsor transfer them between machines with different configurations--if you need to care about the portability of your dbm files (and as we'll see laterby proxythat of your shelve files)you should configure machines such that all have the same dbm interface installed or rely upon the dumb fallback for examplethe berkeley db package ( bsddbused by dbm bsd is widely available and portable note that dbm files may or may not need to be explicitly closedper the last entry in table - some dbm files don' require close callbut some depend on it to flush changes out to disk on such systemsyour file may be corrupted if you omit the close call unfortunatelythe default dbm in some older windows pythonsdbhash ( bsddb)is one of the dbm systems that requires close call to avoid data loss as rule of thumbalways close your dbm files explicitly after making changes and before your program exits to avoid potential problemsit' essential "commitoperation for these files this rule extends by proxy to shelvesa topic we'll meet later in this databases and persistence
5,873
when calling dbm opento force python to create the file if it does not yet exist and to simply open it for reads and writes otherwise this used to be the default behavior but is no longer you do not need the 'cargument when opening shelves discussed ahead--they still use an "open or create'cmode by default if passed no open mode argument other open mode strings can be passed to dbmincluding to always create the fileand for read-only of an existing file--the new default see the python library manual for more details in additionpython stores both key and value strings as bytes instead of str as we've seen (which turns out to be convenient for pickled data in shelvesdiscussed aheadand no longer ships with bsddb as standard component--it' available independently on the web as third-party extensionbut in its absence python falls back on its own dbm file implementation since the underlying dbm implementation rules are prone to change with timeyou should always consult python' library manuals as well as the dbm module' standard library source code for more information pickled objects probably the biggest limitation of dbm keyed files is in what they can storedata stored under key must be simple string if you want to store python objects in dbm fileyou can sometimes manually convert them to and from strings on writes and reads ( with str and eval calls)but this takes you only so far for arbitrarily complex python objects such as class instances and nested data structuresyou need something more class instance objectsfor examplecannot usually be later re-created from their standard string representations moreovercustom to-string conversions and fromstring parsers are error prone and not general the python pickle modulea standard part of the python systemprovides the conversion step needed it' sort of super general data formatting and de-formatting tool--pickle converts nearly arbitrary python in-memory objects to and from single linear string formatsuitable for storing in flat filesshipping across network sockets between trusted sourcesand so on this conversion from object to string is often called serialization--arbitrary data structures in memory are mapped to serial string form the string representation used for objects is also sometimes referred to as byte streamdue to its linear format it retains all the content and references structure of the original in-memory object when the object is later re-created from its byte stringit will be new in-memory object identical in structure and value to the originalthough located at different memory address the net effect is that the re-created object is effectively copy of the originalin pythonspeakthe two will be =but not is since the recreation typically happens in an entirely pickled objects
5,874
generally precludes using pickled objects directly as cross-process shared statepickling works on almost any python datatype--numberslistsdictionariesclass instancesnested structuresand more--and so is general way to store data because pickles contain native python objectsthere is almost no database api to be foundthe objects stored with pickling are processed with normal python syntax when they are later retrieved using object pickling pickling may sound complicated the first time you encounter itbut the good news is that python hides all the complexity of object-to-string conversion in factthe pickle module ' interfaces are incredibly simple to use for exampleto pickle an object into serialized stringwe can either make pickler and call its methods or use convenience functions in the module to achieve the same effectp pickle pickler(filemake new pickler for pickling to an open output file object file dump(object write an object onto the pickler' file/stream pickle dump(objectfilesame as the last two calls combinedpickle an object onto an open file string pickle dumps(objectreturn the pickled representation of object as character string unpickling from serialized string back to the original object is similar--both object and convenience function interfaces are availableu pickle unpickler(filemake an unpickler for unpickling from an open input file object file object load(read an object from the unpickler' file/stream object pickle load(filesame as the last two calls combinedunpickle an object from an open file object pickle loads(stringread an object from character string rather than file pickler and unpickler are exported classes in all of the preceding casesfile is either an open file object or any object that implements the same attributes as file objectspickler calls the file' write method with string argument unpickler calls the file' read method with byte countand readline without arguments databases and persistence
5,875
particularfile can be an instance of python class that provides the read/write methods ( the expected file-like interfacethis lets you map pickled streams to inmemory objects with classesfor arbitrary use for instancethe io bytesio class in the standard library discussed in provides an interface that maps file calls to and from in-memory byte strings and is an alternative to the pickler' dumps/loads string calls this hook also lets you ship python objects across networkby providing sockets wrapped to look like files in pickle calls at the senderand unpickle calls at the receiver (see "making sockets look like files and streamson page for more detailsin factfor somepickling python objects across trusted network serves as simpler alternative to network transport protocols such as soap and xml-rpcprovided that python is on both ends of the communication (pickled objects are represented with python-specific formatnot with xml textrecent changesin python xpickled objects are always represented as bytesnot strregardless of the protocol level which you request (even the oldest ascii protocol yields bytesbecause of thisfiles used to store pickled python objects should always be opened in binary mode moreoverin an optimized _pickle implementation module is also selected and used automatically if present more on both topics later pickling in action although pickled objects can be shipped in exotic waysin more typical useto pickle an object to flat filewe just open the file in write mode and call the dump functionc:\pp \dbasepython table {' '[ ]' '['spam''eggs']' '{'name':'bob'}import pickle mydb open('dbase''wb'pickle dump(tablemydbnotice the nesting in the object pickled here--the pickler handles arbitrary structures also note that we're using binary mode files herein python xwe really mustbecause the pickled representation of an object is always bytes object in all cases to unpickle later in another session or program runsimply reopen the file and call loadc:\pp \dbasepython import pickle mydb open('dbase''rb'table pickle load(mydbtable {' '[ ]' '{'name''bob'}' '['spam''eggs']pickled objects
5,876
the originalbut it is located at different address in memory this is true whether the object is unpickled in the same or future process againthe unpickled object is =but is not isc:\pp \dbasepython import pickle open('temp''wb' ['hello'('pickle''world')pickle dump(xff close( open('temp''rb' pickle load(fy ['hello'('pickle''world') =yx is (truefalselist with nested tuple close to flush changes same valuediff objects to make this process simpler stillthe module in example - wraps pickling and unpickling calls in functions that also open the files where the serialized form of the object is stored example - pp \dbase\filepickle py "pickle to/from flat file utilitiesimport pickle def savedbase(filenameobject)"save object to filefile open(filename'wb'pickle dump(objectfilefile close(def loaddbase(filename)"load object from filefile open(filename'rb'object pickle load(filefile close(return object pickle to binary file any file-like object will do unpickle from binary file re-creates object in memory to store and fetch nowsimply call these module functionshere they are in action managing fairly complex structure with multiple references to the same nested object--the nested list called at first is stored only once in the filec:\pp \dbasepython from filepickle import [ {' ': ' ':ltable {' ': ' ':dsavedbase('myfile'table databases and persistence appears twice serialize to file
5,877
from filepickle import table loaddbase('myfile'table {' '[ ]' '{' '[ ]' ' }table[' '][ savedbase('myfile'tablec:\pp \dbase>python from filepickle import print(loaddbase('myfile'){' '[ ]' '{' '[ ]' ' }reload/unpickle change shared object rewrite to the file both ' updated as expected besides built-in types like the liststuplesand dictionaries of the examples so farclass instances may also be pickled to file-like objects this provides natural way to associate behavior with stored data (class methods process instance attributesand provides simple migration path (class changes made in module files are automatically picked up by stored instanceshere' brief interactive demonstrationclass recdef __init__(selfhours)self hours hours def pay(selfrate= )return self hours rate bob rec( import pickle pickle dump(bobopen('bobrec''wb')rec pickle load(open('bobrec''rb')rec hours rec pay( we'll explore how this works in more detail in conjunction with shelves later in this -as we'll seealthough the pickle module can be used directly this wayit is also the underlying translation engine in both shelves and zodb databases in generalpython can pickle just about anythingexcept forcompiled code objectsfunctions and classes record just their names and those of their modules in picklesto allow for later reimport and automatic acquisition of changes made in module files instances of classes that do not follow class importability rulesin shortthe class must be importable on object loads (more on this at the end of the section "shelve fileson page instances of some built-in and user-defined types that are coded in or depend upon transient operating system states ( open file objects cannot be pickleda picklingerror is raised if an object cannot be pickled againwe'll revisit the pickler' constraints on pickleable objects and classes when we study shelves pickled objects
5,878
in later python releasesthe pickler introduced the notion of protocols--storage formats for pickled data specify the desired protocol by passing an extra parameter to the pickling calls (but not to unpickling callsthe protocol is automatically determined from the pickled data)pickle dump(objectfileprotocolor protocol= keyword argument pickled data may be created in either text or binary protocolsthe binary protocolsformat is more efficientbut it cannot be readily understood if inspected by defaultthe storage protocol in python is -only binary bytes format (also known as protocol in text mode (protocol )the pickled data is printable ascii textwhich can be read by humans (it' essentially instructions for stack machine)but it is still bytes object in python the alternative protocols (protocols and create the pickled data in binary format as well for all protocolspickled data is bytes object in xnot strand therefore implies binary-mode reads and writes when stored in flat files (see if you've forgotten whysimilarlywe must use bytes-oriented object when forging the file object' interfaceimport iopickle pickle dumps([ ] '\ \ ] \ ( \ \ \ pickle dumps([ ]protocol= '(lp \nl \nal \nal \na default=binary protocol ascii format protocol pickle dump([ ]open('temp','wb')same if protocol= ascii pickle dump([ ]open('temp',' ')must use 'rbto read too typeerrormust be strnot bytes pickle dump([ ]open('temp',' ')protocol= typeerrormust be strnot bytes io bytesio(pickle dump([ ]bb getvalue( '\ \ ] \ ( \ \ \ use bytes streams/buffers io bytesio(pickle dump([ ]bprotocol= getvalue( '(lp \nl \nal \nal \na also bytes for ascii io stringio(it' not str anymore pickle dump([ ]ssame if protocol= ascii typeerrorstring argument expectedgot 'bytespickle dump([ ]sprotocol= typeerrorstring argument expectedgot 'bytes databases and persistence
5,879
here in the interest of space also check out marshala module that serializes an object toobut can handle only simple object types pickle is more general than marshal and is normally preferred an additional related module_pickleis -coded optimization of pickleand is automatically used by pickle internally if availableit need not be selected or used directly the shelve module inherits this optimization automatically by proxy haven' explained shelve yetbut will now shelve files pickling allows you to store arbitrary objects on files and file-like objectsbut it' still fairly unstructured mediumit doesn' directly support easy access to members of collections of pickled objects higher-level structures can be added to picklingbut they are not inherentyou can sometimes craft your own higher-level pickle file organizations with the underlying filesystem ( you can store each pickled object in file whose name uniquely identifies the object)but such an organization is not part of pickling itself and must be manually managed you can also store arbitrarily large dictionaries in pickled file and index them by key after they are loaded back into memorybut this will load and store the entire dictionary all at once when unpickled and picklednot just the entry you are interested in shelves provide structure for collections of pickled objects that removes some of these constraints they are type of file that stores arbitrary python objects by key for later retrievaland they are standard part of the python system reallythey are not much of new topic--shelves are simply combination of the dbm files and object pickling we just metto store an in-memory object by keythe shelve module first serializes the object to string with the pickle moduleand then it stores that string in dbm file by key with the dbm module to fetch an object back by keythe shelve module first loads the object' serialized string by key from dbm file with the dbm moduleand then converts it back to the original in-memory object with the pickle module because shelve uses pickle internallyit can store any object that pickle canstringsnumberslistsdictionariescyclic objectsclass instancesand more because shelve uses dbm internallyit inherits all of that module' capabilitiesas well as its portability constraints shelve files
5,880
in other wordsshelve is just go-betweenit serializes and deserializes objects so that they can be placed in string-based dbm files the net effect is that shelves let you store nearly arbitrary python objects on file by key and fetch them back later with the same key your scripts never see all of this interfacingthough like dbm filesshelves provide an interface that looks like dictionary that must be opened in facta shelve is simply persistent dictionary of persistent python objects--the shelve dictionary' content is automatically mapped to file on your computer so that it is retained between program runs this is quite featbut it' simpler to your code than it may sound to gain access to shelveimport the module and open your fileimport shelve dbase shelve open("mydbase"internallypython opens dbm file with the name mydbaseor creates it if it does not yet exist (it uses the dbm 'cinput/output open mode by defaultassigning to shelve key stores an objectdbase['key'object store object internallythis assignment converts the object to serialized byte stream with pickling and stores it by key on dbm file indexing shelve fetches stored objectvalue dbase['key'fetch object internallythis index operation loads string by key from dbm file and unpickles it into an in-memory object that is the same as the object originally stored most dictionary operations are supported heretoolen(dbasedbase keys(number of items stored stored item key index iterable and except for few fine pointsthat' really all there is to using shelve shelves are processed with normal python dictionary syntaxso there is no new database api to learn moreoverobjects stored and fetched from shelves are normal python objectsthey do not need to be instances of special classes or types to be stored away that ispython' persistence system is external to the persistent objects themselves table - summarizes these and other commonly used shelve operations table - shelve file operations python code action description import shelve import get bsddbgdbmand so on whatever is installed file=shelve open('filename'open create or open an existing shelve' dbm file file['key'anyvalue store create or change the entry for key value file['key'fetch load the value for the entry key count len(filesize return the number of entries stored databases and persistence
5,881
action description index file keys(index fetch the stored keys list (an iterable viewfound 'keyin file query see if there' an entry for key del file['key'delete remove the entry for key for key in fileiterate iterate over stored keys file close(close manual closenot always needed because shelves export dictionary-like interfacetoothis table is almost identical to the dbm operation table herethoughthe module name dbm is replaced by shelveopen calls do not require second argumentand stored values can be nearly arbitrary kinds of objectsnot just strings keys are still stringsthough (technicallykeys are always str which is encoded to and from bytes automatically per utf- )and you still should close shelves explicitly after making changes to be safeshelves use dbm internallyand some underlying dbms require closes to avoid data loss or damage recent changesthe shelve module now has an optional writeback argumentif passed trueall entries fetched are cached in memoryand written back to disk automatically at close time this obviates the need to manually reassign changed mutable entries to flush them to diskbut can perform poorly if many items are fetched--it may require large amount of memory for the cacheand it can make the close operation slow since all fetched entries must be written back to disk (python cannot tell which of the objects may have been changedbesides allowing values to be arbitrary objects instead of just stringsin python the shelve interface differs from the dbm interface in two subtler ways firstthe keys method returns an iterable view object (not physical listsecondthe values of keys are always str in your codenot bytes--on fetchesstoresdeletesand other contextsthe str keys you use are encoded to the bytes expected by dbm using the utf- unicode encoding this means that unlike dbmyou cannot use bytes for shelve keys in your code to employ arbitrary encodings shelve keys are also decoded from bytes to str per utf- whenever they are returned from the shelve api ( keys iterationstored values are always the bytes object produced by the pickler to represent serialized object we'll see these behaviors in action in the examples of this section storing built-in object types in shelves let' run an interactive session to experiment with shelve interfaces as mentionedshelves are essentially just persistent dictionaries of objectswhich you open and closec:\pp \dbasepython import shelve shelve files
5,882
object ['the''bright'('side''of')['life']object {'name''brian''age' 'motto'object dbase['brian'object dbase['knight'{'name''knight''motto''ni!'dbase close(herewe open shelve and store two fairly complex dictionary and list data structures away permanently by simply assigning them to shelve keys because shelve uses pickle internallyalmost anything goes here--the trees of nested objects are automatically serialized into strings for storage to fetch them backjust reopen the shelve and indexc:\pp \dbasepython import shelve dbase shelve open("mydbase"len(dbase entries dbase keys(index keysview(list(dbase keys()['brian''knight'dbase['knight'{'motto''ni!''name''knight'fetch for row in dbase keys()keys(is optional print(row'=>'for field in dbase[rowkeys()print('field'='dbase[row][field]brian =motto ['the''bright'('side''of')['life']age name brian knight =motto niname knight the nested loops at the end of this session step through nested dictionaries--the outer scans the shelve and the inner scans the objects stored in the shelve (both could use key iterators and omit their keys(callsthe crucial point to notice is that we're using normal python syntaxboth to store and to fetch these persistent objectsas well as to process them after loading it' persistent python data on disk storing class instances in shelves one of the more useful kinds of objects to store in shelve is class instance because its attributes record state and its inherited methods define behaviorpersistent class databases and persistence
5,883
programs we can also use the underlying pickle module to serialize instances to flat files and other file-like objects ( network sockets)but the higher-level shelve module also gives us convenient keyed-access storage medium for instanceconsider the simple class shown in example - which is used to model people in hypothetical work scenario example - pp \dbase\person py (version " person objectfields behaviorclass persondef __init__(selfnamejobpay= )self name name self job job self pay pay real instance data def tax(self)return self pay computed on call def info(self)return self nameself jobself payself tax(nothing about this class suggests it will be used for database records--it can be imported and used independent of external storage it' easy to use it for database' recordsthoughwe can make some persistent objects from this class by simply creating instances as usualand then storing them by key on an opened shelvec:\pp \dbasepython from person import person bob person('bob''psychologist' emily person('emily''teacher' import shelve dbase shelve open('cast'make new shelve for obj in (bobemily)store objects dbase[obj nameobj use name for key dbase close(need for bsddb here we used the instance objectsname attribute as their key in the shelve database when we come back and fetch these objects in later python session or scriptthey are re-created in memory exactly as they were when they were storedc:\pp \dbasepython import shelve dbase shelve open('cast'list(dbase keys()['bob''emily'print(dbase['emily']print(dbase['bob'tax() reopen shelve both objects are here callbob' tax shelve files
5,884
class in this last session python is smart enough to link this object back to its original class when unpickledsuch that all the original methods are available through fetched objects changing classes of objects stored in shelves technicallypython reimports class to re-create its stored instances as they are fetched and unpickled here' how this worksstore when python pickles class instance to store it in shelveit saves the instance' attributes plus reference to the instance' class in effectpickled class instances in the prior example record the self attributes assigned in the class reallypython serializes and stores the instance' __dict__ attribute dictionary along with enough source file information to be able to locate the class' module later--the names of the instance' class as well as its class' enclosing module fetch when python unpickles class instance fetched from shelveit re-creates the instance object in memory by reimporting the class using the save class and module name stringsassigning the saved attribute dictionary to new empty instanceand linking the instance back to the class this is be defaultand it can be tailored by defining special methods that will be called by pickle to fetch and store instance state (see the python library manual for detailsthe key point in this is that the class and stored instance data are separate the class itself is not stored with its instancesbut is instead located in the python source file and reimported later when instances are fetched the downside of this model is that the class must be importable to load instances off shelve (more on this in momentthe upside is that by modifying external classes in module fileswe can change the way stored objectsdata is interpreted and used without actually having to change those stored objects it' as if the class is program that processes stored records to illustratesuppose the person class from the previous section was changed to the source code in example - example - pp \dbase\person py (version "" person objectfields behavior changethe tax method is now computed attribute ""class persondef __init__(selfnamejobpay= )self name name databases and persistence
5,885
self pay job pay real instance data def __getattr__(selfattr)if attr ='tax'return self pay elseraise attributeerror(on person attr computed on access other unknown names def info(self)return self nameself jobself payself tax this revision has new tax rate ( percent)introduces __getattr__ qualification overload methodand deletes the original tax method because this new version of the class is re-imported when its existing instances are loaded from the shelve filethey acquire the new behavior automatically--their tax attribute references are now intercepted and computed when accessedc:\pp \dbasepython import shelve dbase shelve open('cast'reopen shelve print(list(dbase keys())both objects are here ['bob''emily'print(dbase['emily']print(dbase['bob'taxno need to call tax( because the class has changedtax is now simply qualifiednot called in additionbecause the tax rate was changed in the classbob pays more this time around of coursethis example is artificialbut when used wellthis separation of classes and persistent instances can eliminate many traditional database update programs in most casesyou can simply change the classnot each stored instancefor new behavior shelve constraints although shelves are generally straightforward to usethere are few rough edges worth knowing about keys must be strings (and strfirstalthough they can store arbitrary objectskeys must still be strings the following failsunless you convert the integer to the string manually firstdbase[ value failsbut str( will work this is different from in-memory dictionarieswhich allow any immutable object to be used as keyand derives from the shelve' use of dbm files internally as we've seenshelve files
5,886
objects are unique only within key although the shelve module is smart enough to detect multiple occurrences of nested object and re-create only one copy when fetchedthis holds true only within given slotdbase[key[objectobjectokonly one copy stored and fetched dbase[key object dbase[key object bad?two copies of object in the shelve when key and key are fetchedthey reference independent copies of the original shared objectif that object is mutablechanges from one won' be reflected in the other this really stems from the fact the each key assignment runs an independent pickle operation--the pickler detects repeated objects but only within each pickle call this may or may not be concern in your practiceand it can be avoided with extra support logicbut an object can be duplicated if it spans keys updates must treat shelves as fetch-modify-store mappings because objects fetched from shelve don' know that they came from shelveoperations that change components of fetched object change only the in-memory copynot the data on shelvedbase[keyattr value shelve unchanged to really change an object stored on shelvefetch it into memorychange its partsand then write it back to the shelve as whole by key assignmentobject dbase[keyobject attr value dbase[keyobject fetch it modify it store back-shelve changed (unless writebackas noted earlierthe shelve open call' optional writeback argument can be used to avoid the last step hereby automatically caching objects fetched and writing them to disk when the shelve is closedbut this can require substantial memory resources and make close operations slow concurrent updates are not directly supported the shelve module does not currently support simultaneous updates simultaneous readers are okbut writers must be given exclusive access to the shelve you can trash shelve if multiple processes write to it at the same timewhich is common potential in things such as server-side scripts on the web if your shelves may be updated by multiple processesbe sure to wrap updates in calls to the os open standard library function to lock files and provide exclusive access databases and persistence
5,887
with shelvesthe files created by an underlying dbm system used to store your persistent objects are not necessarily compatible with all possible dbm implementations or pythons for instancea file generated by gdbm on linuxor by the bsddb library on windowsmay not be readable by python with other dbm modules installed this is really the same portability issue we discussed for dbm files earlier as you'll recallwhen dbm file (or by proxya shelveis createdthe dbm module tries to import all possible dbm system modules in predefined order and uses the first that it finds when dmb later opens an existing fileit attempts to determine which dbm system created it by inspecting the files(sbecause the bsddb system is tried first at file creation time and is available on both windows and many unix-like systemsyour dbm file is portable as long as your pythons support bsd on both platforms this is also true if all platforms you'll use fall back on python' own dbm dumb implementation if the system used to create dbm file is not available on the underlying platformthoughthe dbm file cannot be used if dbm file portability is concernmake sure that all the pythons that will read your data use compatible dbm modules if that is not an optionuse the pickle module directly and flat files for storage (thereby bypassing both shelve and dbm)or use the oodb systems we'll meet later in this such systems may also offer more complete answer to transaction processingwith calls to commit changesand automatic rollback to prior commit points on errors pickled class constraints in addition to these shelve constraintsstoring class instances in shelve adds set of additional rules you need to be aware of reallythese are imposed by the pickle modulenot by shelveso be sure to follow these if you store class instance objects with pickle directly tooclasses must be importable as we've seenthe python pickler stores instance attributes only when pickling an instance objectand it reimports the class later to re-create the instance because of thatthe classes of stored objects must be importable when objects are unpickled--they must be coded unnested at the top level of module file that is accessible on the module import search path at load time ( named in python path or in pth fileor the current working directory or that of the top-level scriptfurtherthe class usually must be associated with real imported module when instances are picklednot with top-level script (with the module name __main__)unless they will only ever be used in the top-level script you also need to be careful about moving class modules after instances are stored when an instance is unpickledpython must find its class' module on the module search using the original module name (including any package path prefixesand fetch the class shelve files
5,888
moved or renamedit might not be found in applications where pickled objects are shipped over network socketsit' possible to satisfy this constraint by shipping the text of the class along with stored instancesrecipients may simply store the class in local module file on the import search path prior to unpickling received instances where this is inconvenient or impossiblesimpler pickled objects such as lists and dictionaries with nesting may be transferred insteadas they require no source file to be reconstructed class changes must be backward compatible although python lets you change class while instances of it are stored on shelvethose changes must be backward compatible with the objects already stored for instanceyou cannot change the class to expect an attribute not associated with already stored persistent instances unless you first manually update those stored instances or provide extra conversion protocols on the class other pickle module constraints shelves also inherit the pickling systemsnonclass limitations as discussed earliersome types of objects ( open files and socketscannot be pickledand thus cannot be stored in shelve in an early python releasepersistent object classes also had to either use constructors with no arguments or provide defaults for all constructor arguments (much like the notion of +copy constructorthis constraint was dropped as of python -classes with nondefaulted constructor arguments now work as is in the pickling system other shelve limitations finallyalthough shelves store objects persistentlythey are not really object-oriented database systems such systems also implement features such as immediate automatic write-through on changestransaction commits and rollbackssafe concurrent updatesand object decomposition and delayed ("lazy"component fetches based on generated object ids parts of larger objects may be loaded into memory only as they are accessed it' possible to extend shelves to support such features manuallybut you don' need to--the zodb systemamong othersprovides an implementation of more complete object-oriented database system it is constructed on top of python' built-in pickling interestinglypython avoids calling the class to re-create pickled instance and instead simply makes class object genericallyinserts instance attributesand sets the instance' __class__ pointer to the original class directly this avoids the need for defaultsbut it also means that the class __init__ constructors that are no longer called as objects are unpickledunless you provide extra methods to force the call see the library manual for more detailsand see the pickle module' source code (pickle py in the source libraryif you're curious about how this works or see the pyform example later in this -it does something very similar with __class__ links to build an instance object from class and dictionary of attributeswithout calling the class' __init__ constructor this makes constructor argument defaults unnecessary in classes used for records browsed by pyformbut it' the same idea databases and persistence
5,889
on zodblet' move on to the next section the zodb object-oriented database zodbthe zope object databaseis full-featured and python-specific object-oriented database (oodbsystem zodb can be thought of as more powerful alternative to python' shelves of the preceding section it allows you to store nearly arbitrary python objects persistently by keylike shelvesbut it adds set of additional features in exchange for small amount of extra interface code zodb is not the only oodb available for pythonthe durus system is generally seen as simpler oodb which was inspired by zodb while durus offers some advantagesit does not provide all the features of zodb todayand it has not been as widely deployed (though perhaps in part because it is newerbecause of thatthis section focuses on zodb to introduce oodb concepts in general zodb is an open sourcethird-party add-on for python it was originally developed as the database mechanism for websites developed with the zope web framework mentioned in but it is now available as standalone package it' useful outside the context of both zope and the web as general database management system in any domain although zodb does not support sql queriesobjects stored in zodb can leverage the full power of the python language moreoverin some applicationsstored data is more naturally represented as structured python object table-based relational systems often must represent such data as individual parts scattered across multiple tables and associate them with complex and potentially slow key-based joinsor otherwise map them to and from the python class model because oodbs store native python objects directlythey can often provide simpler model in systems which do not require the full power of sql using zodb database is very similar to python' standard library shelvesdescribed in the prior section just like shelveszodb uses the python pickling system to implement persistent dictionary of persistent python objects in factthere is almost no database interface to be found--objects are made persistent simply by assigning them to keys of the root zodb dictionary objector embedding them in objects stored in the database root and as in shelve"recordstake the form of native python objectsprocessed with normal python syntax and tools unlike shelvesthoughzodb adds features critical to some types of programsconcurrent updates you don' need to manually lock files to avoid data corruption if there are potentially many concurrent writersthe way you would for shelves the zodb object-oriented database
5,890
if your program crashesyour changes are not retained unless you explicitly commit them to the database automatic updates for some types of in-memory object changes objects in zodb derived from persistence superclass are smart enough to know the database must be updated when an attribute is assigned automatic caching of objects objects are cached in memory for efficiency and are automatically removed from the cache when they haven' been used platform-independent storage because zodb stores your database in single flat file with large-file supportit is immune to the potential size constraints and dbm filesystem format differences of shelves as we saw earlier in this shelve created on windows using bsddb may not be accessible to script running with gdbm on linux because of such advantageszodb is probably worth your attention if you need to store python objects in database persistently in production environment the only significant price you'll pay for using zodb is small amount of extra codeaccessing the database requires small amount of extra boilerplate code to interface with zodb--it' not simple open call classes are derived from persistence superclass if you want them to take advantage of automatic updates on changes--persistent classes are generally not as completely independent of the database as in shelvesthough they can be considering the extra functionality zodb provides beyond shelvesthese trade-offs are usually more than justified for many applications the mostly missing zodb tutorial unfortunatelyas write this edition in june zodb is not yet available for python xthe version used in this book because of thatthe prior edition' python examples and material have been removed from this section howeverin deference to python usersas well as readers of some bright future where -base zodb has materializedi've made the prior edition' zodb materials and examples available in this edition' examples package see the preface for details on the examples packageand see these locations within it for more on zodbc:\dbase\zodb- :\dbase\zodb- \documentaion zodb examples code third edition the rd edition' zodb tutorial although cannot predict the futurezodb will likely become available for python eventually in the absence of thisother python-based oodbs may offer additional options databases and persistence
5,891
operation in python once we've installed compatible zodbwe begin by first creating database\pp \dbase\zodb- xpython from zodb import filestoragedb storage filestorage filestorage( ' :\temp\mydb fs'db db(storageconnection db open(root connection root(this is mostly standard "boilerplatecode for connecting to zodb databasewe import its toolscreate filestorage and db from itand then open the database and create the root object the root object is the persistent dictionary in which objects are stored filestorage is an object that maps the database to flat file other storage interface optionssuch as relational database-based storageare also possible adding objects to zodb database is as simple as in shelves almost any python object will doincluding tupleslistsdictionariesclass instancesand nested combinations thereof as for shelvesimply assign your objects to key in the database root object to make them persistentobject ( 'spam' 'you'object [[ ][ ][ ]object {'name'['bob''doe']'age' 'job'('dev''mgr')root['mystr''spam root['mytuple'object root['mylist'object root['mydict'object root['mylist'[[ ][ ][ ]because zodb supports transaction rollbacksyou must commit your changes to the database to make them permanent ultimatelythis transfers the pickled representation of your objects to the underlying file storage medium--herethree files that include the name of the file we gave when openingimport transaction transaction commit(storage close(\pp \dbase\zodb- xdir / :\temp\mydbmydb fs mydb fs index mydb fs tmp without the final commit in this sessionnone of the changes we made would be saved this is what we want in general--if program aborts in the middle of an update taskthe zodb object-oriented database
5,892
general database undo operations pulling persistent objects back from zodb in another session or program is just as straightforwardreopen the database as before and index the root to fetch objects back into memory like shelvesthe database root supports dictionary interfaces--it may be indexedhas dictionary methods and lengthand so on\pp \dbase\zodb- xpython from zodb import filestoragedb storage filestorage filestorage( ' :\temp\mydb fs'db db(storageconnection db open(root connection root(connect len(root)root keys(( ['mylist''mystr''mytuple''mydict']sizeindex root['mylist'fetch objects [[ ][ ][ ]root['mydict'{'job'('dev''mgr')'age' 'name'['bob''doe']root['mydict']['name'][- 'doebob' last name because the database root looks just like dictionarywe can process it with normal dictionary code--stepping through the keys list to scan record by recordfor instancefor key in root keys()print('% =% (key ljust( )root[key])mylist mystr mytuple mydict =[[ ][ ][ ]=spamspamspam =( 'spam' 'you'={'job'('dev''mgr')'age' 'name'['bob''doe']also like pickling and shelveszodb supports storage and retrieval of class instance objectsthough they must inherit from superclass which provides required protocol and intercepts attribute changes in order to flush them to disk automaticallyfrom persistent import persistent class person(persistent)def __init__(selfnamejob=nonerate= )self name name self job job self rate rate def changerate(selfnewrate)self rate newrate automatically updates database when changing zodb persistent class instancesin-memory attribute changes are automatically written back to the database other types of changessuch as in-place appends and key assignmentsstill require reassignment to the original key as in shelves databases and persistence
5,893
know that they are persistentbecause zodb does not yet work with python xthat' as much as we can say about it in this book for more detailssearch for zodb and zope resources on the weband see the examples package resources listed earlier herelet' move on to see how python programs can make use of very different sort of database interface--relational databases and sql sql database interfaces the shelve module and zodb package of the prior sections are powerful tools both allow scripts to throw nearly arbitrary python objects on keyed-access file and load them back later--in single step for shelves and with small amount of administrative code for zodb especially for applications that record highly structured dataobject databases can be convenient and efficient--there is no need to split and later join together the parts of large objectsand stored data is processed with normal python syntax because it is normal python objects shelves and zodb aren' relational database systemsthoughobjects (recordsare accessed with single keyand there is no notion of sql queries shelvesfor instanceare essentially databases with single index and no other query-processing support although it' possible to build multiple-index interface to store data with multiple shelvesit' not trivial task and requires manually coded extensions zodb supports some types of searching beyond shelve ( its cataloging feature)and persistent objects may be traversed with all the power of the python language howeverneither shelves nor zodb object-oriented databases provide the full generality of sql queries moreoverespecially for data that has naturally tabular structurerelational databases may sometimes be better fit for programs that can benefit from the power of sqlpython also broadly supports relational database management systems (rdbmssrelational databases are not necessarily mutually exclusive with the object persistence topics we studied earlier in this -it is possiblefor exampleto store the serialized string representation of python object produced by pickling in relational database zodb also supports the notion of mapping an object database to relational storage medium the databases we'll meet in this sectionthoughare structured and processed in very different waysthey store data in related tables of columns (rather than in persistent dictionaries of arbitrarily structured persistent python objectsthey support the sql query language for accessing data and exploiting relationships among it (instead of python object traversalssql database interfaces
5,894
sql-based database systems provide industrial-strength persistence support for enterprise-level data todaythere are freely available interfaces that let python scripts utilize all common relational database systemsboth free and commercialmysqloraclesybaseinformixinterbasepostgresql (postgres)sqliteodbcand more in additionthe python community has defined database api specification that works portably with variety of underlying database packages scripts written for this api can be migrated to different database vendor packageswith minimal or no source code changes as of python python itself includes built-in support for the sqlite relational database system as part of its standard library because this system supports the portable database apiit serves as tool for both program storage and prototyping--systems developed with sqlite work largely unchanged when more feature-rich database such as mysql or oracle is deployed moreoverthe popular sqlobject and sqlalchemy third-party systems both provide an object relational mapper (orm)which grafts an object interface onto your databasein which tables are modeled by as python classesrows by instances of those classesand columns by instance attributes since orms largely just wrap sql databases in python classeswe'll defer their coverage until later in this for nowlet' explore sql basics in python sql interface overview like zodband unlike the pickle and shelve persistence modules presented earliermost sql databases are optional extensions that are not part of python itself sqlite is the only relational database package that comes with python moreoveryou need to know sql to fully understand their interfaces because we don' have space to teach sql in this textthis section gives brief overview of the apiplease consult other sql references and the database api resources mentioned in the next section for more details that we'll skip here the good news is that you can access sql databases from pythonthrough straightforward and portable model the python database api specification defines an interface for communicating with underlying database systems from python scripts vendorspecific database interfaces for python may or may not conform to this api completelybut all database extensions for python in common use are minor variations on theme under the database apisql databases in python are grounded on three core conceptsconnection objects represent connection to databaseare the interface to rollback and commit operationsprovide package implementation detailsand generate cursor objects databases and persistence
5,895
represent an sql statement submitted as string and can be used to access and step through sql statement results query results of sql select statements are returned to scripts as python sequences of sequences ( list of tuples)representing database tables of rows within these row sequencescolumn field values are normal python objects such as stringsintegersand floats ( [('bob' )('emily', )]column values may also be special types that encapsulate things such as date and timeand database null values are returned as the python none object beyond thisthe api defines standard set of database exception typesspecial database type object constructorsand informational top-level calls including thread safety and replacement style checks for instanceto establish database connection under the python api-compliant oracle interfaceinstall the commonly used python oracle extension module as well as oracle itselfand then run statement of this formconnobj connect("user/password@system"this call' arguments may vary per database and vendor ( some may require network details or local file' name)but they generally contain what you provide to log in to your database system once you have connection objectthere variety of things you can do with itincludingconnobj close(connobj commit(connobj rollback(close connection now (not at object __del__ timecommit any pending transactions to the database roll database back to start of pending transactions but one of the most useful things to do with connection object is to generate cursor objectcursobj connobj cursor(return new cursor object for running sql cursor objects have set of methodstoo ( close to close the cursor before its destructor runsand callproc to call stored procedure)but the most important may be this onecursobj execute(sqlstring [parameters]run sql query or command string parameters are passed in as sequence or mapping of valuesand are substituted into the sql statement string according to the interface module' replacement target conventions the execute method can be used to run variety of sql statement stringsddl definition statements ( create tabledml modification statements ( update or insertdql query statements ( selectsql database interfaces
5,896
rows changed (for dml changesor fetched (for dql queries)and the cursor' description attribute gives column names and types after queryexecute also returns the number of rows affected or fetched in the most vendor interfaces for dql query statementsyou must call one of the fetch methods to complete the operationtuple cursobj fetchone(listoftuple cursobj fetchmany([size]listoftuple cursobj fetchall(fetch next row of query result fetch next set of rows of query result fetch all remaining rows of the result and once you've received fetch method resultstable information is processed using normal python sequence operationsfor exampleyou can step through the tuples in fetchall result list with simple for loop or comprehension expression most python database interfaces also allow you to provide values to be passed to sql statement stringsby providing targets and tuple of parameters for instancequery 'select nameshoesize from spam where job and age ?cursobj execute(query(value value )results cursobj fetchall(for row in resultsin this eventthe database interface utilizes prepared statements (an optimization and convenienceand correctly passes the parameters to the database regardless of their python types the notation used to code targets in the query string may vary in some database interfaces ( : and : or two %srather than the two ? used by the oracle interface)in any eventthis is not the same as python' string formatting operatoras it sidesteps security issues along the way finallyif your database supports stored proceduresyou can call them with the call proc method or by passing an sql call or exec statement string to the execute method callproc may generate result table retrieved with fetch variantand returns modified copy of the input sequence--input parameters are left untouchedand output and input/output parameters are replaced with possibly new values additional api featuresincluding support for database blobs (roughlywith sized results)is described in the api' documentation for nowlet' move on to do some real sql processing in python an sql database api tutorial with sqlite we don' have space to provide an exhaustive reference for the database api in this book to sample the flavor of the interfacethoughlet' step through few simple examples we'll use the sqlite database system for this tutorial sqlite is standard part of python itselfwhich you can reasonably expect to be available in all python installations although sqlite implements complete relational database systemit takes the form of an in-process library instead of server this generally makes it better suited for program storage than for enterprise-level data needs databases and persistence
5,897
such as postgresqlmysqland oracle are used almost identicallythe initial call to log in to the database will be all that normally requires different argument values for scripts that use standard sql code because of thiswe can use the sqlite system both as prototyping tool in applications development and as an easy way to get started with the python sql database api in this book as mentioned earlierthe third edition' coverage of mysql had to be replaced here because the interface used is not yet ported to python howeverthe third edition' mysql-based examples and overview are available in the book examples packagein directory :\pp \dbase \sql\mysql- xand its documentation subdirectory the examples are in python formbut their database-related code is largely version neutral since that code is also largely database neutralit is probably of limited value to most readersthe scripts listed in this book should work on other database packages like mysql with only trivial changes getting started regardless of which database system your scripts talk tothe basic sql interface in python is very simple in factit' hardly object-oriented at all--queries and other database commands are sent as strings of sql if you know sqlyou already have most of what you need to use relational databases in python that' good news if you fall into this categorybut adds prerequisite if you don' this isn' book on the sql languageso we'll defer to other resources for details on the commands we'll be running here ( 'reilly has suite of books on the topicin factthe databases we'll use are tinyand the commands we'll use are deliberately simple as sql goes--you'll want to extrapolate from what you see here to the more realistic tasks you face this section is just brief look at how to use the python language in conjunction with an sql database whether large or smallthoughthe python code needed to process your database turns out to be surprisingly straightforward to get startedthe first thing we need to do is open connection to the database and create table for storing recordsc:\pp \dbase\sqlpython import sqlite conn sqlite connect('dbase 'use full path for files elsewhere we start out by importing the python sqlite interface here--it' standard library module called sqlite to our scripts next we create connection objectpassing in the items our database requires at start-up time--herethe name of the local file where our databases will be stored this file is what you'll want to back up to save your database it will create the file if neededor open its current contentsqlite also accepts that special string ":memory:to create temporary database in memory instead sql database interfaces
5,898
usually the only thing that can vary across different database systems for examplein the mysql interface this call accepts network host' domain nameuser nameand passwordpassed as keyword arguments insteadand the oracle example sketched earlier expects more specific sting syntax once we've gotten past this platformspecific callthoughthe rest of the api is largely database neutral making databases and tables nextlet' make cursor for submitting sql statements to the database serverand submit one to create first tablecurs conn cursor(tblcmd 'create table people (name char( )job char( )pay int( ))curs execute(tblcmdthe last command here creates the table called "peoplewithin the databasethe namejoband pay information specifies the columns in this tableas well as their datatypesusing "type(size)syntax--two strings and an integer datatypes can be more sophisticated than oursbut we'll ignore such details here (see sql referencesin sqlitethe file is the databaseso there' no notion of creating or using specific database within itas there is in some systems at this pointthere is simple flat file in the current working directory named data which contains binary data and contains our people database table adding records so farwe've logged in (which just means opening local file in sqliteand created table next let' start new python session and create some records there are three basic statement-based approaches we can use hereinserting one row at time or inserting multiple rows with single call statement or python loop here is the simple case ( ' omitting some call return values here if they are irrelevant to the story) :\pp \dbase\sqlpython import sqlite conn sqlite connect('dbase 'curs conn cursor(curs execute('insert into people values (???)'('bob''dev' )curs rowcount sqlite paramstyle 'qmarkcreate cursor object to submit sql statements to the database server as before the sql insert command adds single row to the table after an execute callthe cursor' rowcount attribute gives the number of rows produced or affected by the last statement run this is also available as the return value of an execute call in some database interface modulesbut this is not defined in the database api specificationand isn' databases and persistence
5,899
to work on other database systems parameters to substitute into the sql statement string are generally passed in as sequence ( list or tuplenotice the module' paramstyle--this tells us what style it uses for substitution targets in the statement string hereqmark means this module accepts for replacement targets other database modules might use styles such as format (meaning % target)or numeric indexes or mapping keyssee the db api for more details to insert multiple rows with single statementuse the executemany method and sequence of row sequences ( list of liststhis call is like calling execute once for each row sequence in the argumentand in fact may be implemented as suchdatabase interfaces may also use database-specific techniques to make this run quickerthoughcurs executemany('insert into people values (???)'('sue''mus'' ')('ann''mus'' ')]curs rowcount we inserted two rows at once in the last statement it' hardly any more work to achieve the same result by inserting one row at time with python looprows [['tom''mgr' ]['kim''adm' ]['pat''dev' ]for row in rowscurs execute('insert into people values (??)'rowconn commit(blending python and sql like this starts to open up all sorts of interesting possibilities notice the last commandwe always need to call the connection' commit method to write our changes out to the database otherwisewhen the connection is closedour changes may be lost in factuntil we call the commit methodnone of our inserts may be visible from other database connections technicallythe api suggests that connection object should automatically call its rollback method to back out changes that have not yet been committedwhen it is closed (which happens manually when its close method is calledor automatically when the connection object is about to be garbage collectedfor database systems that don' support transaction commit and rollback operationsthese calls may do nothing sqlite implements both the commit and rollback methodsthe latter rolls back any changes made since the last commit sql database interfaces