Python编程第四版 Example 1-30 Example 1-31的坑
Example 1-30. PP4E\Preview\cgi101.html
<html>
<title>Interactive Page</title>
<body>
<!--原 <form method=POST action="cgi-bin/cgi101.py"> -->
<!--改 <form method=POST action="http://localhost:8081/cgi-bin/cgi101.py"> -->
<form method=POST action="http://localhost:8081/cgi-bin/cgi101.py">
<P><B>Enter your name:</B>
<P><input type=text name=user>
<P><input type=submit>
</form>
</body></html>
1.我的80口有问题,查了端口没在占用,不知道什么原因,改其他的端口ok。
Example 1-31. PP4E\Preview\cgi-bin\cgi101.py
#linux 下运行需要指定python3路径 否则出现OSError: [Errno 8] Exec format error起因和解决办法
#!/usr/bin/env python3
import cgi
import html
form = cgi.FieldStorage() # parse form data
print('Content-type: text/html\n') # hdr plus blank line
print('<title>Reply Page</title>') # html reply page
if 'user' in form:
print('<h1>Hello <i>%s</i>!</h1>' % html.escape(form['user'].value)) #module \'cgi\' has no attribute \'escape\'\r\n' 改用html.escape
# print('<h1>Hello <i>%s</i>!</h1>' % cgi.print_form(form))
else:
# print('<h1>Hello <i>%s</i>!</h1>' % cgi.escape(form['user'].value)) #module \'cgi\' has no attribute \'escape\'\r\n'
# print('<h1>Hello !</h1>' )
# print('<h1>Hello <i>%s</i>!</h1>' % html.escape(form['user'].value)) #module \'cgi\' has no attribute \'escape\'\r\n'
print('<h1>Who are you?</h1>')
1.linux 下运行需要指定python3路径,windows无需理会。
2.module ‘cgi’ has no attribute ‘escape’\r\n’ 找不到cig.escape方法改用html.escape
Example 1-32. PP4E\Preview\webserver.py
import os, sys
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir = '.' # where your html files and cgi-bin script directory live
port = 8081 # default http://localhost/, else use http://localhost:xxxx/
os.chdir(webdir) # run in HTML root dir
srvraddr = ("", port) # my hostname, portnumber
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever()
1.改服务器端口 port = 8081
测试
1.先运行webserver.py 让http服务器跑起来,如果你系统已经安装了http可以用系统自带的,改一下根目录。
2.网页打开http://localhost:8081/cgi101.html 浏览器最好使用google chrome 其他浏览器打开慢,或者打不开。
3.点击提交