强化版的 requests_2

HTTPX 特点:

+ 和使用 requests 一样方便,requests 有的它都有

+ 加入 HTTP/1.1 和 HTTP/2 的支持。

+ 能够直接向 WSGI 应用程序或 ASGI 应用程序发出请求。

+ 到处都有严格的超时设置

+ 全类型注释

+ 100% 的测试覆盖率

安装

python3 -m pip install httpx

如果需要对 HTTP/2 支持,我们需要额外安装一个库

python3 -m pip install httpx[http2]

使用示例

import httpx
r = httpx.get('https://www.example.org/')
r.text
r.content
r.json()
r.status_code

 

基本的用法直接导包然后 get 就行了。其他的和 requests 的使用类似

r = httpx.put('https://httpbin.org/put', data={'key': 'value'})
r = httpx.delete('https://httpbin.org/delete')
r = httpx.head('https://httpbin.org/get')
r = httpx.options('https://httpbin.org/get')

 

如果需要做一个爬虫项目,里面涉及到 Cookie 的传递这时候再这样就不行了,
httpx 有个 requests 的 Session 类型的使用方法.

import httpx
client = httpx.Client() #类似requests.Session()
try:
    do somting
finally:
    client.close() #关闭连接池

 

更优雅的方法就是使用 with 上下文管理器的形式

with httpx.Client() as client:
    headers = {'X-Custom': 'value'}
    r = client.get('https://example.com', headers=headers)

 

这里有个地方需要强调下 Client 和 get 里面都可以添加 headers,
最后这两个地方的 headers 可以合并到请求里,官方的例子

>>> headers = {'X-Auth': 'from-client'}
>>> params = {'client_id': 'client1'}
>>> with httpx.Client(headers=headers, params=params) as client:
...     headers = {'X-Custom': 'from-request'}
...     params = {'request_id': 'request1'}
...     r = client.get('https://example.com', headers=headers, params=params)
...
>>> r.request.url
URL('https://example.com?client_id=client1&request_id=request1')
>>> r.request.headers['X-Auth']
'from-client'
>>> r.request.headers['X-Custom']
'from-request'

接下来说下大家比较关心的一点代理的使用,需要注意的是 httpx 的代理只能在 httpx.Client 创建 Client 的实例的时候使用,client.get 的时候没这个参数。
有意思的是它这个代理可以指定规则,限制哪些请求使用代理哪些不使用,来个官方的例子

允许所有请求都走代理

proxies = {
    "all://": "http://localhost:0000",
}

如果字典的值为 None 则表示不使用代理。

不同的协议走不用的代理

proxies = {
    "http://": "http://localhost:8030",
    "https://": "http://localhost:8031",
}

http 走 8030 的代理,https 走 8031 的代理,这里要注意和用 requests 使用代理的区别 requests 是下面这样用的

proxies = {
    "http": "http://localhost:8030",
    "https": "http://localhost:8030",
}

综合使用

你还可以配置多个规则像下面这

proxies = {
    # Route all traffic through a proxy by default...
    "all://": "http://localhost:8030",
    # But don't use proxies for HTTPS requests to "domain.io"...
    "https://domain.io": None,
    # And use another proxy for requests to "example.com" and its subdomains...
    "all://*example.com": "http://localhost:8031",
    # And yet another proxy if HTTP is used,
    # and the "internal" subdomain on port 5550 is requested...
    "http://internal.example.com:5550": "http://localhost:8032",
}

代理就这些,下面看看它的链接池的问题
你可以使用 Client 的关键字参数 limits 来控制连接池的大小。它需要以下实例httpx.Limits 来定义:

  • max_keepalive,允许的保持活动连接数或 None 始终允许。(预设10)

  • max_connections,允许的最大连接数或 None 无限制。(默认为100)

limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)
client = httpx.Client(limits=limits)

httpx 之异步请求

我们先看在 aiohttp 中是如何创建并发送请求的

import aiohttp
import asyncio

async def main():
    async with aiohttp.ClientSession() as client:
         async with client.get('http://httpbin.org/get') as resp:
              assert resp.status == 200
              html= await resp.text()
              print(html)

我们需要使用两个 async with 来完成一个请求,然后我们看看 httpx 怎么实现的呢

async with httpx.AsyncClient() as client:
    resp = await client.get('http://httpbin.org/get')
    assert resp.status_code == 200
    html = resp.text

 

posted @ 2021-11-25 14:08  Mr-刘  阅读(73)  评论(0编辑  收藏  举报