cgi简述
cgi就是公共网关皆苦, 具体的就是服务端和浏览器交互的接口模块,cgitb则用于输出对应的报错信息
可以使用Python自带的服务器运行,也可以使用Apache等服务进行交互
注意事项
服务端代码,第一行务必为 #!PythonPath/python.exe
Python 服务器动态网页
01目录设置:
在Python安装目录新增文件夹cgi-bin, 这里存放服务端代码文件hello.py
#!D:\Program Files\Python\python.exe
#encoding:utf-8
import cgi,cgitb
print ("Content-type:text/html\n\n")
reshtml='''
<html>
<head>
<title> Friends CGI Demo (dynamic screen)</title>
</head>
<body>
<h3>Hello , this is a webpage used by CGI</h3>
</body>
</html>
'''
print (reshtml)
02 python3的cgi服务启动:
1.命令行 输入python -m http.server --cgi 命令打开默认端口8000
2.在浏览器输入localhost:8000就可以访问默认路径,即Python的安装目录, 所有要在这里建立cgi-bin文件夹,然后可以hello.py文件放到该文件夹下,当然可以根据需要创建多级目录.
03 访问文件
在浏览器中打开 http://localhost:8000/cgi-bin/hello.py
04 此时输出代码的问题尚未解决,实践用处不大,可以略过.
Apache 服务器动态网页
01 需要安装Apache 服务器, 安装教程可参考{服务器}模块下的文章,或者百度
02 启动服务器, 在浏览器地址栏输入 localhost验证服务已经正常启动(可以正常访问首页www/myIndex.html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="icon" href="/favicon.ico">
<meta charset="utf-8" />
<title>MyWebsite</title>
</head>
<body bgcolor="#eee" text="#000000" link="#0000FF"
vlink="#000080" alink="#FF0000" style="font-family:Arial;">
<div align="center" style="background-color:#284F95;color:#FFF;font-size:30px;height:50px;">
标题
</div>
<center>
<h3>概述<br/></h3>
<table width="80%" border="1px" cellpading="none" >
<tr>
<td colspan="2" align="center">
<form action="/cgi-bin/cgiApache.py">
<b>Input your name</b>
</td>
</tr>
<tr>
<td>
<input type="text" name="person" value="New User" size="20" />
</td>
</tr>
<tr>
<td>
<p>passage text </p>
</td>
</tr>
<tr>
<td>
<input type="radio" name="one" value="0" checked />0
<input type="radio" name="one" value="10" checked />10
<input type="radio" name="one" value="25" checked />25
<input type="radio" name="one" value="50" checked />50
<input type="radio" name="one" value="100" checked />100
</td>
</tr>
<tr>
<td>
<p><input type="submit" /></p>
</form>
</td>
</tr>
</table>
</center>
</body>
</html>
03 编写服务端代码到 /apache24/cgi-bin/cgiApache.py
#!D:\Program Files\Python\python.exe
#encoding:utf-8
import cgi,cgitb
print ("Content-type:text/html\n\n")
reshtml='''
<html>
<head>
<title> Friends CGI Demo (dynamic screen)</title>
</head>
<body>
<span>getName: <b>%(name)s</b> </span>
<p>theNumber: <b>%(age)s</b> </p>
<br />
<p>%(params)s</p>
</body>
</html>
'''
params = getValue = cgi.FieldStorage()
who = getValue["person"].value
num = getValue["one"].value
HTML_REPORT = reshtml % {"name":who, "age":num, "params":params}
print (HTML_REPORT)
04 提交数据
通过 myIndex.html 页面提交数据
查看后端返回的处理结果.