请求.POST 在自定义中间件 - django 1.11.9 中更新后返回旧值



我正在使用 django 1.11.9

我想将client_id和client_secret添加到 django POST 请求中。

以下是我的 middleware.py 文件的外观:

class LoginMiddleware(object):
def __init__(self, get_response):
    self.get_response = get_response
    # One-time configuration and initialization.
def __call__(self, request):
    # auth_header = get_authorization_header(request)
    # Code to be executed for each request before
    # the view (and later middleware) are called.
    #Add Django authentication app client data to the request
    request.POST = request.POST.copy()
    request.POST['client_id'] = '12345678'
    request.POST['client_secret'] = '12345678'
    response = self.get_response(request)
    # Code to be executed for each request/response after
    # the view is called.
    return response

当我使用调试器检查中间件时,中间件正在成功处理。当视图被称为"client_id"和"client_secret"字段时,请求中缺少"字段。

经过一些实验,我发现请求没有得到更新,当在不同的视图中调用它时,它会返回旧值。

我后来在rest_framework_social_oauth2中使用请求。这就是"client_id"和"client_secret"消失的时候。

class ConvertTokenView(CsrfExemptMixin, OAuthLibMixin, APIView):
"""
Implements an endpoint to convert a provider token to an access token
The endpoint is used in the following flows:
* Authorization code
* Client credentials
"""
server_class = SocialTokenServer
validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS
oauthlib_backend_class = KeepRequestCore
permission_classes = (permissions.AllowAny,)
def post(self, request, *args, **kwargs):
    import pdb ; pdb.set_trace()
    # Use the rest framework `.data` to fake the post body of the django request.
    request._request.POST = request._request.POST.copy()
    for key, value in request.data.items():
        request._request.POST[key] = value
    url, headers, body, status = self.create_token_response(request._request)
    response = Response(data=json.loads(body), status=status)
    for k, v in headers.items():
        response[k] = v
    return response

我需要将client_id和client_secret添加到请求正文中,以便rest_framework_social_oauth2以后可以使用它。

可能是什么问题?如何正确更新请求?

当您处理request和处理请求时,您必须实现process_request方法,因此结果将是这样的:

class LoginMiddleware(object):
    def process_request(self, request):
        request.session['client_id'] = '12345678'

然后在您看来:

def your_view(request):
    client_id = request.session['client_id']

相关内容

  • 没有找到相关文章

最新更新