首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么django-allauth方法似乎无法正确调用Reddit api?

为什么django-allauth方法似乎无法正确调用Reddit api?
EN

Stack Overflow用户
提问于 2019-04-24 23:30:04
回答 1查看 263关注 0票数 1

我正在通过Reddit为一个使用django-rest-authdjango-allauth的应用程序设置社交身份验证。我的问题是,当我尝试使用django-rest-auth端点检索访问令牌时,django-allauth会从Reddit返回429错误。但是,当我尝试使用Reddit api文档中列出的所有内容直接调用Reddit api时,我能够成功地执行此操作。我希望能够通过django-rest-auth进行此调用,这样我就可以从它与Django集成的方式中受益。

我已经对django-rest-auth文档中列出的每个设置进行了四次检查,包括Reddit返回429错误的常见原因: redirect_uri和settings.py中的User-Agent值。我甚至使用了包嗅探器来拦截HTTP请求,当然,这是不起作用的,因为它是加密的。

下面是rest-auth urls:

代码语言:javascript
复制
path('rest-auth/',include('rest_auth.urls')),
path('rest-auth/registration/',include('rest_auth.registration.urls')),
path('rest-auth/reddit/', views.RedditLogin.as_view(),name='reddit_login'),
            ]

以下是views.py中的相关视图:

代码语言:javascript
复制
#imports for social authentication
from allauth.socialaccount.providers.reddit.views import RedditAdapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from rest_auth.registration.views import SocialLoginView

class RedditLogin(SocialLoginView):
    adapter_class = RedditAdapter
    callback_url = 'http://localhost:8080/register'
    client_class = OAuth2Client

以下是settings.py中的相关设置:

代码语言:javascript
复制
SOCIALACCOUNT_PROVIDERS = {
    'reddit': {
        'AUTH_PARAMS': {'duration':'permanent'},
        'SCOPE': [ 'identity','submit'],
        'USER_AGENT': 'web:applicationnamehere:v1.0 (by /u/myusername)',

        }

}

下面是通过/rest-auth/reddit/端点使用django-allauth和django-rest-auth获取访问令牌的结果:

代码语言:javascript
复制
Traceback:

File "/usr/local/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
  45.         return bound_method(*args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  76.             return view(request, *args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/rest_auth/views.py" in dispatch
  49.         return super(LoginView, self).dispatch(*args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
  483.             response = self.handle_exception(exc)

File "/usr/local/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)

File "/usr/local/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)

File "/usr/local/lib/python3.5/site-packages/rest_auth/views.py" in post
  93.         self.serializer.is_valid(raise_exception=True)

File "/usr/local/lib/python3.5/site-packages/rest_framework/serializers.py" in is_valid
  236.                 self._validated_data = self.run_validation(self.initial_data)

File "/usr/local/lib/python3.5/site-packages/rest_framework/serializers.py" in run_validation
  437.             value = self.validate(value)

File "/usr/local/lib/python3.5/site-packages/rest_auth/registration/serializers.py" in validate
  112.             token = client.get_access_token(code)

File "/usr/local/lib/python3.5/site-packages/allauth/socialaccount/providers/oauth2/client.py" in get_access_token
  85.                               % resp.content)

Exception Type: OAuth2Error at /api/v1/rest-auth/reddit/
Exception Value: Error retrieving access token: b'{"message": "Too Many Requests", "error": 429}'

我期望django-allauth的'OAuth2Client‘类(see here)中定义的'get_access_token’方法返回来自Reddit的令牌,而不是来自Reddit的速率限制错误。

在我做了所有的工作来确保我的设置是正确的,并用相同的数据手动重现了对reddit的api调用(这是成功的)之后,我能想到的唯一一件事是django-allauth正在以一种Reddit拒绝的方式形成api请求。如何解决外部库形成POST请求的问题?也许我可以直接重写'get_access_token‘方法?或者我只是完全错过了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-29 22:49:40

我在这里遇到的问题可以通过对django-allauth中的OAuth2Client.get_access_token方法进行故障排除来解决。该方法可以使用monkey patchingpython's debugger进行故障排除。我最终使用猴子补丁覆盖了get_access_token方法views.py:

代码语言:javascript
复制
#imports for social authentication
from allauth.socialaccount.providers.reddit.views import RedditAdapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from rest_auth.registration.views import SocialLoginView

class RedditLogin(SocialLoginView):
    adapter_class = RedditAdapter
    callback_url = 'http://localhost:8080/register'
    OAuth2Client.get_access_token = custom_get_token
    client_class = OAuth2Client

使用python's logging发现django发送给reddit的请求的头和正文是不正确的。主要问题似乎是使用了不正确的用户代理头。Reddit requires a very specific user agent。我的解决方案是覆盖get_access_token方法,如下所示:

代码语言:javascript
复制
def custom_get_token(self, code):

    # The following code uses the 'requests' library retrieve the token directly.
    data = {
        'redirect_uri': self.callback_url,
        'grant_type': 'authorization_code',
        'code': code}
    # This code should generate the basicauth object that can be passed to the requests parameters.
    auth = requests.auth.HTTPBasicAuth(
        self.consumer_key,
        self.consumer_secret
    )
    # The User-Agent header has to be overridden in order for things to work, which wasn't happening before...
    headers = {
        'User-Agent': 'web:myapplication:v0.0 (by /u/reddituser)'
    }

    self._strip_empty_keys(data)
    url = 'https://www.reddit.com/api/v1/access_token' # This is also self.access_token_url
    access_token_method = 'POST' # I set this just to make sure

    resp = requests.request(
        access_token_method,
        url,
        data=data,
        headers=headers,
        auth=auth
    )

    access_token = None

    if resp.status_code in [200, 201]:
        # Weibo sends json via 'text/plain;charset=UTF-8'
        if (resp.headers['content-type'].split(
                ';')[0] == 'application/json' or resp.text[:2] == '{"'):
            access_token = resp.json()
        else:
            access_token = dict(parse_qsl(resp.text))
    if not access_token or 'access_token' not in access_token:
        raise OAuth2Error('Error retrieving access token: %s'
                          % resp.content)
    return access_token

请注意,此解决方案是专门为在Reddit中使用django-allauth而设计的。对于其他社交提供商,此方法可能需要进行调整。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55833707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档