Python编程(第四版) Example 1-30. PP4E\Preview\cgi101.html Example 1-31. PP4E\Preview\cgi-bin\cgi101.py

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.点击提交
运行成功

引用

用python处理html代码的转义与还原

AttributeError: module ‘cgi‘ has no attribute ‘escape‘

ubuntu环境变量和python搜索路径设置
【python】CGI部署问题解决
CGI是什么

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值