second part of 2 tom
DESCRIPTION
second part of 2 tomTRANSCRIPT
-
CGI 499
ProxyHandler ( ).
, Py thon, urllib.request - get post, . - get, URL, . - post, :
>>> from urllib.request import urlopen>>> from urllib.parse import urlencode>>> params = urlencode({'user': 'Brian'})>>> params'user=Brian'>>>>>> print(urlopen('http://localhost/cgi-bin/tutor3.py', params).read().decode())tutor3.pyGreetings
Hello, Brian.
, - cook-ies ( ), - urllib.request , - Py thon, - cookies . - , . , HTTP (HTTPS), - ( ). - Py thon. cookies -, HTTPS.
- . CGI- - . , - , - . HTML 15.9 .
15.9.PP4E\Internet\Web\tutor4.html
CGI 101
-
500 15.
A second user interaction: tables
Enter your name: Enter your age:
, , - , . , -, . 15.10. - , - - tkinter, .
.15.10.,
( Send ( -)) 15.10 , .
-
CGI 501
15.10.PP4E\Internet\Web\cgibin\tutor4.py
#!/usr/bin/python""" , , HTML;URL http://servername/cgibin/tutor4.py"""
import cgi, syssys.stderr = sys.stdout # # form = cgi.FieldStorage() # print('Contenttype: text/html\n') #
# class dummy:# def __init__(self, s): self.value = s# form = {'user': dummy('bob'), 'age':dummy('10')}
html = """tutor4.pyGreetings
%s%s%s"""
if not 'user' in form: line1 = 'Who are you?'else: line1 = 'Hello, %s.' % form['user'].value
line2 = "You're talking to a %s server." % sys.platform
line3 = ""if 'age' in form: try: line3 = "Your age squared is %d!" % (int(form['age'].value) ** 2) except: line3 = "Sorry, I can't compute %s ** 2." % form['age'].value
print(html % (line1, line2, line3))
HTML, CGI-- Py thon. , - HTML , , - . , - , . 15.11.
-
502 15.
.15.11.,tutor4.py
, CGI- URL. . 15.12 , - URL:
http://localhost/cgibin/tutor4.py?user=Joe+Blow&age=30
.15.12.,tutor4.pyURL
-
CGI 503
, ? -; &. , - , user +. URL. + . - , URL, - . 15.10 CGI, , - , - CGI. .
CGI
- , sys.platform, - age. - age int CGI . - eval. ( ) - try, .
eval , , age , , . - , , -- age , ( age URL). eval - !
CGI - , - CGI , . - , ev al exec, - , , os.popen os.system, . - , int float, , Py thon.
CGI
. - , CGI
-
504 15.
, , . - , - , CGI. 15.10 - :
sys.stderr sys.stdout, . stderr, - . , - stderr , stdout ( CGI ). , , - , .
dummy, - , , . , , - stderr, , CGI , CGI. , - . - . dummy - , form , - . form - cgi.FieldStorage. Py thon, - , .
CGI-- :
, HTML, - . , Py thon - : , python somescript.cgi - .
sys.stderrsys.stdout
- , .
-
CGI 505
, - .
CGI
, , CGI ( dummy ), .1 - , URL ( ).
CGI
CGI , - CGI . , cgi.print_form(form) -, , cgi.test() - , , . , . - .
Py thon stderr. - , - . , , - sys.exc_info() sys. , tra ce back - , . PyMailCGI ( 16).
1 CGI. 12 - , Py thon HTML, Py thon Server Pages. , - - , ( , htm.parser, Py thon - 19) , API, .
-
506 15.
CGI- - print , Py thon. , Content-type , - . - - HTML .
, - , . - , , - .
. HTML - ( - ) , . CGI, - . , - HTML CGI- Py-thon . HTML 15.11.
15.11.PP4E\Internet\Web\tutor5a.html
CGI 101
Common input devices
Please complete the following form and click Send Name: Shoe size: Small Medium Large
-
CGI 507
Occupation: Developer Manager Student Evangelist Other Political affiliations: Pythonista Perlmonger Tcler Comments: Enter text here
, . 15.13
, , , , . HTML name, , . Send ( -), 15.12, - , .
15.12.PP4E\Internet\Web\cgibin\tutor5.py
#!/usr/bin/python""" , , HTML"""
import cgi, sysform = cgi.FieldStorage() # print("Contenttype: text/html") #
-
508 15.
html = """tutor5.pyGreetings
Your name is %(name)sYou wear rather %(shoesize)s shoesYour current job: %(job)sYou program in %(language)sYou also said:%(comment)s"""
data = {}for field in ('name', 'shoesize', 'job', 'language', 'comment'): if not field in form: data[field] = '(unknown)' else: if not isinstance(form[field], list): data[field] = form[field].value else: values = [x.value for x in form[field]] data[field] = ' and '.join(values)print(html % data)
.15.13.,tutor5a.html
-
CGI 509
Py thon ; data, . :
, - in . , URL.
- , %(name)s - name .
, - , . - , - language , cgi.FieldStorage value, - value.
-, - join , and - ( , Py thon and Tcl). , - , map(lambda x: x.value, form[field]).
, FieldStorage - getfirst getlist, , - , ( Py thon). , , , - . - , - HTML , HTML. .
, , . 15.14, , , .
-
510 15.
.15.14.,tutor5.py(1)
, , , - , , - , . . CGI ( HTML) ( CGI), . HTML, - CGI . , 15.13 - , - , .
15.13.PP4E\Internet\Web\tutor5b.html
CGI 101
Common input devices: alternative layoutUse the same tutor5.py server side script, but change thelayout of the form itself. Notice the separation of user interfaceand processing logic here; the CGI script is independent of theHTML used to interact with the user/client.
Please complete the following form and click Submit
-
CGI 511
Name: Shoe size: Small Medium Large Occupation: Developer Manager Student Evangelist Other Political affiliations: Pythonista Perlmonger Tcler Comments: Enter spam here
, , . 15.15.
, HTML , , HTML, - , , - , action - URL. Submit ( ) - CGI-- Py thon tutor5.cgi ( 15.12).
, - , -. , , -, HTML , Py-thon, . . 15.16 , .
-
512 15.
.15.15.,tutor5b.html
.15.16.,tutor5.cgi(2)
-
CGI 513
, , - : , HTML -, -, . - , , , .
, - , . , - HTML . , HTML , -. , html, tutor5.py (- 15.12), .
- , , - HTML, . Py thon Ser ver Pa ges , Zope Django, , , - , , - Py thon. , , Py thon HTML CGI-- , HTML Py-thon, , Py thon . . - , , .
URL
CGI- , URL, - , ?. - - . , URL , - .
-
514 15.
, - , 15.14, ( ), tutor5.py, .
15.14.PP4E\Internet\Web\tutor5c.html
CGI 101
: URL
tutor5.py, URL ( ). View Source ( HTML), .
CGI, Python. , cgi Python ( , GET action ), POST ; CGI Python . , cgi .
, URL , , CGI, ; 'hidden' .
Send Bob, smallSend Tom, Python
Send Evangelist, spam
HTML , , (- , -). URL , . 15.17. CGI. ( - , : , .)
, . 15.18. CGI
-
CGI 515
name, Tom, language, Py-thon, - URL, HTML . - , , , , , . , URL , . 15.18.
.15.17.,tutor5c.html
, . tutor5.py , unknown . , CGI- Py thon. - - , , URL - . - CGI - , CGI.
URL, 15.14, HTML . URL CGI- , , , . -
-
516 15.
- . - , .
.15.18.,tutor5.py(3)
, , HTML . , . , - 15.15 job, name lan gu age , .
15.15.PP4E\Internet\Web\tutor5d.html
CGI 101
:
tutor5.py, , , URL . , , , CGI, ; .
-
CGI 517
, 15.15, , , . 15.19.
tutor5.py, ( 15.12), . - , . 15.20.
, , - HTML . , - . - - , CGI- . - , - . , , - .
.15.19.tutor5d.html
-
518 15.
.15.20.,tutor5.py(4)
CGI
CGI - , , - , CGI - , - , . CGI , - , , - , . - , - , .
- - CGI, , - . CGI -
-
CGI 519
, , - - . , - , ; - , -, .
, - , - , - , . , - URL- , , CGI - . - . - .
, , , , HTML, , . - , , - , , , - . - , -, , , . -, - , , .
, , , - . , URL , , -. - . - - .
-
520 15.
URL - . . , - ? , - ? - , , - . , - , HTML .
- CGI - :
URL
Cookies
, ,
CGI
,
, , - - , .
URL : - URL - , . - . - , GET.
CGI- - URL ( , - ).
-
CGI 521
- , - :
script = "onViewListLink.py"user = 'bob'mnum = 66pswd = 'xxx'site = ' pop.myisp.net'print('View %s' % (script, user, pswd, mnum, site, mnum))
URL - , :
View 66
- . . URL , - . , , , - . , , .
, , - . , , - URL, ; - , .
: - , - - , - , URL. , - , . - , - -. , , - , - .
-
522 15.
HTML- - , . :
print('' % urlroot)print('' % msgnum)print('' % user)print('' % site)print('' % pswd)
, - . , , - , - , - .
cookies ( ) - URL, -, HTML- . , - , - .
HTTP CookiesCookies, HTTP, - . - HTML - , , . cookies - .
, , , - cookies . - , cookies - , , . - , - , -, cookies.
-
CGI 523
HTTP cookies - , - HTTP. HTTP, cookies. - HTTP, cookies, . - , cookies, , HTML , HTTP. , cookies - - .
- Py thon , : - http.cookiejar HTTP cookies - , - , http.cookies - cookies . , urllib.request, , - URL cookies.
cookies
- , Firefox Internet Explorer, - , - cookies. - cookies . Cookies - HTTP :
Contenttype: text/htmlSetCookie: foo=bar;
...
Set-Cookie :
SetCookie: name=value; expires=date; path=pathname; domain=domainname; secure
domain , - cookies, path -, cookies. - , , cookies . cookies Py thon CGI cookies :
import http.cookies, timecook = http.cookies.SimpleCookie()
-
524 15.
cook['visited'] = str(time.time()) # print(cook.output()) # "SetCookie: visited=1276623053.89"print('Contenttype: text/html\n')
SimpleCookie , -, ( cookies), - Morsel ( cookies). Morsel , , - cookies: path doma in; expires, cookies ( cookies - ); . , Morsel , key value, - cookies . cookies Morsel , output cookies , - HTTP; - print __str__ . - :
>>> import http.cookies, time>>> cooks = http.cookies.SimpleCookie()>>> cooks['visited'] = time.asctime()>>> cooks['username'] = 'Bob'>>> cooks['username']['path'] = '/myscript'
>>> cooks['visited'].value'Tue Jun 15 13:35:20 2010'>>> print(cooks['visited'])SetCookie: visited="Tue Jun 15 13:35:20 2010">>> print(cooks)SetCookie: username=Bob; Path=/myscriptSetCookie: visited="Tue Jun 15 13:35:20 2010"
cookies
, cookies - HTTP, Cookie: name1=value1; name2=value2. :
Cookie: visited=1276623053.89
, cookies, . co ok ies CGI- HTTP_COOKIE, cookies, . Py thon :
import os, http.cookiescooks = http.cookies.SimpleCookie(os.environ.get("HTTP_COOKIE"))vcook = cooks.get("visited") # Morsel
-
CGI 525
if vcook != None:time = vcook.value
SimpleCookie cookies - Morsel , get None, , - cookies value Morsel.
cookies CGI
, , 15.16 CGI- , cookies - .
15.16.PP4E\Internet\Web\cgibin\cookies.py
""" , cookies ; , """
import http.cookies, oscookstr = os.environ.get("HTTP_COOKIE")cookies = http.cookies.SimpleCookie(cookstr)usercook = cookies.get("user") # ,
if usercook == None: # cookies = http.cookies.SimpleCookie() # Setcookie cookies['user'] = 'Brian' print(cookies) greeting = 'His name shall be... %s' % cookies['user']else: greeting = 'Welcome back, %s' % usercook.value
print('Contenttype: text/html\n') # print(greeting) # html
, - , - 15.1, URL http://localhost/cgibin/cookies.py ( urllib.request). cookies , - :
His name shall be... SetCookie: user=Brian
URL ( - (Reload)) :
-
526 15.
Welcome back, Brian
, cookies , , cookies - . - - .
cookies urllib.request
, urllib.request - URL - http.cookiejar cookies . - . , - cookies - cookies :
>>> from urllib.request import urlopen>>> reply = urlopen('http://localhost/cgi-bin/cookies.py').read()>>> print(reply)b'His name shall be... SetCookie: user=Brian\n'
>>> reply = urlopen('http://localhost/cgi-bin/cookies.py').read()>>> print(reply)b'His name shall be... SetCookie: user=Brian\n'
cookies cookies , -. :
>>> import urllib.request as urllib>>> opener = urllib.build_opener(urllib.HTTPCookieProcessor())>>> urllib.install_opener(opener)>>>>>> reply = urllib.urlopen('http://localhost/cgi-bin/cookies.py').read()>>> print(reply)b'His name shall be... SetCookie: user=Brian\n'
>>> reply = urllib.urlopen('http://localhost/cgi-bin/cookies.py').read()>>> print(reply)b'Welcome back, Brian\n'
>>> reply = urllib.urlopen('http://localhost/cgi-bin/cookies.py').read()>>> print(reply)b'Welcome back, Brian\n'
-
CGI 527
, urllib.request - - cookies cookies, , - , . , , , cookies Py thon . - .
, cookies . - , ( : 4 cookies, 300 cookies 20 cookies ). - , - cookies, . , , - . ( , cookies , - .) , cookies , , , - HTTP. cookies .
, cookies, cookies - Py thon . , HTML.
Py thon , . - 17. Py thon - , -, , - , - ZODB, SQL, MySQL, PostgreSQL, Oracle SQLite. , - , .
- . -
-
528 15.
( , ) - ( , ).
, , CGI- - - , . - - , , , .
. , - . , cookies. - , , cookies.
, , - . , 17, Py thon . , Py thon - , - , .
CGI , - , - , . , Zope - , - 12, , - - , .
, FastCGI, - , mod_python Apache, - CGI- - CGI - . :
FastCGI - , - - HTTP - (Inter- Process Communication, IPC), . - CGI,
-
CGI 529
, - - . FastCGI , , - - .
mod_python - Apache, - Py thon Apache. Py thon Apache, - . - , . - , , , Apa che - . mod_python - , Py thon Ser ver Pages (PSP) HTML, 12 .
, . , - , FastCGI, , , - , , . - CGI Py-thon , FastCGI, - .
, - - . :
- cookies - .
, , URL - , - , - .
, , ,
-
530 15.
URL , , , cookies .
. , , - , - , - CGI .
Hello World . - , , ( ). , - -, Hello World, - .
, - , - . , , . Py thon - , - .
HTML CGI- Py thon, HTML. - - - , . HTML, 15.17, - , .
15.17.PP4E\Internet\Web\languages.html
Languages
Hello World selector
, "hello world" . ( , ) , ( HTML). HTML; , , CGI Python, . :
-
Hello World 531
HTML , 'View Source' (' ' ' HTML') . Python CGI, , . , , .
Select a programming language: All Python Python2 Perl Tcl Scheme SmallTalk Java C C++ Basic Fortran Pascal Other
- , , - . HTML - , . 15.21.
Submit Query ( ) - , HTML. , Submit Query ( ) ( Enter), - CGI , action . - 15.18 Py thon, - .
-
532 15.
.15.21.HelloWorld
15.18.PP4E\Internet\Web\cgibin\languages.py
#!/usr/bin/python""" 'hello world' ; , "" r'...', '\n' , cgi.escape(), , '
-
Hello World 533
'Java': r' System.out.println("Hello World"); ', 'C': r' printf("Hello World\n"); ', 'C++': r' cout
-
534 15.
Py thon HTML \n. , - , Py thon.
,HTMLURL
- - cgi.escape. Py thon - HTML - HTML, - HTML. cgi.escape - HTML: & &. True , (") ".
,
-
Hello World 535
,
( ) , . debugme True, , , cgi.FieldStorage - dummy. , , , cgi.FieldStorage, -, value .
, - : , . - , All, - , - ( ).
showHello . Py thon, - , . showHello , - form['language'].value.1 . , - , showHello , - .
. - , CGI - HTML, ( Con-tent-type ). View Source ( HTML- ) , :
LanguagesSyntaxScheme
1 , ( tutor4.py ). , dummy - , . . - - .
-
536 15.
(display "Hello World") (newline)
, - ( ). , Scheme. . 15.22 , Py thon ( -, , Py thon 3.X).
.15.22.,languages.py
All - - . , HTML, , True debugme All. , All1:
C:\...\PP4E\Internet\Web\cgibin> python languages.py AllContenttype: text/html
1 , All, False debugme . CGI cgi.FieldStorage , , - . .
-
Hello World 537
LanguagesSyntaxC printf("Hello World\n");
Java System.out.println("Hello World");
C++ cout > from urllib.request import urlopen>>> request = 'http://localhost/cgi-bin/languages.py?language=Python'>>> reply = urlopen(request).read()>>> print(reply.decode())LanguagesSyntaxPython print('Hello World')
, - , CGI. -, HTML, - GuiDO ( -, View Source ( HTML- ) , URL ):
>>> request = 'http://localhost/cgi-bin/languages.py?language=GuiDO'>>> reply = urlopen(request).read()>>> print(reply.decode())LanguagesSyntaxGuiDOSorryI don't know that language
, All ( -, URL ?language= ):
>>> reply = urlopen('http://localhost/cgi-bin/languages.py').read()>>> print(reply.decode())LanguagesSyntaxC printf("Hello World\n");
Java System.out.println("Hello World");
C++ cout import cgi, html.parser>>> s = cgi.escape("1
-
HTML URL 555
>>> s'1>> urllib.parse.quote_plus("uploads/index.txt")'uploads%2Findex.txt'>>> urllib.parse.quote("uploads/index.txt")'uploads/index.txt'>>>>>> urllib.parse.quote_plus("uploads/index.txt", '/')'uploads/index.txt'>>> urllib.parse.quote("uploads/index.txt", '/')'uploads/index.txt'>>> urllib.parse.quote("uploads/index.txt", '')'uploads%2Findex.txt'>>>>>> urllib.parse.quote_plus("uploads\index.txt")'uploads%5Cindex.txt'>>> urllib.parse.quote("uploads\index.txt")'uploads%5Cindex.txt'>>> urllib.parse.quote_plus("uploads\index.txt", '\\')'uploads\\index.txt'
, Py thon cgi - URL + . cgi.FieldStorage - urllib.parse , URL. CGI , URL, . , CGI , - URL.
URL, HTML
, , HTML URL. URL HTML? , , - URL, HTML? - , - URL, . , languages2.py HTML, URL:
URL HTML, , ,
-
HTML URL 557
HTML ( , < - > from html.parser import HTMLParser>>> html = open('test-escapes.html').read()>>> HTMLParser().unescape(html)'\nhello\n'
? , , &, - HTML:
hello
Py thon ( testescapes2.html, ), - HTML - :
file.py?name=a&job=b&=c§=d<=e IEChrome
>>> h = 'hello'>>> HTMLParser().unescape(h)'hello'
- HTML URL ( Py thon urlib.parse, cgi) - & . , , - , URL, HTML ( - ;):
file.py?name=a;job=b;amp=c;sect=d;lt=e
-
HTML URL 559
- Py thon html.parser , , HTML. , HTML, , URL http://localhost/badlink.html, - , . HTML, - 15.24, .
15.24.PP4E\Internet\Web\badlink.html
unescaped
escaped
alternative
- CGI, 15.25. , , , - ( - 15.1 ).
15.25.PP4E\Internet\Web\cgibin\badlink.py
import cgi, sysform = cgi.FieldStorage() # # stderr; stodout=reply pagefor name in form.keys(): print('[%s:%s]' % (name, form[name].value), end=' ', file=sys.stderr)
( , ) , - HTML - Internet Explorer. - HTML URL, HTML - - HTML , -
-
560 15.
( Chrome , , ASCII, - ):
markVAIO [16/Jun/2010 10:43:24] b'[:c\xa7=d
-
561
( !) HTML URL, , - HTML URL , Py thon. ( , Py thon - - .) , - , - , - .
, , , - , , Py thon . - , , - HTML URL , , Py thon - . - HTML URL. , - - , Zope -, - , CGI. , , .
HTML, - . , - CGI ( )? , - CGI - HTML, - . 15.26, - language.html, , - HTML. cgi.escape HTML.
-
562 15.
15.26.PP4E\Internet\Web\cgibin\languagessrc.py
#!/usr/bin/python" languages.py ."
import cgifilename = 'cgibin/languages.py'
print('Contenttype: text/html\n') # HTMLprint('Languages')print("Source code: '%s'" % filename)print('')print(cgi.escape(open(filename).read())) # print('') #
- , Windows, filename ( - cgibin - ). - , 15.17 URL -, , CGI. . 15.27.
.15.27.
-
563
, - cgi.escape, - HTML . , , - HTML, HTML. , C++ < , . cgi.escape >> import os>>> os.path.samefileAttributeError: 'module' object has no attribute 'samefile'>>> os.getcwd()'C:\\...\\PP4E\\dev\\Examples\\PP4E\\Internet\\Web'>>>>>> x = os.path.abspath('../Web/PYMailCgi/cgi-bin/secret.py').lower()>>> y = os.path.abspath('PyMailCgi/cgi-bin/secret.py').lower()>>> z = os.path.abspath('./PYMailCGI/cgi-bin/../cgi-bin/SECRET.py').lower()>>> x'c:\\...\\dev\\examples\\pp4e\\internet\\web\\pymailcgi\\cgibin\\secret.py'>>> y'c:\\...\\dev\\examples\\pp4e\\internet\\web\\pymailcgi\\cgibin\\secret.py'>>> z'c:\\...\\dev\\examples\\pp4e\\internet\\web\\pymailcgi\\cgibin\\secret.py'>>>>>> x == y, y == z(True, True)
, . 15.31. -, - , , . , - .
.15.31.
, - . - , , - , (
-
571
sys.exc_info), . . 15.32 .
.15.32.
- , , - . - (- sys.stderr sys.stdout , -). , - sys .
getfile.py, - ! , , Windows. - , - , , - . , -, .
getfile , - , - . , FTP - , . - View Source ( HTML- ).
-
572 15.
, , getfi le urllib, Py thon, - HTML.
? , , - - , - . - , - - PyMailCGI, .
13 , , Py thon FTP. - - - Py thon FTP , - . , - , FTP ( ). - , , .
- , ? , HTML, Py-thon. HTML type=file, - , - . , , - . , 15.29 - HTML, , action .
15.29.PP4E\Internet\Web\putfile.html
Putfile: upload page
Select client file to be uploaded
View script code
-
573
: , file, multipart/formdata post, . URL - get . - HTML , . 15.33. Browse ( ) , - Upload ( ) .
.15.33.
Upload ( ), , - ( ). , Py thon, action - 15.30.
15.30.PP4E\Internet\Web\cgibin\putfile.py
#!/usr/bin/python"""############################################################################ , HTTP; putfile.html, , ; : ; , : Unix 'chmod 777 uploads' ; : ;
: , ,
-
574 15.
, cgi str, cgi 3.1 ;############################################################################"""
import cgi, os, sysimport posixpath, ntpath, macpath # debugmode = False # True= loadtextauto = False # True= uploaddir = './uploads' #
sys.stderr = sys.stdout # form = cgi.FieldStorage() # print("Contenttype: text/html\n") # if debugmode: cgi.print_form(form) #
# html
html = """Putfile response page
Putfile response page%s"""
goodhtml = html % """Your file, '%s', has been saved on the server as '%s'.An echo of the file's contents received and saved appears below.
%s
"""
#
def splitpath(origpath): # for pathmodule in [posixpath, ntpath, macpath]: # basename = pathmodule.split(origpath)[1] # if basename != origpath: return basename # return origpath #
def saveonserver(fileinfo): # data basename = splitpath(fileinfo.filename) # srvrname = os.path.join(uploaddir, basename) # , srvrfile = open(srvrname, 'wb') # if loadtextauto: filetext = fileinfo.value # if isinstance(filetext, str): # Python 3.1 filedata = filetext.encode()
-
575
srvrfile.write(filedata) # else: # numlines, filetext = 0, '' # . while True: # str line = fileinfo.file.readline() # for if not line: break if isinstance(line, str): # Python 3.1 line = line.encode() srvrfile.write(line) filetext += line.decode() # numlines += 1 filetext = ('[Lines=%d]\n' % numlines) + filetext srvrfile.close() os.chmod(srvrname, 0o666) # : 'nobody' return filetext, srvrname
def main(): if not 'clientfile' in form: print(html % 'Error: no file was received') elif not form['clientfile'].filename: print(html % 'Error: filename is missing') else: fileinfo = form['clientfile'] try: filetext, srvrname = saveonserver(fileinfo) except: errmsg = 'Error%s%s' % tuple(sys.exc_info()[:2]) print(html % errmsg) else: print(goodhtml % (cgi.escape(fileinfo.filename), cgi.escape(srvrname), cgi.escape(filetext)))main()
- , Py thon. - : , - cgi.FieldStorage , ; clientfile, - name HTML.
- . , - value . , ( - ). Py thon cgi - - . , , .
-
576 15.
: - loadtextauto - , . , CGI :
filename
,
file
, -,
value
( file)
, - . . , value , .
CGI ( - nobody) , , , . , - , uploaddir. Linux - chmod 777 ( / / ), -. - , , - , , , , .
os.chmod, - , . - , no-bo dy, . Linux nobody, , - ( - ).
, , : . -
-
577
- ; , . , , .
, CGI, - , , . 15.34. , - , .
.15.34.putfile
, , . , - , cgi - str, bytes. - , 3.1 cgi - ( ).
, , - ( fc Windows, ). , getfile, .
-
578 15.
, . 15.35.
.15.35.putfilegetfile
, - , . 15.36. - nobody ( CGI) , nobody .
.15.36.putfilegetfile
-
579
URL : /, - , %2F , URL . URL . -, , urllib.parse.
%2F URL , - ASCII, , -. +. , - ASCII, ( URL). , , , URL (- , &), urllib.parse.
,
putfile.py uploaddir , ( - ). , , , - splitpath - . - , - . , , CGI. - , , .
, - os.path.split, , - , -, . , - CGI Unix, os.path.split /. - DOS Windows, \, /. , Mac-intosh, .
-, Py thon , , - ,
-
580 15.
. , posixpath , - Unix, ntpath DOS Windows. , os.path.split - , , ; - , . , - , - split:
def splitpath(origpath): # basename = os.path.split(origpath)[1] # if basename == origpath: # ? if '\\' in origpath: basename = origpath.split('\\')[1] # DOS elif '/' in origpath: basename = origpath.split('/')[1] # Unix return basename
( , DOS , - ). - , ( - ), .
, , , - :
- , putfile , -. , , DOS, , , .
- , -, . wb, - , , , . 4. Py thon 3.1, - ( - CGI 3.1). , , .
- , , - .
-
581
CGI 3.1
, , CGI, , Py thon 3.1. , cgi , . - , - , . CGI Py thon 2.X , , 3.X .
, cgi , - email, , , -, email, - 13. email - str, - CGI, - . 13, CGI , MIME, - . - email str , , , - cgi .
, - , - HTML Py thon testcgiuuploadsbug*, , , :
testcgiuploadsbug.html/py - , ,
testcgiuploadsbug0.html/py , - , , , , - , email str
-
582 15.
testcgiuploadsbug1.html/py -
testcgiuploadsbug.html/py -
- - , - , ( multipart/form-data ). - cgi , - . , - , - - , - - .
, -, , , , Py thon 3.3 -. 3.0 - - , . , str/bytes Py-thon 3.X - Py thon . , , , - 3.X. , , , 0.X, .
cgi - email . - CGI, - , . - , - PyMailCGI, - , , - , PyMailGUI . - , .
-
583
, , , , - ( -). , , - , - -, , - . ( )
- . getfile. , , - , , :
getfile CGI, - HTTP ( 80).
12 getfile - ( 50001).
13 getfile, - , FTP ( 21).
CGI- getfile, , , , - . , putfile , CGI HTTP, putfile 13, - FTP, - , FTP.
, , FTP HTTP (- ); - . , - POP, NNTP, Telnet .
, : . , , , , FTP HTTP, -, , CGI, , .
- ,
-
584 15.
, PyMailCGI, - , - , - . , , - .
CGI:
15.27 getfile.py CGI- Py thon, - ( ) , , - . - Content-type text/plain text/html. getfile.py - CGI- , .
, , getfile.py - , - CGI. - CGI ( , - - ), - , Content-type CGI.
, ( , xxx.jpg - ) Content-type ( , text/html HTML). MIME , - . , application/octetstream Content-type .
, - , - / , , . , Py-thon CGI CGI down-load.
-
16 16. PyMailCGI
- - Py thon. , 15. CGI- Py-thon. , - , CGI.
PyMailCGI - - , - , , URL -. PyMailGUI, - 14, -- . CGI -, - , 15.
, - , Py-thon. , - , -. CGI : PyMailCGI , .
, , , ( -, PyMailCGI - ). ,
-
586 16. PyMailCGI
, . , - , CGI , - Py thon, . , , , , . , Py-thon, .
- PyMailCGI 14 PyMailGUI, Py thon+tkinter - ( , ). , : PyMailCGI CGI, - - . - - , - (ISP), - .
, CGI, , - Py thon , , - - (PyMailCGI) - , (PyMailGUI). , - .
PyMailCGI - POP SMTP. , . PyMailCGI , , , PyMailCGI (- , ).
, - . -
-
- PyMailCGI 587
, - CGI HTML. - Py Ma ilCGI - ( - ). CGI - , .
, PyMailCGI , . - ; cookies, - , . , - - .
, PyMailCGI , , 16.1. - - . , - - , - ( , ), - .
16.1.PP4E\Internet\Web\PyMailCgi\pageflow.txt
[pymailcgi.html] => [onRootViewLink.py] => [onViewPswdSubmit.py] ( ) => [onViewListLink.py] +=del|reply|fwd () => [onViewPageAction.py] + (del) => [onEditPageSend.py] ( ) => => [onRootSendLink.py] => [onEditPageSend.py] ( ) =>
, => - .
-
588 16. PyMailCGI
, pymailcgi.html - onRootViewLink.py onRootSendLink.py. onRootViewLink.py , Submit ( ) onViewPswdSubmit.py . - , , , - onSendSubmit.py - , .
CGI , - . , . - . 16.1, - Cygwin Win-dows.
.16.1.PyMailCgi
, , - PyMailCgi, - - . HTML CGI, - , PyMailCGI :
commonhtml.py
HTML.
externs.py
, -.
-
- PyMailCGI 589
loadmail.py
- .
secret.py
.
PyMailCGI mailtools mailconfig.py, 13. - PP4E , - , PyMailCgi, PyMailGUI PyMailCGI -. externs.py - , , - .
- . - mailtools, - 13, , , , , , , - PyMailGUI. PyMailCGI, , , -. mailtools 13.
, PyMailCGI Py thon: smtplib, poplib, email.*, cgi, urllib.* . - . PyMailCGI 846 , -, HTML ( linecounts.xls, ; - 835 ).
PyMailGUI 14, - - PyMailCGI - , - , - , , - , . , -
-
590 16. PyMailCGI
, PyMailCGI - , , , - - Py thon 3.1.
, PyMailCGI - , -- , - . PyMailGUI - . , - PyMailCGI - - .
( 3.0) - PyMailCGI Py thon 3.X. , - , mailtools, , , . - - :
- , MIME -, .
- , - , UTF-8.
, - , - .
, - . meta HTML, . , - HTML , :
-
- PyMailCGI 591
. , - - , -, HTML. , - Subject From - ( , ), - ( UTF-8). , - , , -, , - . PyMailGUI - , Text - tkinter, - . PyMailCGI , .
, , , - , , ; - . - , - CGI, . - , , Py thon 3.1 - CGI, stdout bytes ( ).
/i18n , PyMailGUI. , , , - , - - .
, 3.0, - , , - 3.0. , - , . - .
-
592 16. PyMailCGI
( )
, - CGI 3.1 - . , cgi Py thon 3.1, email, - . , PyMailCGI, - , CGI, , -, . , Py thon 2.X.
- PyMailGUI, 14, , ( , , MIME ). , - PyMailCGI, , , CGI, , cgi. - cgi .
, , . PyMailCGI , Py thon 3.1, - , . , , PyMailCGI mailtools, - , - - - PyMailGUI . , , .
-
- PyMailCGI 593
, - AJAX, CGI. - , , , , Py-thon 3.X. (PyMail RIA?), CGI Py thon 3.X.
( 2.0) - PyMailCGI - mailtools, 13; - PyCrypto ; - - . - 3.0.
-, , - , . - , - - mailtools:
- . - , . - , .
, - 15. , - . -, , - , - - mailtools. , 3.0 - , HTML, .
-
594 16. PyMailCGI
- , , PyMailCGI ( ) , . , , - - . - , - , - , .
PyMailCGI . - - . - , - . , , - , mailtools , ( , , ).
- , - ( 14, ). , - , - . , , , PyMail-GUI 14.
- - CGI . , - , , - ( , , -), cookies, URL. - - - , - . - , .
-
- PyMailCGI 595
- , ( , , , - ).
, PyMailCGI, ( -, commonhtml.py). , - CGI, , . , - , . - , , , - .
, : , . - , - - , , HTML CGI- Py thon , . - , , , . -, , , , .
, , . Py-Ma ilGUI 14, , - , . - - , . , , , Py thon - . Py-thon , Py thon, .
HTML CGI- , PyMailCGI, - , . , 15, webserver.py - , -
-
596 16. PyMailCGI
15.1, - . , , - urllib.request local-host ( IP- 127.0.0.1).
, - . , - , , - - , .
: PyMailCGI , webserver.py. - , :
C:\...\PP4E\Internet\Web> webserver.py PyMailCgi 8000
Windows - Unix- . -- localhost, 8000. - PyMailCgi, -, CGI, PyMailCgi\cgibin. , - , .
: - , - , , , - - 80, , 8000. , - , . , , URL :
http://localhost/languages.htmlhttp://localhost/cgibin/languages.py?language=All
- URL :
http://localhost:8000/pymailcgi.htmlhttp://localhost:8000/cgibin/onRootSendLink.py
-
- PyMailCGI 597
, - , - . , , , 12 - URL 15.
, localhost: 8000/cgi-bin URL, , , . , PyMailCGI, , , - - .1
PyMailGUI, - mailconfig.py, . , - , - .
PyMailCGI CGI , - . - - OHare ( , -). - Py thon. , - - , - .
1 - webserver.py, - , , , CGI , , - - . CGI : . Windows , - CGI , . - , - CGI , - ; - .
-
598 16. PyMailCGI
, - . , PyMailCGI PyMailGUI 14 - , , , . .
- . - - - , , - , - 17. PyMailCGI PyMailGUI, . , Py thon 3.1 - , .
, , -, . , , , . , , , - Py thon, - .
. , - 16.2, - . HTML, - .
16.2.PP4E\Internet\Web\PyMailCgi\pymailcgi.html
PyMailCGI Main Page
PyMailCGIA POP/SMTP Web Email Interface
-
599
Version 3.0 June 2010 (2.0 January 2006)
Actions
, , , SMTP
POP/SMTP. , , . PyMailCgi CGI Python, ( ) HTML . Python, 4e .
: PyMailCgi 1.0 2 O'Hare. , PyMailGUI (, , , , ). , PyMailCgi Python ( Tk) .
, , PyMailCgi . , .
2: PyMailCGI , .
-
600 16. PyMailCGI
, .
3: PyMailCGI Python 3.X () mailtools: , . cgi email Python 3.1 3.0 , ( 15 16).
:
PyMailGUI Internet, Python+Tk pymail.py Email, Python imaplib, IMAP POP
[Book][O'Reilly]
pymailcgi.html - PyMailCgi, - . - , , URL ( , - - ):
http://localhost:8000/pymailcgi.html
, , . 16.2 - Google Chrome Windows 7. Internet Explorer Chrome , , - . , , , HTML CGI- Py thon.
-
601
.16.2.PyMailCGI
PyMailCGI , View, ... ( , ...), - . 16.2, , , PyMailCGI - , Send... ( ...) ( , SMTP ). - URL - .
, , - . , , - . , , - , , - .
, - , , [email protected] - POP. ( , - !), PyMailCGI , - . ,
-
602 16. PyMailCGI
mailconfig.py, - . . , - , , .
SMTPPyMailCGI - : - . ( View...) , - , , - . , .
( Send...) : - . Send... , . 16.2, - CGI, 16.3.
16.3.PP4E\Internet\Web\PyMailCgi\cgibin\onRootSendLink.py
#!/usr/bin/python"""############################################################################ 'send' : ############################################################################"""
import commonhtmlfrom externs import mailconfig
commonhtml.editpage(kind='Write', headers={'From': mailconfig.myaddress})
, . , commonhtml externs. , - editpage, myaddress From.
- , - , . , . - , . 16.3.
-
SMTP 603
.16.3.PyMailCGI()
- - ( From mailconfig, - ). Choose File ( ) , - . PyMailGUI 14, . , - , - .
, HTML , - . 16.3, - . - Send ( ), , 16.4, .
-
604 16. PyMailCGI
16.4.PP4E\Internet\Web\PyMailCgi\cgibin\onEditPageSend.py
#!/usr/bin/python"""############################################################################ : , ;
2.0+: mailtools , ; MIME;
3.0: CGI cgi py3.1, ( , cgi, ); 3.0: , ;############################################################################"""
import cgi, sys, commonhtml, osfrom externs import mailtools
savedir = 'partsupload'if not os.path.exists(savedir): os.mkdir(savedir)
def saveAttachments(form, maxattach=3, savedir=savedir): """ , mailtools ; FieldStorage 3.1 cgi , , ; """ partnames = [] for i in range(1, maxattach+1): fieldname = 'attach%d' % i if fieldname in form and form[fieldname].filename: fileinfo = form[fieldname] # ? filedata = fileinfo.value # filename = fileinfo.filename # if '\\' in filename: basename = filename.split('\\')[1] # DOS elif '/' in filename: basename = filename.split('/')[1] # Unix else: basename = filename # ,
-
SMTP 605
pathname = os.path.join(savedir, basename) if isinstance(filedata, str): # 3.0: rb bytes filedata = filedata.encode() # 3.0: . ? savefile = open(pathname, 'wb') savefile.write(filedata) # with savefile.close() # EIBTI1 os.chmod(pathname, 0o666) # . . partnames.append(pathname) # return partnames #
#commonhtml.dumpstatepage(0)form = cgi.FieldStorage() # attaches = saveAttachments(form) # cgi.print_form(form),
# URL, GETsmtpservername = commonhtml.getstandardsmtpfields(form)
# , URLfrom 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 = ''
# 3.0: ascii utf8 mailtools parser = mailtools.MailParser()Tos = parser.splitAddresses(To) # : ','Ccs = (Cc and parser.splitAddresses(Cc)) or ''extraHdrs = [('Cc', Ccs), ('XMailer', 'PyMailCGI 3.0')]
# 3.0: ; # =ascii mailtoolsbodyencoding = 'ascii'try: text.encode(bodyencoding) # ascii ( latin1?)except (UnicodeError, LookupError): # . utf8 ( ?) bodyencoding = 'utf8' # : # , PyMailGUI
# 3.0: utf8 ; # attachencodings = ['utf8'] * len(attaches) # #
# sender = mailtools.SilentMailSender(smtpservername)
1 Explicit Is Better Than Implicit ( -) Py thon. ..
-
606 16. PyMailCGI
try: sender.sendMessage(From, Tos, Subj, extraHdrs, text, attaches, bodytextEncoding=bodyencoding, attachesEncodings=attachencodings)except: commonhtml.errorpage('Send mail error')else: commonhtml.confirmationpage('Send mail')
( - URL) - Py thon smtplib mailtools. - mailtools 13, . , - - sentmail.txt PyMailCGI - , .
2.0 saveAttachments -, , . , , - . - CGI 15 , ( - Py thon 3.1 - ). - mailtools .
commonhtml SMTP, - , mailconfig - ( URL). , , . 16.4.
sentmail.txt PyMailCGI, , ( -, PyMailGUI). - UTF-8 MIME Base64, - ASCII, .
, . - . , PyMailGUI,
-
SMTP 607
, , - , , , .
.16.4.PyMailCGI
, , - : 13, SMTP -, SMTP, - . , SMTP - Py thon ( , ), , , . mailtools - , .
, , . 16.5. , - , , traceback . - , , .
, commonhtml - , , PyMailCGI , , . , commonhtml, ( - ).
-
608 16. PyMailCGI
.16.5.PyMailCGI
commonhtml - , . , : - , - - , Py thon . - commonhtml, , ( HTML).
, - - commonhtml, . , , 16.14. , - .
-
SMTP 609
PyMail-CGI , . , , - URL; CGI, mailconfig, - . , URL ( - ):
http://localhost:8000/cgibin/ onEditPageSend.py?site=smtp.rmi.net& [email protected]& [email protected]& Subject=test+url& text=Hello+Mark;this+is+Mark
- , URL. , URL - , . 13 15, urllib.request URL - Py thon. 16.5 - .
16.5.PP4E\Internet\Web\PyMailCgi\sendurl.py
"""#################################################################### , URL :http://servername/pathname/ onEditPageSend.py?site=smtp.rmi.net& [email protected]& [email protected]& Subject=test+url& text=Hello+Mark;this+is+Mark####################################################################"""
from urllib.request import urlopenfrom urllib.parse import quote_plus
url = 'http://localhost:8000/cgibin/onEditPageSend.py'url += '?site=%s' % quote_plus(input('Site>'))url += '&From=%s' % quote_plus(input('From>'))url += '&To=%s' % quote_plus(input('To >'))url += '&Subject=%s' % quote_plus(input('Subj>'))url += '&text=%s' % quote_plus(input('text>')) #
-
610 16. PyMailCGI
print('Reply html:')print(urlopen(url).read().decode()) # #
, CGI , - . sendurl.py , Py thon , - Py thon, . HTML, - CGI:
C:\...\PP4E\Internet\Web\PyMailCgi> sendurl.pySite>smtpout.secureserver.netFrom>[email protected] >[email protected]>testing sendurl.pytext>But sir, it's only wafer-thin...Reply html:PyMailCGI: Confirmation page (PP4E)PyMailCGI ConfirmationSend mail operation was successfulPress the link below to return to the main page.
Back to root page
HTML, , - , . , , ( , - successful find - in ), Py thon html.parse re ( 19) . , - PyMailGUI 14, - . 16.6 ( ).
, , - . , Py thon smtplib ( mailtools) - SMTP, - CGI ( - , CGI SMTP). CGI - URL, , HTML
-
POP 611
mailto:, urllib.request - - . , - sendurl.py , - .
.16.6.sendurl.py
POP , . , POP.
POP , . 16.2, View..., -, 16.6:
16.6.PP4E\Internet\Web\PyMailCgi\cgibin\onRootViewLink.py
#!/usr/bin/python"""############################################################################ View... HTML: ;
HTML, ,
-
612 16. PyMailCGI
, ; , URL , , ;############################################################################"""
# pswdhtml = """
"%s" POP "%s".
, : , , , , : ( ), ( cookies). , ; PyMailCGI "" ("Back") ."""
# import commonhtml # :user, pswd, site = commonhtml.getstandardpopfields({}) # ,commonhtml.pageheader(kind='POP password input') # html|urlprint(pswdhtml % (commonhtml.urlroot, user, site))commonhtml.pagefooter()
HTML: - pswdhtml - , , . , - , , - HTML. commonhtml ( , URL ) mail config , HTML, HTML -. CGI Py thon HTML -, ( , PSP, , -, HTML Py thon, - ).
-
POP 613
, commonhtml, - , . 16.7.
.16.7.PyMailCGI
, - POP. , ; - HTML type=password, , - . ( pymail 13, , PyMail GUI 14, tkinter.)
Submit ( ) , - 16.7.
16.7.PP4E\Internet\Web\PyMailCgi\cgibin\onViewPswdSubmit.py
#!/usr/bin/python"""############################################################################ POP : ;
2.0+ , , , ;
-
614 16. PyMailCGI
, : (?) ; 3.0: , ;############################################################################"""
import cgiimport loadmail, commonhtmlfrom externs import mailtoolsfrom secret import encode # , MaxHdr = 35 #
# , formdata = cgi.FieldStorage()mailuser, mailpswd, mailsite = commonhtml.getstandardpopfields(formdata)parser = mailtools.MailParser()
try: newmails = loadmail.loadmailhdrs(mailsite, mailuser, mailpswd) mailnum = 1 maillist = [] # . enumerate() for mail in newmails: # msginfo = [] hdrs = parser.parseHeaders(mail) # email.message.Message addrhdrs = ('From', 'To', 'Cc', 'Bcc') # for key in ('Subject', 'From', 'Date'): rawhdr = hdrs.get(key, '?') if key not in addrhdrs: dechdr = parser.decodeHeader(rawhdr) # 3.0: . # else: # . dechdr = parser.decodeAddrHeader(rawhdr) # msginfo.append(dechdr[:MaxHdr]) msginfo = ' | '.join(msginfo) maillist.append((msginfo, commonhtml.urlroot + 'onViewListLink.py', {'mnum': mailnum, 'user': mailuser, # 'pswd': encode(mailpswd), # 'site': mailsite})) # URL, # mailnum += 1 commonhtml.listpage(maillist, 'mail selection list')except: commonhtml.errorpage('Error loading mail index')
-
POP 615
, ( - URL). , :
loadmail.loadmailhdrs
mailtools 13 - POP. - . , , , ( TOP POP, , , mailconfig, ).
commonhtml.listpage
HTML (, _URL, _) . URL .
maillist -. URL, , . , - .
, HTML - , . 16.8. , , , , , . - commonhtml , PyMailCGI.
- ( , - ), - try .
. 16.9 , - Py thon - . , - sys.exc_info, - Py thon traceback.
-
616 16. PyMailCGI
.16.8.PyMailCGI,
.16.9.PyMailCGI
-
POP 617
URL-
, 16.7, - URL, . View ( ) , URL- -. 15, - , , , . . 16.10 HTML, - ( , - View Source ( HTML- ) - , Save As ( ) - Inter net Exp lorer).
.16.10.HTML,PyMailCGI
. 16.10? HTML, . - - , - , :
ViewAmong our weapons are these | [email protected] | Fri, 07 May 2010 20:32...
-
618 16. PyMailCGI
PyMailCGI URL ( , commonhtml). View , HTML, - onViewListLink, , URL: POP, POP , , POP . , , - , cgi.FieldStorage. , POP mnum - , - , mailtools, - email.
commonhtml - urllib.parse, cgi.escape, - URL. pswd , urllib.parse URL ( - %xx). , URL . - , cgi.FieldStorage - URL, - %.
, commonhtml - . , urllib.parse.quote_plus - URL:
>>> import urllib.parse>>> urllib.parse.quote_plus("There's bugger all down here on Earth")'There%27s+bugger+all+down+here+on+Earth'
commonhtml urllib.parse.urlencode , , :-, , - URL ?. urlencode :
>>> parmdict = {'user': 'Brian',... 'pswd': '#!/spam',... 'text': 'Say no more, squire!'}>>> urllib.parse.urlencode(parmdict)'text=Say+no+more%2C+squire%21&pswd=%23%21%2Fspam&user=Brian'
-
POP 619
>>> "%s?%s" % ("http://scriptname.py", urllib.parse.urlencode(parmdict))'http://scriptname.py?text=Say+no+more%2C+squire%21&pswd=%23%21%2Fspam&user=Brian'
urlencode str ( ), , - , urllib.parse.quote_plus. CGI - commonhtml - .1
URL ( , - 15). - , - .
, - , PyMailGUI 14, - . . 16.11 , - , . 16.8, .
, PyMailGUI HTML , - tkinter. , POP . - - , PyMailGUI - . - - . , , , - , . Py Ma il GUI , , .
1 & URL cgi.escape, -- ( , &=high) - HTML. 15; , URL HTML.
-
620 16. PyMailCGI
.16.11.PyMailGUI
, PyMailCGI - - POP - , CGI. - - CGI PyMailCGI - , - . , - .
, onViewPswdSubmit ( 16.7) encode, URL . ( %, - ) - POP. - encode PyMail CGI.
Py thon ssl, - (Secure Sockets Layer, SSL) - - , . , . , -
-
POP 621
, , secret.py ( 16.13), - PyMailCGI. , - , Py thon , - HTTPS HTTP. - , - .
. , : , - . mailconfig, , - , - .
, URL , secret.encode , , , PyMailCGI. PyMailCGI - , , - , . - , -, , .
PyMailCGI , - . - ( ), - .