2 回答
TA贡献1786条经验 获得超13个赞
您所要做的就是导入http.server默认模块。
from http.server import HTTPServer, SimpleHTTPRequestHandler
def run(number=8080, server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler):
server_address = ('', number)
httpd = server_class(server_address, handler_class)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("Exit")
有关详细说明,请参阅Python 文档。
TA贡献1934条经验 获得超2个赞
通过使用这两个模块,可以通过 Python 程序轻松地为网站提供服务:
http.server(用于 http)
套接字服务器(用于 TCP 端口)
这是工作代码的示例:
# File name: web-server-demo.py
import http.server
import socketserver
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving the website at port # ", PORT)
httpd.serve_forever()
示例 index.html 文件:
<!DOCTYPE html>
<html>
<head>
<title>Website served by Python</title>
</head>
<bod>
<div>
<h1>Website served by Python program</h2>
</div>
</body>
</html>
输出:
> python web-server-demo.py
serving the website at port # 8080
127.0.0.1 - - [25/May/2020 14:19:27] "GET / HTTP/1.1" 304 -
添加回答
举报