命令
python -m http.server
# 参数
[-h] [--cgi] [--bind ADDRESS] [--directory DIRECTORY] [port]
详解
cgi 指定cgi脚本服务器
-
- 本质将http请求转为python命令行执行映射脚本并返回对应结果
以服务器的形式访问python脚本文件
py脚本代码文件默认目录在cgi-bin或者htbin下
在脚本层面不受http谓词的影响
web服务器
- 遵守
http
谓词,需要实现相应server
类的诸如do_post
方法 - 默认8000端口
示例
post请求cgi脚本
from urllib.request import *
# 发起post请求
with urlopen(url='http://localhost:8000/cgi-bin/test.py', data='测试数据'.encode('utf-8')) as f:
# 读取服务器全部响应
print(f.read().decode('utf-8'))
cgi脚本
# cgi-bin/test.py
import sys
data = sys.stdin.read()
# 以cgi形式执行python脚本应用
print('Content-type: text/plain\n\nGot Data:"%s"' % data)
响应
- 控制台响应
# 控制台
Got Data:"测试数据"
- 命令行轨迹
# 命令行开启cgi服务器
>py -3 -m http.server --cgi
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
127.0.0.1 - - [18/May/2019 21:39:16] "POST /cgi-bin/test.py HTTP/1.1" 200 -
127.0.0.1 - - [18/May/2019 21:39:16] command: "D:\Program Files\anaconda\python.
exe" -u D:\code-base\python\net\cgi-bin\test.py ""
127.0.0.1 - - [18/May/2019 21:39:16] CGI script exited OK
其它
- 类似的php也有开启置简易服务器的命令,如下
php -S <addr>:<port>