python学习之http客户端和服务端

Part1前言

python非常简洁,非常适合写小功能以及测试接口。本文主要记录用pyhon实现一个简单的http客户端和服务端。

4dcc6a8b8aae832b9c3e5ba57a9ca198.png

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 re


class Router:
    def __init__(self):
        self.routes = {}

    def add_route(self, path, handler):
        self.routes[path] = handler

    def 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')
            return

        for route in self.routes:
            match = re.match(f'{route}(\?.*)?', path)
            if match:
                self.routes[route](handler)
                return

        print(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.path
        router.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.headers
    content_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).query
    params = 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的服务端。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用Python socket进行图片传输的简单示例,包括客户端服务端的代码: 服务端代码(server.py): ```python import socket import cv2 import numpy as np # 创建一个TCP/IP套接字 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(('localhost', 8888)) server_socket.listen(1) print("等待客户端连接...") client_socket, client_address = server_socket.accept() print("客户端已连接:", client_address) # 接收图片数据 data = b"" while True: packet = client_socket.recv(4096) if not packet: break data += packet # 将接收到的数据转换为图像 image_array = np.frombuffer(data, dtype=np.uint8) image = cv2.imdecode(image_array, cv2.IMREAD_COLOR) # 显示图像 cv2.imshow("Received Image", image) cv2.waitKey(0) # 关闭套接字和窗口 client_socket.close() server_socket.close() cv2.destroyAllWindows() ``` 客户端代码(client.py): ```python import socket import cv2 # 连接服务端 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(('localhost', 8888)) # 读取图像文件 image = cv2.imread('image.jpg') # 将图像数据转换为字符串 _, image_data = cv2.imencode('.jpg', image) image_data = image_data.tobytes() # 发送图像数据 client_socket.sendall(image_data) # 关闭套接字 client_socket.close() ``` 在这个示例中,服务端监听本地8888端口,客户端连接到服务端并发送图片数据。服务端接收数据并将其转换为图像,然后显示出来。请注意,客户端需要将要发送的图片命名为"image.jpg"并与客户端代码处于同一目录下。 希望这个示例对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值