首页 > 编程语言 >python学习之http客户端和服务端

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

时间:2023-04-16 10:01:26浏览次数:39  
标签:http python self send headers json handler response 服务端


Part1前言

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

python学习之http客户端和服务端_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 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的服务端。

标签:http,python,self,send,headers,json,handler,response,服务端
From: https://blog.51cto.com/u_12701820/6193332

相关文章

  • 在写Python是要注意初始化函数的书写
    问题来啦!在撰写Python程序的时候,我们一定要注意,Python的初始化函数init的书写,它的名称是init,这样的话,实例化的过程中,我们才能够成功获取到我们在里面输入的数值;我起初就忽视了这个问题,将原本的四个横线写成了这样__init,主要是它也没有报出错误,我也获取不到数值,后来又仔细检查......
  • python 批量打印证书(保存未调试)
    importosfromPILimportImage,ImageDraw,ImageFontimportxlrd#要求录入学校信息的证书defzs_school(size,left,height,n,c,m1,d1,m2,d2,t):newfont=ImageFont.truetype(font="Songti.ttc",size=size)draw.text((600,height),n,font=newfont......
  • 全排列--Python实现
    给定一个不含重复数字的数组nums,返回其所有可能的全排列。defpermute(nums):track,self.res=[],[]self.backtrack(nums,track)returnself.res#路径:记录在track中#选择列表:nums中不存在于track的那些元素#结束条件:nums中的......
  • Python 人工智能:6~10
    原文:ArtificialIntelligencewithPython协议:CCBY-NC-SA4.0译者:飞龙本文来自【ApacheCN深度学习译文集】,采用译后编辑(MTPE)流程来尽可能提升效率。不要担心自己的形象,只关心如何实现目标。——《原则》,生活原则2.3.c6集成学习的预测分析在本章中,我们将学习集成学习......
  • Python 人工智能:21~23
    原文:ArtificialIntelligencewithPython协议:CCBY-NC-SA4.0译者:飞龙本文来自【ApacheCN深度学习译文集】,采用译后编辑(MTPE)流程来尽可能提升效率。不要担心自己的形象,只关心如何实现目标。——《原则》,生活原则2.3.c21循环神经网络和其他深度学习模型在本章中,我们将......
  • Python 迁移学习实用指南:6~11
    原文:Hands-OnTransferLearningwithPython协议:CCBY-NC-SA4.0译者:飞龙本文来自【ApacheCN深度学习译文集】,采用译后编辑(MTPE)流程来尽可能提升效率。不要担心自己的形象,只关心如何实现目标。——《原则》,生活原则2.3.c六、图像识别与分类知识投资永远是最大的利益。......
  • Python模块-requests
    1、requests模块requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求。功能强大,用法简洁高效。2、模块介绍及请求过程requests模块模拟浏览器发送请求请求流程:指定url-->发起请求-->获取响应对象中存储的数据-->持久化存储3、爬取百度首页#!......
  • Python模块-socket
    1、基于TCP协议的socket通信以打电话为理解方式进行TCP的通信#Server端importsocketphone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)#购买电话卡,AF_INET服务器之间网络通信,socket.SOCK_STREAM,流式协议,就是TCP协议phone.bind(('127.0.0.1',8080))......
  • java.lang.NoSuchMethodException: com.innovation.web.BuyServlet.get(javax.servlet
    问题描述我将路径定义到相应的servlet的函数方法里面,然后就出现了这个问题,很明显的找不到相应的函数方法;问题解决将目光重新放到我定义的相关路径那里,发现我出于习惯,将servlet里面原本应该是名为checkIt的函数方法写成了get方法,改回去之后,这个问题也就解决啦!......
  • 部署Python3
    1、安装编译工具yum-ygroupinstall"Developmenttools"yum-yinstallzlib-develbzip2-developenssl-develncurses-develsqlite-develreadline-develtk-develgdbm-develdb4-devellibpcap-develxz-develyuminstalllibffi-devel2、下载软件包并解压wgethttps://ww......