广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python-httpx的具体使用
  • 933
分享到

python-httpx的具体使用

2024-04-02 19:04:59 933人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录安装创建请求自定义头部超时时间SSL证书认证请求类型Query ParamsFORM表单文件上传JSON二进制数据响应响应类型Cookie重定向历史Httpx.Client合并/

HTTPX是python3的功能齐全的HTTP客户端,它提供同步和异步api,并支持HTTP/1.1和HTTP/2

安装

pip install httpx

创建请求

通过httpx库发出一个请求非常简单,如下:

import httpx

response = httpx.get('https://www.baidu.com/')
print(type(response), response)     # <class 'httpx.Response'> <Response [200 OK]>

同样,我们再来发出一个POST请求:

response = httpx.post('http://localhost:5000/login', data={'username': 'httpx', 'passWord': '123456'})

PUT, DELETE, HEAD和OPTioNS请求都遵循相同的样式:

response = httpx.put('http://www.baidu.com/', data={key: value})
response = httpx.head('http://www.baidu.com/')
response = httpx.delete('http://www.baidu.com/')
response = httpx.options('http://www.baidu.com/')

自定义头部

要在传入请求中包含其他标头,请使用headers关键字参数:

header = {"user-agent": 'my_test/0001'}
response = httpx.get("https://api.GitHub.com/events", headers=header)

超时时间

httpx设置默认的超时时间为5秒,超过此时间未响应将引发错误。我们可以通过timeout关键字参数来手动修改它:

response = httpx.get('http://localhost:5000/update', timeout=10)

你也可以将其设置为None完全禁用超时行为

response = httpx.get('http://localhost:5000/update', timeout=None)

超时又可以分为connect, read,write和pool超时。如果想详细设置,我们可以通过httpx.Timeout类来实现:

# 读取超时为10s,其他超时为5秒
timeout = httpx.Timeout(5, read=10)
response = httpx.get('http://localhost:5000/update', timeout=timeout)

SSL证书

通过httpx发出HTTPS请求时,需要验证所请求主机的身份。我们可以通过verify来指定我们存在的CA证书:

response = httpx.get('https://example.org', verify='../../client.pem')

或者你可以传递标准库ssl.SSLContext

import ssl
import httpx

context = ssl.create_default_context()
context.load_verify_locations(cafile='../../client.pem')
response = httpx.get('https://example.org', verify='../../client.pem')

又或者,你可以将verify设置为False禁用SSL验证:

response = httpx.get('https://example.org', verify=False)

认证

HTTPX支持Basic Auth和Digest Auth身份验证。要提供身份验证凭据,请将2个元组得纯文本str或bytes对象作为auth参数传递给请求函数:

response = httpx.get('https://example.com', auth=('my_user', 'password123'))

要提供Digest Auth身份验证得凭据,你需要Digest Auth使用纯文本用户名和密码作为参数实例化一个对象。然后可以将该对象作为auth参数传递给上述请求方法:

from httpx import DigestAuth

auth = DigestAuth('my_user', 'password123')
response = httpx.get('https://example.com', auth=auth)

httpx还提供了一个FunctionAuth类,允许我们传入一个Callable对象,该Callable接收request参数,并返回request。如下:

import httpx
from httpx._auth import FunctionAuth

def init_authorization(request):
    request.headers['Authorization'] = 'Bearer 12334'
    yield request

auth = FunctionAuth(init_authorization)
response = httpx.get('http://localhost:5000/home', auth=auth)

请求类型

Query Params

params = {"name":"zhangsan", "age":18}
response = httpx.get("https://www.baidu.com/s", params=params)

此时我们打印一下URL,发现该URL已经被正确编码:

print(response.url)    # https://www.baidu.com/s?name=zhangsan&age=18

也可以传递一个列表数据进去:

params = {"name":"zhangsan", "favorite": ["football", "basketball"]}
response = httpx.get("https://www.baidu.com/s", params=params)

Form表单

通常情况下,你想要发送一些表单编码数据,就像html表单一样。要做到这一点,你只需要将字典传递给data关键字参数即可:

data = {'name': '张三'}
response = httpx.post('http://127.0.0.1:5000/test/post', data=data)

文件上传

你还可以使用HTTP分段编码上传文件

f = open('a.txt', 'rb')
files = {'file': f}
response = httpx.post('http://localhost:5000/post', files=files)
f.close()

jsON

如果你想要发送一个JSON数据,你可以通过将数据传递给json关键字参数即可:

response = httpx.post('http://127.0.0.1:5000/test/post', json={'name': '张三'})

二进制数据

对于其他编码,应使用content关键字参数,传递一个bytes类型数据

content = b'Hello World'
response = httpx.post('http://127.0.0.1:5000/test/post', content=content)

响应

响应类型

在上面的栗子可以知道,我们每次请求之后都会返回一个httpx.Response对象,我们可以从此对象中获取响应内容:

response = httpx.get("https://api.github.com/events")
print(type(response.text), response.text)      # <class 'str'> [{"id":"14551634865","type":"PushEvent", ...}]

二进制响应

print(type(response.content), response.content) # <class 'bytes'> b'[{"id":"14551634865","type":"PushEvent", ...}]

JSON响应

print(type(response.json()), response.json())   # <class 'list'> [{'id': '14551634865', 'type': 'PushEvent', ...}]

流式响应

对于大型下载,你可能需要使用不将整个响应主体立即加载到内存中的流式响应。你可以流式传输响应的二进制内容:

for data in response.iter_bytes():
    print(data)

流式传输响应的文本内容:

for text in response.iter_text():
    print(text)

逐行流文本:

for line in response.iter_lines():
    print(line)

原始字节:

for chunk in response.iter_raw():
    print(chunk)

Cookie

如果响应包含了Cookie,你可以这样快速的访问它:

response = httpx.get('http://localhost:5050/get')
print(response.cookies['user'])

重定向历史

history响应的属性可用于检查任何后续的重定向。它包含遵循它们的顺序的所有重定向响应列表。例如GitHub将所有HTTP请求重定向到HTTPS:

response = httpx.get('http://github.com/')
print(response, response.url)       # <Response [200 OK]> https://github.com/
print(response.history, response.history[0].url)    # [<Response [301 Moved Permanently]>] http://github.com/

你还可以使用allow_redirects关键字参数来修改默认得重定向处理:

response = httpx.get('http://github.com/', allow_redirects=False)
print(response)         # <Response [301 Moved Permanently]>
print(response.history) # []

httpx.Client

如果你会使用requests,那么可以使用httpx.Client代替requests.Session

with httpx.Client() as client:
    response = client.get('http://localhost:5000/details')

另外,还可以使用.close()方法明确关闭连接池,而不会阻塞:

client = httpx.Client()
try:
    response = client.get('http://localhost:5000/details')
finally:
    client.close()

一旦你拥有了一个httpx.Client实例,那么你就可以通过调用.get()、.post()等方法发送请求。这些方法同样支持timeout、auth、headers等参数来满足我们的需求

合并/共享配置

httpx.Client还接收headers、cookie和params参数,对于同一组的请求操作,将共享同样的headers、cookie和params参数。如果请求方法中也包含了这些参数,那么它们将进行合并:

with httpx.Client(headers={'Token': '12345678'}, params={'page_size': 1, 'size': 20}) as client:
    resp1 = client.get('http://localhost:5000/get', params={'search': 'laozhang'})
    resp2 = client.post('http://localhost:5000/post')

如此,这两个请求的头部都将包含{'Token': '12345678'}。请求1的params将会合并,请求2将会使用{'page_size': 1, 'size': 20}查询参数

对于其他参数,如auth等,那么将会优先使用请求方法里面的auth

base_url

httpx.Client还允许使用base_url参数来设置基础URL,如下:

with httpx.Client(base_url='http://localhost:5000') as client:
    response = client.get('/user/detail')
    print(response.url)     # http://localhost:5050/user/detail

limits

可以使用limits关键字参数来控制连接池的大小。它需要传递一个httpx.Limits类实例,httpx.Limits类接收以下两个参数:

  • max_keepalive: 最大活跃连接数,设置为None表示无限制。默认为10
  • max_connections:最大连接数,设置为None表示苏限制。默认为100
limits = httpx.Limits(max_keepalive=2, max_connections=5)
client = httpx.Client(limits=limits)

调用Python Web App

你可以配置httpx客户端以使用WSGI协议直接调用Python Web应用程序。这对于两个主要用例特别有用:

  • 使用httpx的测试案例中的客户端
  • 在测试期间或在dev/staging环境中模拟外部服务
import httpx
from flask import Flask

app = Flask(__name__)

@app.route("/home")
def home():
    return 'Home Api Success'

with httpx.Client(app=app, base_url='http://testapi') as client:
    response = client.get('/home')
    print(response)                     # <Response [200 OK]>
    print(response.text, response.url)  # Home Api Success http://testapi/home

我们还可以通过使用WSGITransport来使用给定的客户端地址用于请求,如下:

transport = httpx.WSGITransport(app=app, remote_addr='1.2.3.4')
with httpx.Client(transport=transport, base_url='http://testapi') as client:
    response = client.get('/home')
    print(response)                     # <Response [200 OK]>
    print(response.text, response.url)  # Home Api Success http://testapi/home

如此,视图函数home中request.remote_addr将会是1.2.3.4

事件钩子

httpx允许你向客户端注册事件钩子,每次发生特定类型的事件时都会调用该钩子。httpx支持两个事件钩子:

  • request: 在即将发生请求时调用。为一个Callable列表,Callable接收httpx.Request实例参数
  • response: 响应返回后调用。为一个Callable列表,Callable接收httpx.Response实例参数
def _log_request(request):
    print(type(request), request.url, request.method)       # <class 'httpx.Request'> http://localhost:5000/hello GET
    
def _log_response(response):
    print(type(response), response.url, response.text)      # <class 'httpx.Response'> http://localhost:5000/hello Home Api Success
    
with httpx.Client(base_url='http://localhost:5000') as client:
    client.get('/home')

代理

要将所有请求使用http://localhost:8030的代理,请将代理URL传递给Client:

with httpx.Client(proxies='http://localhost:8030') as client:
    pass

对于更高级的使用,请使用dict。例如,要将HTTP和HTTPS请求路由到两个不同的代理: http://localhost:8030和http:localhost:8031:

proxies = {
    'http://': 'http://localhost:8030',
    'https://': 'http:localhost:8031'
}
with httpx.Client(proxies=proxies) as client:
    pass

代理所有请求:

proxies = {
    'all://': 'http://localhost:8030'
}

代理域名为“example.com”的所有请求:

proxies = {
    'all://example.com': 'http://localhost:8030'
}

代理域名为“example.com”的所有HTTP请求:

proxies = {
    'http://example.com': 'http://localhost:8030'
}

代理所有包含“example.com”的所有请求:

proxies = {
    'all://*example.com': 'http://localhost:8030'
}

对于上面匹配,如果未匹配到将不使用代理。域名后面还可以添加端口号,用于更加严格的匹配。此外,我们还可以将匹配设置为None,用于排除,如下:

proxies = {
    'all://': 'http://localhost:8030',
    'all://example.com': None
}

即除使用“example.com”域名的路由,将使用“http://localhost:8030”代理

异步支持

HTTPX默认情况下提供标准的同步API,但是如果需要,还可以为你提供异步客户端的选项。要发出异步请求,你需要一个httpx.AsyncClient

import asyncio
import httpx

async def main():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://example.org/')

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(main())
finally:
    loop.close()

发出请求

请求方法都是异步的,因此你应该使用response = await client.get(...)样式对以下所有内容使用:

  • AsyncClient.get(url, ...)
  • AsyncClient.options(url, ...)
  • AsyncClient.head(url, ...)
  • AsyncClient.post(url, ...)
  • AsyncClient.put(url, ...)
  • AsyncClient.patch(url, ...)
  • AsyncClient.delete(url, ...)
  • AsyncClient.request(url, ...)
  • AsyncClient.send(url, ...)

流式响应

  • Response.aread()
  • Response.aiter_bytes()
  • Response.aiter_text()
  • Response.aiter_lines()
  • Response.aiter_raw()

更多关于httpx的操作请看: https://www.python-httpx.org/

到此这篇关于python-httpx的具体使用的文章就介绍到这了,更多相关python httpx内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: python-httpx的具体使用

本文链接: https://www.lsjlt.com/news/161951.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python-httpx的具体使用
    目录安装创建请求自定义头部超时时间SSL证书认证请求类型Query ParamsForm表单文件上传JSON二进制数据响应响应类型Cookie重定向历史httpx.Client合并/...
    99+
    2022-11-12
  • python httpx如何使用
    什么是 HttpxHttpx 是一个 Python 库,它提供了一个现代化的、易于使用的 HTTP 客户端和服务器。Httpx 可以与 Python 的异步框架协同工作,并支持 WebSocket 和 HTTP/2。Httpx 具有极佳的性...
    99+
    2023-05-14
    Python httpx
  • Python中collections.Counter()的具体使用
    目录Counter类创建计数值的访问与缺失的键计数器的更新键的删除elements()most_common([n])fromkeys浅拷贝copy算术和集合操作常用操作Counter类 Counter类的目的是用...
    99+
    2022-06-02
    Python collections.Counter()
  • python中pywifi的具体使用
    目录写在前面pywifi常量接口wifi连接代码写在前面 无线AP(Access Point):即无线接入点 python的wifi管理模块叫pywifi 安装 pip instal...
    99+
    2023-03-06
    python pywifi
  • python具名元组(namedtuple)的具体使用
    目录具名元组元组操作属性排序与字典比较数据类dataclass修饰继承NamedTuplecollections.namedtuple用于构造带字段名的元组。对应类型为typing....
    99+
    2023-03-21
    python具名元组
  • python Pygame的具体使用讲解
    一、实验介绍 1.1 实验内容 在本节课中,我们将讲解Pygame的常用对象及其操作,包括图形、动画、文字、音频等,确保同学们对Pygame有一个基础的了解,同时为后续课程做好准备。 1.2 实验知识点 ...
    99+
    2022-06-04
    python Pygame
  • python[::-1][::-1,::-1]的具体使用
    目录一、 [::-1]二、 [::-1,::-1]一、 [::-1] import numpy as np import numpy as np x = np.arange(1, ...
    99+
    2022-11-11
  • Python中typing模块的具体使用
    目录typing库一、 简介二、 别名1、 类型别名2、 NewType3、 可调用对象三、 泛型支持1、集合类型2、 抽象基类3、 泛型4、 Any5、 特殊形式5.1 Type5...
    99+
    2022-11-11
  • Python中range()与np.arange()的具体使用
    目录np.arange()range()range()和np.arange()区别np.arange() np.arange()函数返回一个有终点和起点的固定步长的排列,如[1,2,...
    99+
    2022-11-12
  • Python try-except-else-finally的具体使用
    目录try-excepttry-except-elsetry-finallytry-except 作用:处理异常情况 用法:try:后面写正常运行的代码,except + 异常情况:...
    99+
    2022-11-12
  • Python中str.format()方法的具体使用
    目录1. 术语说明 2. 简单字段名 2.1 简单字段名的说明 2.2 省略字段名 2.3 数字形式的简单字段名 2.4 变量名形式的简单字段名 2.5 简单字段名的混合使用 2.6...
    99+
    2022-11-12
  • python中decimal模块的具体使用
    decimal模块主要的作用是精确小数,因为float是不精确的,只是无限接近,对于一些需要精确小数点后位数的就需要用decimal。 Decimal类型的优点 Decimal类型是...
    99+
    2023-01-29
    python decimal模块 python decimal
  • python中networkx函数的具体使用
    目录1. 介绍1.1 前言1.2 图的类型(Graph Types)1.3 常用方法2. 代码示例1. 介绍 1.1 前言 NetworkX是复杂网络研究领域中的常用Python包。...
    99+
    2023-02-14
    python networkx使用 python networkx
  • python数据类(dataclass)的具体使用
    目录数据类定义装饰器field初始化数据比较后处理dataclasses方法Python3.7引入了dataclass。dataclass装饰器可以声明Python类为数据类;数据类...
    99+
    2023-03-21
    python 数据类
  • Python中的axis参数的具体使用
    目录一、axis简介二、不一样的axis对于axis=0三、总结补充:python中某些函数axis参数的理解 在我们使用Python中的Numpy和Pandas进行数据分析的时候,...
    99+
    2022-11-12
  • Python命令行库click的具体使用
    目录一、前言二、介绍三、快速开始四、小结一、前言 今天要介绍的 click 则是用一种你很熟知的方式来玩转命令行。命令行程序本质上是定义参数和处理参数,而处理参数的逻辑一定是与所定义...
    99+
    2022-11-11
  • python灰色预测法的具体使用
    目录1.简介2.算法详解2.1生成累加数据2.2  累加后的数据表达式2.3 求解2.2的未知参数3.实例分析3.1导入数据3.2进行累加数据 ...
    99+
    2022-11-13
  • python内置函数anext的具体使用
    作用 anext() 是 Python 3.10 版本中的一个新函数。它在等待时从异步迭代器返回下一项,如果给定并且迭代器已用尽,则返回默认值。这是 next() 内置的异步变体,行...
    99+
    2023-01-18
    python内置函数anext python anext
  • Python内置函数 next的具体使用
    Python 3中的File对象不支持next()方法。 Python 3有一个内置函数next(),它通过调用其next ()方法从迭代器中检索下一个项目。 如果给定了默认值,则在迭代器耗尽返回此默认值,否则会引发StopIterati...
    99+
    2023-01-31
    函数 Python
  • Python IO文件管理的具体使用
    目录文件操作python文件操作的两种模式编码格式的了解open函数的使用文件的写入(写入模式)文件的读取(读取模式)文件内容追加(追加模式)字节流的转换存储二进制的字节流上下文管理...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作