当前位置: 首页 > news >正文

Python 的下一代 HTTP 客户端

e3d1f934bfb2d47ae3843acffc7b8d56.png

迷途小书童

读完需要

9

分钟

速读仅需 3 分钟

1

   

环境

  • windows 10 64bit

  • python 3.8

  • httpx 0.23.0

2

   

简介

之前我们介绍过使用 requests ( https://xugaoxiang.com/2020/11/28/python-module-requests/ ) 来进行 http 操作,本篇介绍另一个功能非常类似的第三方库 httpx,它提供了同步和异步的 API,同时支持 HTTP/1.1 和 HTTP/2,是一个全功能的 HTTP 客户端。

3

   

安装

使用 pip 安装,执行命令

pip install httpx

在安装 python 库的同时,还安装了命令行工具 httpx.exe

bd6e7c17592a686bcd471a5eca8cd0e1.png

来看几个简单的示例

# get方法请求url
httpx.exe https://github.com -m get# post方法请求url,同时上传一个文本文件
httpx.exe https://domain.com -m post -f test.txt

4

   

基本使用

还是拿之前的 flask 后端例子来讲

from flask import Flask, jsonify, request
from flask_restful import Api, Resource, reqparseUSERS = [{"name": "zhangsan"},{"name": "lisi"},{"name": "wangwu"},{"name": "zhaoliu"}
]class Users(Resource):def get(self):return jsonify(USERS)def post(self):args = reqparse.RequestParser() \.add_argument('name', type=str, location='json', required=True, help="名字不能为空") \.parse_args()if args['name'] not in USERS:USERS.append({"name": args['name']})return jsonify(USERS)def delete(self):USERS = []return jsonify(USERS)class UserId(Resource):def __init__(self):self.parser = reqparse.RequestParser()self.parser.add_argument('name', type=str)self.parser.add_argument('age', type=int)def get(self, userid):datas = self.parser.parse_args()return jsonify({"name": USERS[int(userid)].get('name'), "age": datas.get('age')})def post(self, userid):file = request.files['file']file.save('flask_file.txt')return jsonify({'msg' : 'success'})app = Flask(__name__)
api = Api(app, default_mediatype="application/json")api.add_resource(Users, '/users')
api.add_resource(UserId, '/user/<userid>')app.run(host='0.0.0.0', port=5000, use_reloader=True, debug=True)

启动后端服务后,接着来看看客户端的请求。httpx 的基本用法和 requests 近乎相同,很多时候,只需要将原来的代码中的 requests 换成 httpx 就行。

import httpx# 使用get方法
r = httpx.get('http://127.0.0.1:5000/users')# http返回码
print(r.status_code)# http头
print(r.headers['content-type'])
# 也可以使用 r.headers.get('content-type')# 接口返回的json
print(r.json())

38b2f54ee29798a8e5e9a540e4e4f44e.png

import httpx
import jsonparam = {'name': 'xugaoxiang'}
headers = {"Content-type": "application/json"}# post请求
r = httpx.post('http://127.0.0.1:5000/users', data=json.dumps(param), headers=headers)print(r.status_code)
print(r.json())

88faa5bdddf7a42294700df98ee182a8.png

import httpx# delete请求
r = httpx.delete('http://127.0.0.1:5000/users')
print(r.json())
print(r.status_code)

302a44bb6fd10559c06e1c80d5021cb0.png

除此之外,像 put、head、options 方法的请求也是类似的,这里就不再举例了

r = httpx.put(url, data={'key': 'value'})
r = httpx.head(url)
r = httpx.options(url)

5

   

高级用法

上面示例中的用法是 httpx 提供的 top-level API,这在写一些测试脚本或者做系统原型时问题不大,但真正要在实际项目中去用的话,就会有性能上的问题。这是因为 httpx 在进行每一次的请求时都会去重新建立一个链接,也就是原有的链接没有被复用,这在高并发的情况就显得特别低效。

类似于 requests 模块中的 Session,httpx 提供了 Client,它会使用 http 连接池,大大减少链接重新建立的次数,减少 cpu 的使用率,降低了网络拥堵,提升系统效率。

Client 的使用比较简单,推荐的做法是将 Client 作为 context 管理器,看下面的示例

import httpxwith httpx.Client() as client:# 请求部分,将原来的 httpx 换成 client 就可以了,参数是一样的r = client.get('http://127.0.0.1:5000/users')print(r.json())print(r.status_code)

6

   

同步请求与异步请求

默认情况下,httpx 提供的是标准同步 API,如果想使用异步请求,可以这样

import httpx
import asyncioasync def make_async_request():async with httpx.AsyncClient()  as client:r = await client.get('http://127.0.0.1:5000/users')print(r.json())print(r.status_code)asyncio.run(make_async_request())

be299c3e09f19b91a0eff4b68ac90ce9.png

7

   

http2 支持

要使能 http2,我们需要额外安装库 httpx[http2]

# 这个包名取的太奇怪了
pip install httpx[http2]

然后在初始化 client 的时候加上 http2 的支持

with httpx.Client(http2=True)  as client:r = client.get('http://127.0.0.1:5000/users')

8

   

免费社群

7de33fa364f5f6683c07ad1fbd2d8106.jpeg

http://www.lryc.cn/news/131237.html

相关文章:

  • 网络安全---webshell实践
  • 论AI GPT跨境贸易架构及其应用
  • github的CodeSpace如何对外提供TCP 端口服务?
  • 借助Midjourney创作龙九子图
  • Azure存储访问层
  • Unity进阶–通过PhotonServer实现人物移动和攻击–PhotonServer(五)
  • 中间件: Redis安装与部署
  • Java日志框架-JUL
  • 【Java】智慧工地SaaS平台源码:AI/云计算/物联网/智慧监管
  • Dodaf架构的学习分享
  • 听GPT 讲Prometheus源代码--discovery
  • HTTP 介绍
  • Rust语言深入解析:后向和前向链接算法的实现与应用
  • 快速提高写作生产力——使用PicGo+Github搭建免费图床,并结合Typora
  • Java方法的参数可以有默认值吗?
  • 电子商务的安全防范
  • STM32开关输入控制220V灯泡亮灭源代码(附带PROTEUSd电路图)
  • Spring Boot配置文件
  • 函数(2)
  • Linux笔试题(4)
  • Selenium的使用:WEB功能测试
  • Kubernetes(K8s)从入门到精通系列之十七:minikube启动K8s dashboard
  • C++ 网络编程项目fastDFS分布式文件系统(五)--nginx+fastdfs
  • 开发者本地搭建性能监测工具(Windows)
  • 嵌入式Linux开发实操(八):UART串口开发
  • 公告:微信小程序备案期限官方要求
  • cesium中获取高度的误区
  • 基于Centos:服务器基础环境安装: JDK、Maven、Python、Go、Docker、K8s
  • Elasticsearch的数据删除策略只能触发一次
  • Open3D 最小二乘拟合空间直线(方法一)