Part1前言
python非常简洁,非常适合写小功能以及测试接口。本文主要记录用pyhon实现一个简单的http客户端和服务端。
Part2http客户端
这里采用request库来实现。示例如下
import requests
import json
url = 'http://127.0.0.1:81/test?key1=123&key2=456'headers = {'Authorization': 'cfe7mpr2fperuifn65g0','Content-Type': 'application/json',
}
payload = {}
payload["prompt"] = "prompt"
payload["model"] = "xl"
sendBody = json.dumps(payload)response = requests.post(url, headers=headers, data=sendBody)print(response.status_code)
print(response.content)
本示例实现了几个功能:
1、发送内容python对象转成json字符串,通过
sendBody = json.dumps(payload)
2、设置http的头内容,构建了一个headers对象
3、发送数据
4、处理应答数据
Part3http服务端
http服务端也是采用内置的http.server来实现,代码如下
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import requests
from urllib.parse import urlparse, parse_qs
import reclass Router:def __init__(self):self.routes = {}def add_route(self, path, handler):self.routes[path] = handlerdef dispatch(self, path, method, handler):if method not in ('GET', 'POST'):handler.send_response(405)handler.send_header('Content-type', 'text/plain')handler.end_headers()handler.wfile.write(b'Method not allowed')returnfor route in self.routes:match = re.match(f'{route}(\?.*)?', path)if match:self.routes[route](handler)returnprint(f'error path = {path}')handler.send_response(404)handler.send_header('Content-type', 'text/plain')handler.end_headers()handler.wfile.write(b'Page not found')class MyHTTPRequestHandler(BaseHTTPRequestHandler):def do_GET(self):self.route_request('GET')def do_POST(self):self.route_request('POST')def route_request(self, method):path = self.pathrouter.dispatch(path, method, self)def send_response(self, code):super().send_response(code)self.send_header('Access-Control-Allow-Origin', '*')def send_json_response(self, data):self.send_response(200)self.send_header('Content-type', 'application/json')self.end_headers()self.wfile.write(json.dumps(data).encode('utf-8'))def on_Test(handler):responseData = {"code": 0,"msg": "success"}# 解析请求的 URL,获取参数print(handler.path)# 获取请求头部信息headers = handler.headerscontent_type = headers.get('Content-Type', 'json')print(content_type)# 获取请求体信息content_length = int(handler.headers.get('Content-Length'))content = handler.rfile.read(content_length).decode('utf-8')print(content)query = urlparse(handler.path).queryparams = parse_qs(query)value1 = params.get('key1', '')value2 = params.get('key2', '')print(value1)print(value2)handler.send_json_response(responseData)router = Router()
router.add_route('/test', on_Test)httpd = HTTPServer(('localhost', 81), MyHTTPRequestHandler)
httpd.serve_forever()
本示例构建了一个路由类,这样可以非常方便的处理不同url的请求。我们只需要编写自己的处理函数即可。例如示例的处理函数是on_Test。
1、获取请求的url通过函数 print(handler.path)
2、获取头部信息,通过 handler.headers 对象获取
3、获取请求消息内容,通过
content = handler.rfile.read(content_length).decode('utf-8')
4、获取请求url中的参数,通过parse_qs来实现
params = parse_qs(query)value1 = params.get('key1', '')
5、发送应答我们进行了从新封装,在send_json_response函数中,设置应答code,以及设置http头和写入应答数据
def send_json_response(self, data):self.send_response(200)self.send_header('Content-type', 'application/json')self.end_headers()self.wfile.write(json.dumps(data).encode('utf-8'))
Part4总结
本文主要写了一个基于Python得最简单的http的客户端和http的服务端。