id
int64
0
25.6k
text
stringlengths
0
4.59k
5,600
this window is much like the message view window we saw in figure - except there are no quick-access part buttons in the middle (this window is new mailit has fields for entering header line detailaction buttons for sending the email and managing attachment files added to it when sentand an attached texteditor object c...
5,601
the sender' own address if this header is enabled in mailconfigthis prefill sends copy to the sender (in addition to that written to the sent-mail file)but it can be deleted if unwanted also in compose windowsthe attach button issues file selection dialog for attaching file to your messageas in figure - the parts butto...
5,602
since sent the earlier message to myselfit shows up in mine the next time press the main window' load buttonas we see in figure - figure - pymailgui main window after loading sent mail the pymailgui client
5,603
email now--pymailgui is smart enough to download only the one new message' header text and tack it onto the end of the loaded email list mail send operations automatically save sent mails in save file that you name in your configuration moduleuse open to view sent messages in offline mode and delete to clean up the sen...
5,604
buttons in the middle they are also listed by the parts pop up dialogand they can be saved and opened all at once with split figure - shows this window' parts list pop upand figure - displays this window' split dialog in action figure - parts dialog listing all message parts figure - split dialog selection the pymailgu...
5,605
directory you selectand known parts are automatically opened individual parts are also automatically opened by the row of quick-access buttons labeled with the part' filename in the middle of the view windowafter being saved to temporary directorythis is usually more convenientespecially when there are many attachments...
5,606
the save button in the view window itselfthe main part is includedbecause not all mails have text part for messages that have only html for their main text partpymailgui displays plain text extracted from its html text in its own windowand opens web browser to view the mail with its html formatting againi'll say more o...
5,607
figure - view window for mail with many parts like much of pymailgui' behaviorthe maximum number of part buttons to display in view windows can be configured in the mailconfig py user settings module that setting specified eight buttons in figure - figure - shows what the same mail looks like when the part buttons sett...
5,608
as sample of other attachmentsbehaviorfigures - and - show what happens when the sousa au and pdf buttons in figures - and - are pressed on my windows laptop the results vary per machinethe audio file opens in windows media playermp files open in itunes insteadand some platforms may open such files directly in web brow...
5,609
up simple unformatted display of the mail' raw text (its full text is downloaded in thread if it hasn' yet been fetched and cachedpart of the raw version of the mail sent to myself in figure - is shown in figure - in this editionraw text is displayed in pyedit pop-up window (its prior scrolled-text display is still pre...
5,610
mail just sent to myself (arguably narcissisticbut demonstrative)the mail composition window shown in figure - appears this window is identical in format to the one we saw for the write operationexcept that pymailgui fills in some parts automatically in factthe only thing 've added in this window is the first line in t...
5,611
the optional bcc lineif enabled in the mailconfig moduleis prefilled with the sender' addresstoosince it' often used this way to retain copy (new in this versionthe body of the reply is initialized with the signature line in mailconfigalong with the original message' text the original message text is quoted with charac...
5,612
extracts all of the original message' header linesand single string replace method call does the work of adding the quotes to the original message body simply type what wish to say in reply (the initial paragraph in the mail' text areaand press the send button to route the reply message to the mailbox on my mail server...
5,613
they are not continuation of group discussions notice that ' forwarding this message to three different addresses (two in the toand one manually entered in the bcci' also using full "name formats for email addresses multiple recipient addresses are separated with comma (,in the toccand bcc header fieldsand pymailgui is...
5,614
from there into python list from which it is displayed in factit went to three different email accounts have (the other two appear later in this demo--see figure - the third recipient doesn' appear in figure - here because it was bcc blind-copy-it receives the messagebut no header line is added to the mail itself figur...
5,615
addresses in group mail scenarios open this version' mail save file to view this mail' behavior liveand see the suggested enhancements later for more ideas deleting email so farwe've covered every action button on list windows except for delete and the all checkbox the all checkbox simply toggles from selecting all mes...
5,616
figure - pymailgui delete verification on quit by designno mail is ever removed automaticallyyou will see the same messages the next time pymailgui runs it deletes mail from your server only when you ask it toand then only if verified in the last pop up shown (this is your last chance to prevent permanent mail removala...
5,617
files may be processed pop message numbers and synchronization by nowwe've seen all the basic functionality of pymailgui--enough to get you started sending and receiving simple but typical text-based messages in the rest of this demowe're going to turn our attention to some of the deeper concepts in this systemincludin...
5,618
similarlyboth index list loads and individual message fetches run synchronization test in mailtoolsas well figure - captures the error generated on fetch if message has been deleted in another client since we last loaded the server index window the same error is issued when this occurs during load operationbut the firs...
5,619
inbox content by pymailgui immediately after the error pop up is dismissed this scheme ensures that pymailgui won' delete or display the wrong messagein the rare case that the server' inbox is changed without its knowledge see mailtools in for more on synchronization teststhese errors are detected and raised in mail to...
5,620
figure - viewing html-only mails the pymailgui client
5,621
plain text from itbut it cannot display html directly in its own window and has no support for editing it specially these are enhancements that will have to await further attention by other programmers who may find them useful mail content internationalization support our next advanced feature is something of an inevit...
5,622
figure - raw text of fetched internationalized mailsheaders and body encoded as additional contextfigure - shows how these messagesmain parts appear when opened via their part buttons their content is saved as raw post-mime bytes in binary modebut the pyedit pop ups decode according to passed-in encoding names obtained...
5,623
from the raw message headers as we learned in and the underlying tkinter toolkit generally renders decoded str better than raw bytes so farwe've displayed internationalized emailsbut pymailgui allows us to send them as welland handles any encoding tasks implied by the text content figure - shows the result of running r...
5,624
message headers are similarly encoded per utf- if they are non-ascii when sentso they will work in the full email text in factif you study this closely you'll find that the subject here was originally encoded per russian unicode scheme but is utf- now-its new representation yields the same characters (code pointswhen d...
5,625
alternative configurations and accounts so farwe've mostly seen pymailgui being run on an email account created for this book' examplesbut it' easy to tailor its mailconfig module for different accountsas well as different visual effects for examplefigure - captures the scene with pymailgui being run on three different...
5,626
multiple windows and status messages finallypymailgui is really meant to be multiple-window interface-- detail that most of the earlier screenshots haven' really done justice to for examplefigure - shows pymailgui with the main server list windowtwo save-file list windowstwo message view windowsand help all these windo...
5,627
messages when pymailgui is started from another programsuch as the pydemos or pygadgets launcher bar guis these status messages print server informationshow mail loading statusand trace the loadstoreand delete threads that are spawned along the way if you want pymailgui to be more verboselaunch it from command line and...
5,628
content-typetext/plaincharset="us-asciicontent-transfer-encoding bit frompp @learning-python com tolutz@rmi net subjectalready got one datefri jun : : - -mailerpymailgui (pythonorigin send exit you can also double-click on the pymailgui py filename in your file explorer gui and monitor the popped-up dos console box on ...
5,629
common superclass to avoid redundancy and simplify the code message view windows are similarly factoreda common view window superclass is reused and customized for writereplyand forward view windows to make the code easier to followit is divided into two main modules that reflect the structure of the gui--one for the i...
5,630
the pydemos launcher of for example example - pp \internet\email\pymailgui\pymailgui py ""#################################################################################pymailgui python/tkinter email client client-side tkinter-based gui interface for sending and receiving email see the help string in pymailguihelp py...
5,631
wraplines py utility for wrapping long lines of messages html text py rudimentary html parser for extracting plain text mailconfig py user configuration parametersserver namesfontsetc ==program-specific modules defined here:=sharednames py objects shared between window classes and main file viewwindows py implementatio...
5,632
windows componentwindow __init__(selfpymailserver __init__(selfclass pymailfilewindow(pymailfilewindows popupwindow)" toplevelwith extra protocol and mixed-in methodsdef __init__(selffilename)windows popupwindow __init__(selfappnamefilenamepymailfile __init__(selffilename################################################...
5,633
from tkinter simpledialog import askstring from tkinter filedialog import saveasopendirectory from tkinter messagebox import showinfoshowerroraskyesno reuse book examples from pp gui tools import windows from pp gui tools import threadtools from pp internet email import mailtools from pp gui texteditor import textedito...
5,634
load and delete calls to the server or local file list windows are created on program startup (the initial server windowand possible save-file windows for command-line options)as well as in response to open button actions in existing list windows (for opening new save-file list windowssee the open button' callback in t...
5,635
##############################################################################main frame general structure for both file and server message lists ##############################################################################class pymailcommon(mailtools mailparser)""an abstract widget packagewith main mail listboxmixed ...
5,636
button(toolstext=titlecommand=callbackpack(side=leftadd multiselect listbox with scrollbars listwide mailconfig listwidth or config start size listhigh mailconfig listheight or wide=charshigh=lines mails frame(selfvscroll scrollbar(mailshscroll scrollbar(mailsorient='horizontal'fontsz (sys platform[: ='winand or defaul...
5,637
browser insert(' 'fulltextbrowser pack(expand=yesfill=bothelseemore useful pyedit text editor wintitle raw message textbrowser texteditor texteditormainpopup(selfwintitle=wintitlebrowser update(browser setalltext(fulltextbrowser clearmodified(def onviewformatmail(self)""possibly threadedview selected messages pop up fo...
5,638
if type ='text/html'if ((not mailconfig verifyhtmltextopenor askyesno(appname'open message text in browser?')) get post mime decodepre unicode decode bytes typeasbytes self findmaintext(messageasstr=falsetryfrom tempfile import gettempdir or tk html viewertempname os path join(gettempdir()'pymailgui html'tmp open(tempn...
5,639
on all displayed headers (the extra subject decode is no-op)on sendsall non-ascii hdrs and hdr email names are in decoded form in the guibut are encoded within the mailtools packagequoteorigtext also decodes the initial headers it inserts into the quoted text blockand index lists decode for display""for msgnum in msgnu...
5,640
""msgnums self selectedmsgs(if not msgnumsshowerror(appname'no message selected'elsecaveatdialog warns about replacing file filename self savedialog show(shared class attr if filenamedon' verify num msgs filename os path abspath(filenamenormalize to self getmessages(msgnumsafter=lambdaself contsave(msgnumsfilename)def ...
5,641
always verify here showerror(appname'no message selected'elseif askyesno(appname'verify delete % mails?len(msgnums))self dodelete(msgnums#################utility methods #################def selectedmsgs(self)get messages selected in main listbox selections self listbox curselection(return [int( )+ for in selectionstup...
5,642
no is_multipart yet msgline (msgtype ='multipartand '*'or msgline +'% (ix+ for key in showhdrsmysize maxsize[keyif key not in addrhdrskeytext self decodeheader(msg get(key')elsekeytext self decodeaddrheader(msg get(key')msgline +%-* (mysizekeytext[:mysize]msgline +' fk(self mailsize(ix+ optional self listbox insert(end...
5,643
also already in fully decoded formcould be in any unicode scheme""quoted '\noriginal message\nfor hdr in ('from''to''subject''date')rawhdr message get(hdr'?'if hdr not in ('from''to')dechdr self decodeheader(rawhdrfull value elsedechdr self decodeaddrheader(rawhdrname parts only quoted +'% % \ (hdrdechdrquoted +'\nmain...
5,644
""def actions(self)return ('open'self onopenmailfile)('write'self onwritemail)('none) separators ('view'self onviewformatmail)('reply'self onreplymail)('fwd'self onfwdmail)('save'self onsavemailfile)('delete'self ondeletemail)('none)('quit'self quitdef __init__(selffilename)callerdo loadmailfilethread next pymailcommon...
5,645
allmsgs file read(self msglist allmsgs split(savemailseparator)[ :full text self hdrlist list(map(self parseheadersself msglist)msg objects def onloadmailfileexit(selfsavetitle)on thread success self title(savetitlereset window title to filename self fillindex(updates guido in main thread self lift(raise my window self...
5,646
run in thread while gui active indexed enumerate(self msglistkeepers [msg for (ixmsgin indexed if ix+ not in msgnumsallmsgs savemailseparator join([''keepersfile open(self filename' 'encoding=mailconfig fetchencodingfile write(allmsgsself msglist keepers self hdrlist list(map(self parseheadersself msglist)def ondeletem...
5,647
main window when viewing messages on the mail server ##############################################################################class pymailserver(pymailcommon)""customize pymailcommon for viewing mail still on servermixed with tktoplevelor frameadds main mail listboxmaps loadfetchdelete actions to email server inbo...
5,648
showhtmlhelp( html version without source file links def onshowmysource(selfshowasmail=false)""display my sourcecode fileplus imported modules here elsewhere ""import pymailguilistwindowsviewwindowssharednamestextconfig from pp internet email mailtools import mailtools now pkg mailsendermailfetchermailparsercan' use in...
5,649
def onloadhdrsexit(selfpopup)self fillindex(popup quit(self lift(loadinghdrsbusy decr(allow other actions to run def onloadhdrsfail(selfexc_infopopup)popup quit(showerror(appname'load failed\ % \ %sexc_info[: ]printstack(exc_infosend stack trace to stdout loadinghdrsbusy decr(if exc_info[ =mailtools messagesyncherrorsy...
5,650
new threadsome msgnums changed def ondeleteprogress(selfinpopup)popup changetext('% of % (in)def getmessages(selfmsgnumsafter)""threadedprefetch all selected messages into cache nowused by saveviewreplyand forward to prefill cachemay overlap with other loadmsgs and sendsdisables delete,loadonly runs "afteraction if the...
5,651
self onloadserver(forcereload=truesynch inbox/index new threadreload def onloadmsgsprogress(selfinafterpopuptoload)popup changetext('% of % (in)def getmessage(selfmsgnum)return self cache getmessage(msgnumfull mail text def headersmaps(self)list of email message message objects requires list(if map(return [self parsehe...
5,652
new in pyedit supports arbitrary unicode for message parts viewed new in supports unicode/mail encodings for headers in mails sent tbdcould avoid verifying quits unless text area modified (like pyedit )but these windows are largerand would not catch headers already changed tbdshould open dialog in write windows be prog...
5,653
self actionbuttons(for (labelcallbackin myactionsb button(actionsframetext=labelcommand=callbackb config(bg='beige'relief=ridgebd= pack(side=topexpand=yesfill=bothbody textpack last=clip first self editor pack(side=bottommay be multiple editors self update( else may be line self editor setalltext(showtexteach has own c...
5,654
for (iheaderin enumerate(showhdrs)lab label(middletext=header+':'justify=leftent entry(middlelab grid(row=icolumn= sticky=ewent grid(row=icolumn= sticky=ewmiddle rowconfigure(iweight= hdrvalue headermap get(header'?'might be empty if encodeddecode per email+mime+unicode if header not in addrhdrshdrvalue self decodehead...
5,655
part display code in onview of the list window class)""trysavedir self temppartdir message self origmessage (contypesavepathself saveonepart(savedirpartnamemessageexceptshowerror(appname'error while writing part file'printstack(sys exc_info()elseself openparts([(contypeos path abspath(savepath))]reuse def onparts(self)...
5,656
safe filename extension such as htmlcaveatimage/audio/video could be opened with the book' playfile pycould also do that if text viewer failswould start notepad on windows via startfilewebbrowser may handle most cases here toobut specific is better""def textpartencoding(fullfilename)"" map text part filename back to ch...
5,657
if self askopen(appname'open text part "% "?basename)tryencoding textpartencoding(fullfilenametexteditor texteditormainpopup(parent=selfwintitle=% email part(encoding or '?')loadfirst=fullfilenameloadencode=encodingexceptshowerror(appname'error opening text viewer'multimedia typeswindows opens mediaplayerimagevieweretc...
5,658
return [('cancel'self quit)('parts'self onparts)('attach'self onattach)('send'self onsend)need method to use self popupwindow verifies cancel edon' padcentered def onparts(self)caveatdeletes not currently supported if not self attachesshowinfo(appname'nothing attached'elsemsg '\njoin(['already attached:\ 'self attaches...
5,659
bodytext encode(bodytextencodingexcept (unicodeerrorlookuperror)bodytextencoding 'utf- lookupbad encoding name general code point scheme resolve any text part attachment encodings attachesencodings [config mailconfig attachmenttextencoding for filename in self attachesif not istextkind(filename)attachesencodings append...
5,660
fieldvalues [entry get(for entry in self hdrfieldsfromtoccsubj fieldvalues[: extrahdrs [('cc'cc)(' -mailer'appname (python)')extrahdrs +list(zip(self userhdrsfieldvalues[ :])bodytext self editor getalltext(split multiple recipient lists on ','fix empty fields tos self splitaddresses(tofor (ix(namevalue)in enumerate(ext...
5,661
sendingbusy decr(try againenot on self def asksmtppassword(self)""get password if needed from gui herein main threadcaveatmay try this again in thread if no input first timeso goes into loop until input is providedsee pop paswd input logic for nonlooping alternative ""password 'while not passwordprompt ('password for %...
5,662
this may change in future python/emailsee for details changeinherits the new mailconfig fetchlimit feature of mailtoolswhich can be used to limit the maximum number of most recent headers or full mails (if no topfetched on each load requestnote that this feature is independent of the loadfrom used here to limit loads t...
5,663
don' refetch viewed msgs if hdrs list same or extendedretains cached msgs after delete unless delete fails does quick check to see if msgnums still in sync this is now subject to mailconfig fetchlimit max""if forcereloadsloadfrom self msglist [msg nums have changed elseloadfrom len(self msglist)+ continue from last loa...
5,664
if delete of all msgnums worksremove deleted entries from mail cachebut don' reload either the headers list or already viewed mails textcache list will reflect the changed msg nums on serverif delete fails for any reasoncaller should forceably reload all hdrs nextbecause _some_ server msg nums may have changedin unpred...
5,665
""############################################################################utility windows may be useful in other programs ############################################################################""from tkinter import from pp gui tools windows import popupwindow class helppopup(popupwindow)""custom toplevel that ...
5,666
""pop up blocking wait message boxthread waits main gui event thread stays alive during wait but gui is inoperable during this wait stateuses quit redef here because lowernot leftmost""def __init__(selfappnamemessage)popupwindow __init__(selfappname'busy'self protocol('wm_delete_window'lambda: ignore deletes label labe...
5,667
def wraplinessimple(lineslistsize=defaultsize)"split at fixed position sizewraplines [for line in lineslistwhile truewraplines append(line[:size]ok if len size line line[size:split without analysis if not linebreak return wraplines def wraplinessmart(lineslistsize=defaultsizedelimiters=,:\ ')"wrap at first delimiter le...
5,668
def wraplines (linessize=defaultsize)"samebut concat as one long linetext 'join(lineslines wraptext (textreturn [(line '\ 'for line in linesput them back more uniform across lines but loses original structure put together as line wrap on delimiters put newlines on ends ##################################################...
5,669
as before this is prototype because pymailgui is oriented toward plain text todaythis parser is intended as temporary workaround until html viewer/editor widget solution is found because of thatthis is at best first cut which has not been polished to any significant extent robustly parsing html in its entirety is task ...
5,670
self text '[extracted html text]self save self last 'def addtext(selfnew)if self save self text +new self last new def addeoln(selfforce=false)if force or self last !'\ 'self addtext('\ 'def handle_starttag(selftagattrs)others imply content startif tag in (' ''div''table'' '' ''li')self save + self addeoln(elif tag ='t...
5,671
to test mehtml text py media\html text-test\htmlmail html parse file name in commandlinedisplay result in tkinter text file assumed to be in unicode platform defaultbut text need not be import systkinter text open(sys argv[ ]' 'read(text html text(textt tkinter text( insert(' 'textt pack( mainloop(after this example an...
5,672
extended externally example - pp \internet\email\pymailgui\mailconfig py ""###############################################################################pymailgui user configuration settings email scripts get their server names and other email config options from this modulechange me to reflect your machine namessigan...
5,673
force programs to ask (in consoleor gui#smtpuser none smtppasswdfile 'per your isp set to 'to be asked #smtpuser popusername #(optionalpymailguiname of local one-line text file with your pop passwordif empty or file cannot be readpswd is requested when first connectingpswd not encryptedleave this empty on shared machin...
5,674
view windows can also be set interactively with texteditor' tools menusee also the setcolor py example in the gui part (ch for custom colors#listbg 'indianredlistfg 'blacklistfont ('courier' 'bold'viewbg 'light blueviewfg 'blackviewfont ('courier' 'bold'viewheight partfg partbg none'white''#rrggbbnone('courier' 'bold i...
5,675
bytesand to encode and decode message text stored in text-mode save filessee the book' for detailsthis is limited and temporary approach to unicode encodings until new bytes-friendly email package parser is provided which can handle unicode encodings more accurately on message-level basisnote'latin (an -bit encoding wh...
5,676
downloaded on each load requestgiven this setting npymailgui fetches at most of the most recently arrived mailsolder mails outside this set are not fetched from the serverbut are displayed as empty/dummy emailsif this is assigned to none (or )loads will have no such limituse this if you have very many mails in your inb...
5,677
font ('courier' 'normal'height tk default lines width tk default characters pymailguihelpuser help text and display finallyexample - lists the module that defines the text displayed in pymailgui' help pop up as one triple-quoted stringas well as function for displaying the html rendition of this text the html version o...
5,678
helpfile 'pymailguihelp htmlsee book examples package def showhtmlhelp(helpfile=helpfile)"" popup html version of help file in local web browser via webbrowserthis module is importablebut html file might not be in current working dir ""import oswebbrowser mydir os path dirname(__file__dir of this module' filename mydir...
5,679
addresses may be given in the full '"nameform payloads and headers are decoded on fetches and encoded on sends html mails show extracted plain text plus html in web browser toccand bcc receive composed mailbut no bcc header is sent if enabled in mailconfigbcc is prefilled with sender address reply and fwd automatically...
5,680
programming python th edition mark lutzfor 'reilly mediainc pymailgui is multiwindow interface for processing emailboth online and rest of file omitted altconfigsconfiguring for multiple accounts though not an "officialpart of the systemi use few additional short files to launch and test it if you have multiple email a...
5,681
from mailconfig_book import popusername 'lutz@learning-python commyaddress 'lutz@learning-python comlistbg 'wheatlistfg 'navyviewbg 'aquamarineviewfg 'blackwrapsz viewheaders none no bcc fetchlimit load more headers get base in (copied from goldenroddark greenbeige chocolatebrownexample - pp \internet\pymailgui\altconf...
5,682
setattr using class for configuration to better support customization in subclasses issuing pop-up in the gui to prompt for an account name after or before the main window appears and so on the separate subdirectory scheme used here was chosen to minimize impacts on existing code in generalto avoid changes to the exist...
5,683
also benefit from prompt for deletions if they grow too large embedded links hyperlink urls within messages could be highlighted visually and made to spawn web browser automatically when clicked by using the launcher tools we met in the gui and system parts of this book (tkinter' text widget supports links directlyhelp...
5,684
we may want to add an explicit button for opening the sent-mails file pymailgui already does save sent messages to text file automaticallywhich may be opened currently with the list window' open button franklythoughthis feature may be too-well-kept secret-- forgot about it myself when revisited the program for this edi...
5,685
source alternativessuch as the html text py same-named third-party utility described in this earlier note the open source beautifulsoup system offers another lenient and forgiving html parserbut is based on sgmlparser tools available in only (removed in xtext/html alternative mails also in the html departmentthere is p...
5,686
save to store fetched mails in text file and searching in that file externally frozen binary distribution as desktop programpymailgui seems an ideal candidate for packing as selfcontained frozen binary executableusing tools such as pyinstallerpy exeand others when distributed this wayusers need not install pythonsince ...
5,687
your mileage may vary reply and forward buttons on view windowstoominor potential ergonomic improvementwe could include reply and forward buttons on the message view windowstooinstead of requiring these operations to be selected in mail list windows only as this system' sole useri prefer the uncluttered appearance and ...
5,688
mutation as clever generalization or diabolical hack is left as an exercise in itself smtp sends may not work in some network configurationson my home/office networksmtp works fine and as shown for sending emailsbut have occasionally seen sends have issues on public networks of the sort available in hotels and airports...
5,689
python upon which pymailgui heavily depends it may be difficult for pythoncoded email clients to support some features better until python' libraries dotoo moreoverthe unicode support that is present in this program has been tested neither widely nor rigorously just like ' pyeditthis is currently still single-user syst...
5,690
we've implemented herebut they might limit further progress for examplethe current lack of an html viewer widget in the base tkinter toolkit precludes html mail viewing and composition in the gui itself moreoveralthough pymailgui broadly supports internationalization todayit must rely on workarounds to get email to wor...
5,691
server-side scripting "ohwhat tangled web we weavethis is the fourth part of our look at python internet programming in the last three we explored sockets and basic client-side programming interfaces such as ftp and email in this our main focus will be on writing server-side scripts in python-- type of program usually ...
5,692
material added in later editions of this book reflects recent technology shifts in this domain given such large and dynamic fieldthis part of the book does not even pretend to be complete look at the server-side scripting domain that isyou should not take this text to be final word on the subject to become truly profic...
5,693
use to transfer input data and results between web browsers and other clients and server-side scripts perhaps more useful way to understand cgithoughis in terms of the interaction it implies most people take this interaction for granted when browsing the web and pressing buttons in web pagesbut lot is going on behind t...
5,694
next page you see but if the url requested by the browser names an executable program instead ( url ending in cgi or py)the http server starts the named program on the server machine to process the request and redirects the incoming browser data to the spawned program' stdin input streamenvironment variablesand command...
5,695
stdin input streamalong with shell environment variables output is sent back from the server to the client by simply printing properly formatted html to the stdout output stream the most complex parts of this scheme include parsing all the input information sent up from the browser and formatting information in the rep...
5,696
deal in python objectsnot html syntaxthough you must learn this system' api as well running server-side examples like guisweb-based systems are highly interactiveand the best way to get feel for some of these examples is to test-drive them live before we get into some codelet' get set up to run the examples we're going...
5,697
today that do naturallythis may change over time running local web server to keep things simplethis edition is taking different approach all the examples will be run using simple web server coded in python itself moreoverthe web server will be run on the same local machine as the web browser client this wayall you have...
5,698
import ossys from http server import httpservercgihttprequesthandler webdir port where your html files and cgi-bin script directory live if len(sys argv webdir sys argv[ if len(sys argv port int(sys argv[ ]print('webdir "% "port % (webdirport)command-line args else default os chdir(webdirrun in html root dir srvraddr (...
5,699
server if you wish to install and run the examples under different web serveryou'll want to extrapolate the examples for your context things like server names and pathnames in urlsas well as cgi script filename extensions and other conventionscan vary widelyconsult your server' documentation for more details for this a...