极简运行
python -m http.sever
或
# test.py
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
CGI-Bin
-
做了以上的启动之后就得到了一个文件服务器。
-
我主要复制教你如何用几行Python代码编写出一个简易Web服务器的代码。在当前目录下创建C:\Users\admin\Desktop\http\cgi-bin文件夹,CGI-bin 是一个用于存放脚本的文件夹,这些脚本将与 Web 浏览器交互以提供网页或网站的功能。通用网关接口 (CGI) 是一种资源,用于在 Web 设计中使用脚本。当脚本从服务器发送到 Web 浏览器时,通常在 url 中引用 CGI-bin。,用于实现类似jsp的功能。
-
但是大多数的博客都比较推荐使用此模块搭建简单的测试项目。
启动服务
import os
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir="C:\\Users\\admin\\Desktop\\http"
os.chdir(webdir)
HTTPServer(("127.0.0.1", 8080), CGIHTTPRequestHandler).serve_forever()
import pickle
import os
student_keys = ("name", "gender", "age", "score")
if os.path.exists("student.data"):
with open("student.data", "rb") as file:
student = pickle.load(file)
student = student or {}
else:
student = {}
if not student:
student = dict.fromkeys(student_keys, "")
header = "Content-Type: text/html\n"
content = """
<html>
<body>
<form action="/cgi-bin/update.py" method="POST">
<table>
<tr>
<td>name: </td>
<td><input name="name" value="{name}"/></td>
</tr>
<tr>
<td>gender:</td>
<td><input name="gender" value="{gender}"/></td>
<tr>
<tr>
<td>age: </td>
<td><input name="age" value="{age}"/></td>
</tr>
<tr>
<td>score: </td>
<td><input name="score" value="{score}"/></td>
</tr>
<tr>
<td style="padding-top: 10px" align="center" colspan="2">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
</body>
</html>
"""
import os
import cgi
import pickle
student_keys = ("name", "gender", "age", "score")
if os.path.exists("student.data"):
with open("student.data", "rb") as file:
student = pickle.load(file)
student = student or {}
else:
student = {}
if not student:
student = dict.fromkeys(student_keys, "")
form = cgi.FieldStorage()
for key in student_keys:
if key in form and form[key].value:
student[key] = form[key].value
with open("student.data", "wb") as file:
pickle.dump(student, file)
header = "Content-Type: text/html\n"
content = """
<html>
<body>
<h1>update successfully, will skip to display page: <span id="count_down">3</span></h1>
<script>
var count = 3
timer_id = setInterval(function(){
count = count -1
if(count == 0) {
clearInterval(timer_id)
location.href="/cgi-bin/student.py"
} else {
document.getElementById("count_down").innerHTML = "" + count
}
},1000)
</script>
</body>
</html>
"""
你可能应该访问“localhost:81/cgi-bin/index.py”。因为“localhost:81/cgi-bin/”是一个目录,不是一个python script。
使用体验
- 当在文件服务器的模式下,可以直接访问并渲染html文件,但是当我使用以下代码时,浏览器提示
var myChart = echarts.init(document.getElementById('main'));
无法找到echarts对象。
import os
import cgi
import pickle
# student_keys = ("name", "gender", "age", "score")
# if os.path.exists("student.data"):
# with open("student.data", "rb") as file:
# student = pickle.load(file)
# student = student or {}
# else:
# student = {}
#
# if not student:
# student = dict.fromkeys(student_keys, "")
form = cgi.FieldStorage()
# for key in student_keys:
# if key in form and form[key].value:
# student[key] = form[key].value
# with open("student.data", "wb") as file:
# pickle.dump(student, file)
header = "Content-Type: text/html\n"
content = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>bar</title>
<!-- 引入 echarts.js -->
<script src="echarts.min.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 900px;height:600px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
var option = {
// 标题
title: {
text: 'ECharts 入门示例'
},
// 工具箱
toolbox: {
show: true,
feature: {
saveAsImage: {
show: true
}
}
},
// 图例
legend: {
data: ['销量']
},
// x轴
xAxis: {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
},
yAxis: {},
// 数据
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>
"""
print(header + content)
参考与更多
https://docs.python.org/3/library/http.server.html
用 Python 的 SimpleHTTPServer 模組快速建立一個臨時網頁伺服器(Web Server)
使用Python的http.server实现一个简易的Web Api对外提供HanLP拼音转换服务
simple http server for upload and download