2 回答

TA貢獻1786條經(jīng)驗 獲得超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條經(jīng)驗 獲得超2個贊
通過使用這兩個模塊,可以通過 Python 程序輕松地為網(wǎng)站提供服務:
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 -
添加回答
舉報