python - 设置 `aiohttp.ClientSession` 默认参数

标签 python python-requests aiohttp

我正在从 requests 迁移到 aiohttp,并且我之前使用过 requests.Session.params 来设置默认查询参数对于 session 中发出的每个请求。

如何正确实现与 aiohttp.ClientSession 相同的效果?

我已经尝试过:

  • 子类化 aiohttp.ClientSession 以覆盖 _request 方法。 但这会引发DepcrecationWarning:不鼓励从 ClientSession 继承
  • 子类化 aiohttp.ClientResponse 以覆盖 __init__ 方法,并更新其中的 params,然后将子类传递给 aiohttp .ClientSession。 这是行不通的,因为我需要在 session 的基础上定义自定义参数(并且是可变的)。

编辑:我希望代码的外观示例,以供澄清:

from aiohttp import ClientSession

session = ClientSession()
# Do something fancy here, or in the initialization of `ClientSession`, so that
# `default_params` is set as the default parameters for each request
default_params = dict(some_parameter="a value")

async with session.get("http://httpbin.org/get") as resp:
    j = await resp.json()
assert j["args"] == default_params

# Do something fancy here, where we change the default parameters
default_params.update(some_parameter="another value")

async with session.get("http://httpbin.org/get") as resp:
    j = await resp.json()
assert j["args"] == default_params

最佳答案

Custom Request Headers
If you need to add HTTP headers to a request, pass them in a dict to the headers parameter.

它在文档 http://docs.aiohttp.org/en/stable/client_advanced.html#custom-request-headers

url = 'http://example.com/image'
payload = b'GIF89a\x01\x00\x01\x00\x00\xff\x00,\x00\x00'
          b'\x00\x00\x01\x00\x01\x00\x00\x02\x00;'
headers = {'content-type': 'image/gif'}

await session.post(url,
                   data=payload,
                   headers=headers)

要添加默认参数和稍后的自定义参数,您可以这样做,而无需进行任何子类化( based on this part of documentation )

import asyncio
from aiohttp import ClientSession

async def fetch(url, params, loop):
    async with ClientSession() as session:
        async with session.get(url, params=params) as response:
            print(response.request_info)
            print(str(response.url))
            print(response.status)
            args = await response.json()
            resp_text = await response.text()
            print('args:', args['args'])
            print(resp_text)

def main(url, params):
    loop = asyncio.get_event_loop()
    return loop.run_until_complete(fetch(url, params, loop))

if __name__ == '__main__':
    url = 'http://httpbin.org/get'
    default_params = {'param1': 1, 'param2': 2}
    main(url, default_params)
    new_params = {'some_parameter': 'a value', 'other_parameter': 'another value'}
    default_params.update(new_params)
    main(url, default_params)

结果:

RequestInfo(url=URL('http://httpbin.org/get?param1=1&param2=2'), method='GET', headers=<CIMultiDict('Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'Python/3.5 aiohttp/3.4.4')>, real_url=URL('http://httpbin.org/get?param1=1&param2=2'))
  http://httpbin.org/get?param1=1&param2=2
  200
  args: {'param1': '1', 'param2': '2'}
  {
    "args": {
      "param1": "1", 
      "param2": "2"
    }, 
    "headers": {
      "Accept": "*/*", 
      "Accept-Encoding": "gzip, deflate", 
      "Connection": "close", 
      "Host": "httpbin.org", 
      "User-Agent": "Python/3.5 aiohttp/3.4.4"
    }, 
    "origin": "10.10.10.10", 
    "url": "http://httpbin.org/get?param1=1&param2=2"
  }

  RequestInfo(url=URL('http://httpbin.org/get?param1=1&param2=2&some_parameter=a+value&other_parameter=another+value'), method='GET', headers=<CIMultiDict('Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'Python/3.5 aiohttp/3.4.4')>, real_url=URL('http://httpbin.org/get?param1=1&param2=2&some_parameter=a+value&other_parameter=another+value'))
  http://httpbin.org/get?param1=1&param2=2&some_parameter=a+value&other_parameter=another+value
  200
  args: {'other_parameter': 'another value', 'param1': '1', 'param2': '2', 'some_parameter': 'a value'}
  {
    "args": {
      "other_parameter": "another value", 
      "param1": "1", 
      "param2": "2", 
      "some_parameter": "a value"
    }, 
    "headers": {
      "Accept": "*/*", 
      "Accept-Encoding": "gzip, deflate", 
      "Connection": "close", 
      "Host": "httpbin.org", 
      "User-Agent": "Python/3.5 aiohttp/3.4.4"
    }, 
    "origin": "10.10.10.10", 
    "url": "http://httpbin.org/get?param1=1&param2=2&some_parameter=a+value&other_parameter=another+value"
  }

关于python - 设置 `aiohttp.ClientSession` 默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52563238/

相关文章:

python - 开发服务器 HTTP 错误 403 : Forbidden

python - 使用 python requests 模块在 Github 中创建经过身份验证的 session

python - 类型错误 : 'data' is an invalid keyword argument for this function

python - 为什么 Python 的 `requests` 拒绝我的浏览器接受的 SSL 证书

python - 异步: why isn't it non-blocking by default

python - discord.py 中的 client.wait_for 中的“检查未定义”

python - 序列化器无法添加额外数据

当在函数内的 if 语句的条件中使用全局变量时,Python 抛出 UnboundLocalError

python - 学习异步 : "coroutine was never awaited" warning error

python - aiohttp + uvloop 并行 HTTP 请求比没有 uvloop 慢