環境: python3.68 centos 7.5
python3 中實現http serverr有很多種方法,可以使用 flask(light), django , tornado 等等。也可以使用build-in 模塊實現,即: http.server - HTTP servers
以下代碼就是實現的一個http get 請求的完整流程。
import json
import http.server
import socketserver
from urllib.parse import urlparse, parse_qs
PORT = 7700
class HandleServer(http.server.BaseHTTPRequestHandler):
def do_GET(self):
print(self.client_address)
print(self.headers)
query = urlparse(self.path)
returncode, msg = 0, "success"
if query.path.strip("/") == urlparse("/parse/").path.strip("/") :
params = parse_qs(query.query)
q = params("q",[""])[0]
print("right")
else:
print("wrong")
returncode, msg = 1000, "url path should be parse"
output = {"returncode": returncode, "message": msg}
self.wfile.write(json.dumps(output).encode("utf-8"))
handler = HandleServer
with socketserver.TCPServer(("", PORT), handler) as httpd:
print("server starting..", PORT)
httpd.serve_forever()
其中:
urlparse, parse_qs 是用來解析請求路徑,以及解析參數
json 是將json的響應數據轉成string,然後通過 encode 轉換爲 utf8 二進制數據
linux 命令行請求示例:
curl "http://127.0.0.1:7700/parse/?q=test"
以上是http請求,當然也可以改成https, 可以參考網上的資料。
有關 http.server 的使用,可以參見官方文檔,裏面是有幾種方法的。
推薦資料:
Simple Python HTTP(S) Server With GET/POST Examples
https://blog.anvileight.com/posts/simple-python-http-server/