【问题标题】:How to use OAuth1 with aiohttp如何将 OAuth1 与 aiohttp 一起使用
【发布时间】:2021-08-19 13:21:30
【问题描述】:

我已经使用常规的requests 模块成功实现了 OAuth1,如下所示:

import requests
from requests_oauthlib import OAuth1


oauth = OAuth1(client_key=oauth_cred["consumer_key"], client_secret=oauth_cred["consumer_secret"], resource_owner_key=oauth_cred["access_token"], resource_owner_secret=oauth_cred["access_token_secret"])

session = requests.Session()

session.auth = oauth

当尝试将其转移到aiohttp 时,我无法让它工作。用aiohttp.ClientSession() 代替requests.Session() 得到{'errors': [{'code': 215, 'message': 'Bad Authentication data.'}]}

我在互联网上查看了一些解决方案,例如https://github.com/klen/aioauth-client,但这似乎是一种不同的方法。我只是希望它的功能与上面的示例完全相同。

我试过了

import aiohttp
from aioauth_client import TwitterClient


oauth = TwitterClient(consumer_key=oauth_cred["consumer_key"], consumer_secret=oauth_cred["consumer_secret"], oauth_token=oauth_cred["access_token"], oauth_token_secret=oauth_cred["access_token_secret"])

session = aiohttp.ClientSession()

session.auth = oauth

但我遇到了同样的错误。

我怎样才能让它工作?

【问题讨论】:

标签: python http asynchronous oauth aiohttp


【解决方案1】:

使用oauthlib

import oauthlib.oauth1, aiohttp, asyncio

async def main():
    # Create the Client. This can be reused for multiple requests.
    client = oauthlib.oauth1.Client(
        client_key = oauth_cred['consumer_key'],
        client_secret = oauth_cred['consumer_secret'],
        resource_owner_key = oauth_cred['access_token'],
        resource_owner_secret = oauth_cred['access_token_secret']
    )

    # Define your request. In my code I'm POSTing so that's what I have here,
    # but if you're doing something different you'll need to change this a bit.
    uri = '...'
    http_method = 'POST'
    body = '...'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    # Sign the request data. This needs to be called for each request you make.
    uri,headers,body = client.sign(
        uri = uri,
        http_method = http_method,
        body = body,
        headers = headers
    )

    # Make your request with the signed data.
    async with aiohttp.ClientSession() as session:
        async with session.post(uri, data=body, headers=headers, raise_for_status=True) as r:
            ...

# asyncio.run has a bug on Windows in Python 3.8 https://bugs.python.org/issue39232
#asyncio.run(main())
asyncio.get_event_loop().run_until_complete(main())

oauthlib.oauth1.Client 构造函数还需要更多参数,如果您需要它们(对于基本用途,您不需要)。 official documentation 不是很彻底,但doc comment on the method itself 相当不错。

doc comment on the Client.sign method 有更多关于它所采用的参数的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2023-03-11
    • 2021-01-02
    相关资源
    最近更新 更多