版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a1368783069/article/details/87359881
环境: 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/