Das http.server-Modul von Python3 kann einen einfachen http-Dienst erstellen.
Servercode
#! /usr/bin/env python3
# -*- coding:UTF-8 -*-
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import cgi
import datetime
# in:
# {'history':["q1", "a1", "q2", "a2"], 'query':"are you ok?"}
class RequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
self.send_error(415, 'Only get is supported')
def do_GET(self):
ctype, pdict = cgi.parse_header(self.headers['content-type'])
print(ctype, pdict)
print(f"ctype:{
ctype}")
print(f"pdict:{
pdict}")
path = str(self.path) # 获取请求的url
print(f"path:{
path}")
length = int(self.headers['content-length']) # 获取除头部后的请求参数的长度
datas = self.rfile.read(length) # 获取请求参数数据,请求数据为json字符串
print(f"datas:<<{
datas}>>")
rjson = json.loads(datas.decode())
print(f"rjson:<<{
rjson}>>, type<{
type(rjson)}>")
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({
'ret':0}).encode())
if __name__ == '__main__':
host = ('',8000)
server = HTTPServer(host, RequestHandler)
print("Starting server, listen at: %s:%s" % host)
server.serve_forever()
Kundenanfrage
GET http://10.20.42.93:6000/ HTTP/1.1
content-type: application/json; charset=utf-8
{
"name":"chatglm"
}
Serverseitiges Drucken
# python3 test_http.py
Starting server, listen at: :8000
application/json {
'charset': 'utf-8'}
ctype:application/json
pdict:{
'charset': 'utf-8'}
path:/
datas:<<b'{\r\n "name":"chatglm"\r\n}'>>
rjson:<<{
'name': 'chatglm'}>>, type<<class 'dict'>>
10.20.42.49 - - [17/Jul/2023 16:12:45] "GET / HTTP/1.1" 200 -
Verweise
BaseHTTPRequestHandler implementiert eine einfache API-Schnittstelle
Offizielles Handbuch: „http.server – HTTP-Server“