如何使用Python-httpx库进行新一代网络请求操作?
- 内容介绍
- 文章标签
- 相关推荐
本文共计3723个文字,预计阅读时间需要15分钟。
目录
一、概述
1.简介
2.命令行模式
3.快速开始
3.1 get请求 3.2 post请求 3.3 响应处理 3.4 流式响应 3.5 cookie 3.6 重定向 3.7 超时和验证二、客户端
1.特性
2.发起请求
3.其他配置
目录
- 一、 概述
- 1、 简介
- 2、 命令行模式
- 3、 快速开始
- 3.1 get请求
- 3.2 post请求
- 3.3 响应处理
- 3.4 流式响应
- 3.5 cookie
- 3.6 重定向
- 3.7 超时和验证
- 二、 客户端
- 1、 特性
- 2、 发出请求
- 3、 其他配置
- 4、 python_web
- 5、 Request对象
- 6、 钩子函数
- 7、 进度条
- 8、 .netrc 支持
- 三、 代理
- 1、 简介
- 2、 使用方法
- 2.1 简单使用
- 2.2 验证
- 2.3 路由
- 3、 区别
- 3.1 前言
- 3.2 requests代理
- 3.3 总结
- 四、 异步客户端
- 1、 简介
- 2、 API 差异
- 2.1 发出请求
- 2.2 打开和关闭客户
- 2.3 流式响应
- 2.4 流式传输请求
- 3、 异步环境
- 3.1 asyncio
- 3.2 trio
- 3.3 anyio
- 4、 python_web
- 总结
一、 概述
1、 简介
HTTPX 是 Python 3 的全功能 HTTP 客户端,它提供同步和异步 API,并支持 HTTP/1.1 和 HTTP/2。
官方文档位置:www.python-www.baidu.com/s", params=params, headers=headers, cookies=None, proxies=None) # 和原来requests的使用方法类似 resp.encoding = resp.charset_encoding # 根据文档的编码还对文档进行编码 print(resp.text) # 获取数据信息
requests中的参数和www.baidu.com") if resp.status_code == www.example.com") as r: for data in r.iter_bytes(): # 流式传输响应的二进制内容 # for text in r.iter_text(): # 获取全部的文本内容 # for line in r.iter_lines(): # 逐行获取传输响应的文本内容 # for chunk in r.iter_raw(): # 获取编码前的原始数据 # if r.headers['Content-Length'] < TOO_LONG: # 有条件的加载内容 print(data)
注意:
如果您以任何这些方式使用流式响应,则response.contentandresponse.text属性将不可用3.5 cookie
#!/usr/bin/python3 # -*- coding: UTF-8 -*- __author__ = "A.L.Kun" __file__ = "demo01.py" __time__ = "2022/9/9 7:55" import github.com/') print(r.status_code) print(r.history) # 查看重定向的记录 print(r.next_request) # 获取到重定向以后的请求对象 resp = github.com/', follow_redirects=True) print(r.history) # 查看重定向记录 print(r.url) # 获取请求的url print(r.text) # 获取请求数据
3.7 超时和验证
HTTPX 默认包含所有网络操作的合理超时,这意味着如果连接没有正确建立,那么它应该总是引发错误而不是无限期挂起。
网络不活动的默认超时为五秒。您可以将值修改为或多或少严格:
github.com/', timeout=0.001) # 同时也可以禁止超时行为 github.com/', timeout=None)
HTTPX 支持基本和摘要 HTTP 身份验证。
要提供基本身份验证凭据,请将纯文本
str或bytes对象的 2 元组作为auth参数传递给请求函数:#!/usr/bin/python3 # -*- coding: UTF-8 -*- __author__ = "A.L.Kun" __file__ = "demo01.py" __time__ = "2022/9/9 7:55" import example.com", auth=("my_user", "password123")) # 验证方法一 auth = example.com", auth=auth)
二、 客户端
1、 特性
如果您来自 Requests,
example.com', headers=headers_, params=params_) # 这个参数结合了headers+headers_ , params+params_,但是只限于params和headers,对于所有其他参数,内部请求级别的值优先 print(r.request.url) print(r.request.headers['X-Auth']) print(r.request.headers['X-Custom']) # 优先级 with example.com', auth=('alice', 'ecila123')) _, _, auth = r.request.headers['Authorization'].partition(' ') import base64 print(base64.b64decode(auth)),请将代理 URL 传递给客户端…3、 其他配置
此外,
Client接受一些在请求级别不可用的配置选项。例如,
base_url允许您为所有传出请求添加 URL:#!/usr/bin/python3 # -*- coding: UTF-8 -*- __author__ = "A.L.Kun" __file__ = "demo01.py" __time__ = "2022/9/9 7:55" import localhost") as client: # base_url:指定app的根路由 r = client.get("/") # 获取根路由下的响应数据 print(r.text) assert r.status_code == 200 # 断言 assert r.text == "Hello World!"
对于一些更复杂的情况,您可能需要自定义 WSGI 传输。这使您可以:
- 通过设置检查 500 个错误响应而不是引发异常
raise_app_exceptions=False。script_name通过设置(WSGI)将 WSGI 应用程序挂载到子路径。remote_addr通过设置(WSGI)为请求使用给定的客户端地址。# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4". transport = testserver") as client: ...
5、 Request对象
为了最大限度地控制通过网络发送的内容,HTTPX 支持构建显式
Request实例:request = example.com")
要将
Request实例分派到网络,请创建一个Client实例并使用.send():with api.example.com") print(request.headers["X-Client-ID"]) # "ABC123" # Don't send the API key for this particular request. del request.headers["X-Api-Key"] response = client.send(request) ...
6、 钩子函数
HTTPX 允许您向客户端注册“事件挂钩”,每次发生特定类型的事件时都会调用这些挂钩。
目前有两个事件挂钩:
request- 在请求完全准备好之后,但在它被发送到网络之前调用。通过request实例。response- 在从网络获取响应之后但在返回给调用者之前调用。通过response实例。这些允许您安装客户端范围的功能,例如日志记录、监视或跟踪。
def log_request(request): print(f"Request event hook: {request.method} {request.url} - Waiting for response") def log_response(response): request = response.request print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}") client = speed.hetzner.de/100MB.bin" with example.org/', trust_env=False)
如果
NETRCenvironment 为空,HTTPX 会尝试使用默认文件。(~/.netrc,~/_netrc)改变
NETRC环境:import os os.environ["NETRC"] = "my_default_folder/.my_netrc"
.netrc 文件内容示例:
machine netrcexample.org login example-username password example-password ...
使用
Client实例时,trust_env应该在客户端本身上设置,而不是在请求方法上:client = localhost:8030
with localhost:8030") as client: ...
对于更高级的用例,传递一个 proxies
dict。例如,要将 HTTP 和 HTTPS 请求路由到 2 个不同的代理,分别位于localhost:8030和localhost:8031,传递一个dict代理 URL:proxies = { "": "localhost:8030", "": "localhost:8031", } with ": "username:password@localhost:8030", # ... }
2.3 路由
HTTPX 提供了细粒度的控制来决定哪些请求应该通过代理,哪些不应该。此过程称为代理路由。
该
proxies字典将 URL 模式(“代理键”)映射到代理 URL。HTTPX 将请求的 URL 与代理密钥进行匹配,以决定应该使用哪个代理(如果有)。从最具体的代理密钥(例如:)到最不具体的代理密钥(例如 )进行匹配。HTTPX 支持基于scheme、domain、port或这些的组合的路由代理。
2.3.1 通配符路由
通过代理路由所有内容…
proxies = { "all://": "localhost:8030", }
2.3.2 方案路由
通过一个代理路由 HTTP 请求,通过另一个代理路由 HTTPS 请求…
proxies = { "": "localhost:8030", "": "localhost:8031", }
2.3.3 域路由
# 代理域“example.com”上的所有请求,让其他请求通过... proxies = { "all://example.com": "localhost:8030", } # 代理域“example.com”上的 HTTP 请求,让 HTTPS 和其他请求通过... proxies = { "example.com": "localhost:8030", } # 将所有请求代理到“example.com”及其子域,让其他请求通过... proxies = { "all://*example.com": "localhost:8030", } # 代理所有请求到“example.com”的严格子域,让“example.com”等请求通过... proxies = { "all://*.example.com": "localhost:8030", }
2.3.4 端口路由
将端口 1234 上的 HTTPS 请求代理到“example.com”…
proxies = { "example.com:1234": "localhost:8030", }
代理端口 1234 上的所有请求…
proxies = { "all://*:1234": "localhost:8030", }
2.3.5 无代理支持
也可以定义不应通过代理路由的请求。
为此,请
None作为代理 URL 传递。例如…proxies = { # Route requests through a proxy by default... "all://": "localhost:8031", # Except those for "example.com". "all://example.com": None, }
3、 区别
3.1 前言
有细心的朋友就发现了,我前面不是说大部分参数
requests库一样么?怎么代理的有点不一样呢?注意啊,我的意思是大部分一样,这样便于大家理解和记忆。那么,这个代理的区别在哪呢?
我们来看一下
requests的代理的使用3.2 requests代理
使用
proxies任何请求方法的参数配置单个请求, 确保在存在环境代理的情况下使用代理:# 普通的代理 import requests proxies = { '10.10.1.10:3128', '10.10.1.10:1080', } requests.get('example.org', proxies=proxies) # 权限认证 proxies = {'user:pass@10.10.1.10:3128/'} # 给特定的方案和主机提供代理,这将匹配对给定方案和确切主机名的任何请求。 proxies = {'example.org': '10.10.1.10:5323'} # 其为一个简单的路由功能,进行简单的代理分发
3.3 总结
通过回顾
requests代理,相信大家就发现了区别了:在代理字典中,
python.org", proxy="proxy.com", proxy_auth=proxy_auth) as resp: print(resp.status)注意:
proxy_auth = aioyour_proxy_url:your_proxy_port'以及
scrapy框架的代理是这样使用的:def start_requests(self): for url in self.start_urls: return Request(url=url, callback=self.parse, headers={"User-Agent": "scrape web"}, meta={"proxy": "192.168.1.1:8050"
当然,如果大家有更好的看法的话,可以私信我哦!
同时, 如果您使用的是异步客户端,那么有一些 API 使用异步方法。 请求方法都是异步的,因此您应该 异步响应流方法是: 对于上下文块使用不实例的情况,可以通过使用 发送实例来进入“手动模式 import www.example.com/")
r = await client.send(req, stream=True)
return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))
使用这种“手动流模式”时,作为开发人员,您有责任确保 async def upload_bytes():
... # yield byte content
await client.post(url, content=upload_bytes())
AsyncIO 是 Python 的内置库 ,用于使用 async/await 语法编写并发代码。 import asyncio
import www.example.com/')
print(response)
asyncio.run(main())
Trio 是一个替代异步库,围绕结构化并发原则设计。 import www.example.com/')
print(response)
trio.run(main)
AnyIO 是一个异步网络和并发库,可在 import www.example.com/')
print(response)
anyio.run(main, backend='trio')
正如 对于一些更复杂的情况,您可能需要自定义 ASGI 传输。这使您可以: 例如: # Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",
# on port 123.
transport = testserver") as client:
...
其余更多内容,请到官方文档查看!www.python-httpx.org/ 到此这篇关于python新一代网络请求库之python-httpx库操作指南的文章就介绍到这了,更多相关新一代网络请求库python-httpx库内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!www.baidu.com")
print(r)
tasks = [test() for i in range(100)]
asyncio.run(asyncio.wait(tasks))
2、 API 差异
2.1 发出请求
response = await client.get(...)对以下所有内容使用样式:2.2 打开和关闭客户
async with www.example.com/') as response:
async for chunk in response.aiter_bytes():
...
Request”client.send(..., stream=True)。Response.aclose()最终调用它。不这样做会使连接保持打开状态,很可能导致资源泄漏。2.4 流式传输请求
3、 异步环境
3.1 asyncio
3.2 trio
trio必须安装该软件包才能使用 Trio 后端。3.3 anyio
asyncio或trio. 它与您选择的后端的本机库融合在一起(默认为asyncio)。4、 python_web
testserver") as client:
r = await client.get("/")
assert r.status_code == 200
assert r.text == "Hello World!"
raise_app_exceptions=False。root_path。client。总结
本文共计3723个文字,预计阅读时间需要15分钟。
目录
一、概述
1.简介
2.命令行模式
3.快速开始
3.1 get请求 3.2 post请求 3.3 响应处理 3.4 流式响应 3.5 cookie 3.6 重定向 3.7 超时和验证二、客户端
1.特性
2.发起请求
3.其他配置
目录
- 一、 概述
- 1、 简介
- 2、 命令行模式
- 3、 快速开始
- 3.1 get请求
- 3.2 post请求
- 3.3 响应处理
- 3.4 流式响应
- 3.5 cookie
- 3.6 重定向
- 3.7 超时和验证
- 二、 客户端
- 1、 特性
- 2、 发出请求
- 3、 其他配置
- 4、 python_web
- 5、 Request对象
- 6、 钩子函数
- 7、 进度条
- 8、 .netrc 支持
- 三、 代理
- 1、 简介
- 2、 使用方法
- 2.1 简单使用
- 2.2 验证
- 2.3 路由
- 3、 区别
- 3.1 前言
- 3.2 requests代理
- 3.3 总结
- 四、 异步客户端
- 1、 简介
- 2、 API 差异
- 2.1 发出请求
- 2.2 打开和关闭客户
- 2.3 流式响应
- 2.4 流式传输请求
- 3、 异步环境
- 3.1 asyncio
- 3.2 trio
- 3.3 anyio
- 4、 python_web
- 总结
一、 概述
1、 简介
HTTPX 是 Python 3 的全功能 HTTP 客户端,它提供同步和异步 API,并支持 HTTP/1.1 和 HTTP/2。
官方文档位置:www.python-www.baidu.com/s", params=params, headers=headers, cookies=None, proxies=None) # 和原来requests的使用方法类似 resp.encoding = resp.charset_encoding # 根据文档的编码还对文档进行编码 print(resp.text) # 获取数据信息
requests中的参数和www.baidu.com") if resp.status_code == www.example.com") as r: for data in r.iter_bytes(): # 流式传输响应的二进制内容 # for text in r.iter_text(): # 获取全部的文本内容 # for line in r.iter_lines(): # 逐行获取传输响应的文本内容 # for chunk in r.iter_raw(): # 获取编码前的原始数据 # if r.headers['Content-Length'] < TOO_LONG: # 有条件的加载内容 print(data)
注意:
如果您以任何这些方式使用流式响应,则response.contentandresponse.text属性将不可用3.5 cookie
#!/usr/bin/python3 # -*- coding: UTF-8 -*- __author__ = "A.L.Kun" __file__ = "demo01.py" __time__ = "2022/9/9 7:55" import github.com/') print(r.status_code) print(r.history) # 查看重定向的记录 print(r.next_request) # 获取到重定向以后的请求对象 resp = github.com/', follow_redirects=True) print(r.history) # 查看重定向记录 print(r.url) # 获取请求的url print(r.text) # 获取请求数据
3.7 超时和验证
HTTPX 默认包含所有网络操作的合理超时,这意味着如果连接没有正确建立,那么它应该总是引发错误而不是无限期挂起。
网络不活动的默认超时为五秒。您可以将值修改为或多或少严格:
github.com/', timeout=0.001) # 同时也可以禁止超时行为 github.com/', timeout=None)
HTTPX 支持基本和摘要 HTTP 身份验证。
要提供基本身份验证凭据,请将纯文本
str或bytes对象的 2 元组作为auth参数传递给请求函数:#!/usr/bin/python3 # -*- coding: UTF-8 -*- __author__ = "A.L.Kun" __file__ = "demo01.py" __time__ = "2022/9/9 7:55" import example.com", auth=("my_user", "password123")) # 验证方法一 auth = example.com", auth=auth)
二、 客户端
1、 特性
如果您来自 Requests,
example.com', headers=headers_, params=params_) # 这个参数结合了headers+headers_ , params+params_,但是只限于params和headers,对于所有其他参数,内部请求级别的值优先 print(r.request.url) print(r.request.headers['X-Auth']) print(r.request.headers['X-Custom']) # 优先级 with example.com', auth=('alice', 'ecila123')) _, _, auth = r.request.headers['Authorization'].partition(' ') import base64 print(base64.b64decode(auth)),请将代理 URL 传递给客户端…3、 其他配置
此外,
Client接受一些在请求级别不可用的配置选项。例如,
base_url允许您为所有传出请求添加 URL:#!/usr/bin/python3 # -*- coding: UTF-8 -*- __author__ = "A.L.Kun" __file__ = "demo01.py" __time__ = "2022/9/9 7:55" import localhost") as client: # base_url:指定app的根路由 r = client.get("/") # 获取根路由下的响应数据 print(r.text) assert r.status_code == 200 # 断言 assert r.text == "Hello World!"
对于一些更复杂的情况,您可能需要自定义 WSGI 传输。这使您可以:
- 通过设置检查 500 个错误响应而不是引发异常
raise_app_exceptions=False。script_name通过设置(WSGI)将 WSGI 应用程序挂载到子路径。remote_addr通过设置(WSGI)为请求使用给定的客户端地址。# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4". transport = testserver") as client: ...
5、 Request对象
为了最大限度地控制通过网络发送的内容,HTTPX 支持构建显式
Request实例:request = example.com")
要将
Request实例分派到网络,请创建一个Client实例并使用.send():with api.example.com") print(request.headers["X-Client-ID"]) # "ABC123" # Don't send the API key for this particular request. del request.headers["X-Api-Key"] response = client.send(request) ...
6、 钩子函数
HTTPX 允许您向客户端注册“事件挂钩”,每次发生特定类型的事件时都会调用这些挂钩。
目前有两个事件挂钩:
request- 在请求完全准备好之后,但在它被发送到网络之前调用。通过request实例。response- 在从网络获取响应之后但在返回给调用者之前调用。通过response实例。这些允许您安装客户端范围的功能,例如日志记录、监视或跟踪。
def log_request(request): print(f"Request event hook: {request.method} {request.url} - Waiting for response") def log_response(response): request = response.request print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}") client = speed.hetzner.de/100MB.bin" with example.org/', trust_env=False)
如果
NETRCenvironment 为空,HTTPX 会尝试使用默认文件。(~/.netrc,~/_netrc)改变
NETRC环境:import os os.environ["NETRC"] = "my_default_folder/.my_netrc"
.netrc 文件内容示例:
machine netrcexample.org login example-username password example-password ...
使用
Client实例时,trust_env应该在客户端本身上设置,而不是在请求方法上:client = localhost:8030
with localhost:8030") as client: ...
对于更高级的用例,传递一个 proxies
dict。例如,要将 HTTP 和 HTTPS 请求路由到 2 个不同的代理,分别位于localhost:8030和localhost:8031,传递一个dict代理 URL:proxies = { "": "localhost:8030", "": "localhost:8031", } with ": "username:password@localhost:8030", # ... }
2.3 路由
HTTPX 提供了细粒度的控制来决定哪些请求应该通过代理,哪些不应该。此过程称为代理路由。
该
proxies字典将 URL 模式(“代理键”)映射到代理 URL。HTTPX 将请求的 URL 与代理密钥进行匹配,以决定应该使用哪个代理(如果有)。从最具体的代理密钥(例如:)到最不具体的代理密钥(例如 )进行匹配。HTTPX 支持基于scheme、domain、port或这些的组合的路由代理。
2.3.1 通配符路由
通过代理路由所有内容…
proxies = { "all://": "localhost:8030", }
2.3.2 方案路由
通过一个代理路由 HTTP 请求,通过另一个代理路由 HTTPS 请求…
proxies = { "": "localhost:8030", "": "localhost:8031", }
2.3.3 域路由
# 代理域“example.com”上的所有请求,让其他请求通过... proxies = { "all://example.com": "localhost:8030", } # 代理域“example.com”上的 HTTP 请求,让 HTTPS 和其他请求通过... proxies = { "example.com": "localhost:8030", } # 将所有请求代理到“example.com”及其子域,让其他请求通过... proxies = { "all://*example.com": "localhost:8030", } # 代理所有请求到“example.com”的严格子域,让“example.com”等请求通过... proxies = { "all://*.example.com": "localhost:8030", }
2.3.4 端口路由
将端口 1234 上的 HTTPS 请求代理到“example.com”…
proxies = { "example.com:1234": "localhost:8030", }
代理端口 1234 上的所有请求…
proxies = { "all://*:1234": "localhost:8030", }
2.3.5 无代理支持
也可以定义不应通过代理路由的请求。
为此,请
None作为代理 URL 传递。例如…proxies = { # Route requests through a proxy by default... "all://": "localhost:8031", # Except those for "example.com". "all://example.com": None, }
3、 区别
3.1 前言
有细心的朋友就发现了,我前面不是说大部分参数
requests库一样么?怎么代理的有点不一样呢?注意啊,我的意思是大部分一样,这样便于大家理解和记忆。那么,这个代理的区别在哪呢?
我们来看一下
requests的代理的使用3.2 requests代理
使用
proxies任何请求方法的参数配置单个请求, 确保在存在环境代理的情况下使用代理:# 普通的代理 import requests proxies = { '10.10.1.10:3128', '10.10.1.10:1080', } requests.get('example.org', proxies=proxies) # 权限认证 proxies = {'user:pass@10.10.1.10:3128/'} # 给特定的方案和主机提供代理,这将匹配对给定方案和确切主机名的任何请求。 proxies = {'example.org': '10.10.1.10:5323'} # 其为一个简单的路由功能,进行简单的代理分发
3.3 总结
通过回顾
requests代理,相信大家就发现了区别了:在代理字典中,
python.org", proxy="proxy.com", proxy_auth=proxy_auth) as resp: print(resp.status)注意:
proxy_auth = aioyour_proxy_url:your_proxy_port'以及
scrapy框架的代理是这样使用的:def start_requests(self): for url in self.start_urls: return Request(url=url, callback=self.parse, headers={"User-Agent": "scrape web"}, meta={"proxy": "192.168.1.1:8050"
当然,如果大家有更好的看法的话,可以私信我哦!
同时, 如果您使用的是异步客户端,那么有一些 API 使用异步方法。 请求方法都是异步的,因此您应该 异步响应流方法是: 对于上下文块使用不实例的情况,可以通过使用 发送实例来进入“手动模式 import www.example.com/")
r = await client.send(req, stream=True)
return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))
使用这种“手动流模式”时,作为开发人员,您有责任确保 async def upload_bytes():
... # yield byte content
await client.post(url, content=upload_bytes())
AsyncIO 是 Python 的内置库 ,用于使用 async/await 语法编写并发代码。 import asyncio
import www.example.com/')
print(response)
asyncio.run(main())
Trio 是一个替代异步库,围绕结构化并发原则设计。 import www.example.com/')
print(response)
trio.run(main)
AnyIO 是一个异步网络和并发库,可在 import www.example.com/')
print(response)
anyio.run(main, backend='trio')
正如 对于一些更复杂的情况,您可能需要自定义 ASGI 传输。这使您可以: 例如: # Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",
# on port 123.
transport = testserver") as client:
...
其余更多内容,请到官方文档查看!www.python-httpx.org/ 到此这篇关于python新一代网络请求库之python-httpx库操作指南的文章就介绍到这了,更多相关新一代网络请求库python-httpx库内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!www.baidu.com")
print(r)
tasks = [test() for i in range(100)]
asyncio.run(asyncio.wait(tasks))
2、 API 差异
2.1 发出请求
response = await client.get(...)对以下所有内容使用样式:2.2 打开和关闭客户
async with www.example.com/') as response:
async for chunk in response.aiter_bytes():
...
Request”client.send(..., stream=True)。Response.aclose()最终调用它。不这样做会使连接保持打开状态,很可能导致资源泄漏。2.4 流式传输请求
3、 异步环境
3.1 asyncio
3.2 trio
trio必须安装该软件包才能使用 Trio 后端。3.3 anyio
asyncio或trio. 它与您选择的后端的本机库融合在一起(默认为asyncio)。4、 python_web
testserver") as client:
r = await client.get("/")
assert r.status_code == 200
assert r.text == "Hello World!"
raise_app_exceptions=False。root_path。client。总结

