我正在使用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使用。
可能是什么问题?如何正确更新请求?
答案 0 :(得分:0)
当您使用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']