我使用Django 2.x和Django REST框架。
我使用django-oauth-toolkit来启用OAuth2身份验证和用于登录的django-rest-auth以及用于用户注册的django-allauth。
当用户成功注册时,我希望在响应中生成访问令牌。为此,我使用自定义注册视图。
为此,我创建了一个函数实用程序,如
def generate_token(request, user):
# Get OAuth application to use
application_: Application = Application.objects.filter(
client_type=Application.CLIENT_CONFIDENTIAL,
authorization_grant_type=Application.GRANT_PASSWORD
).first()
if not application_:
raise Exception('No OAuth2 Application is setup')
auth_data = {
'username': user.username,
'password': password,
'grant_type': 'password',
'client_id': application_.client_id,
'client_secret': application_.client_secret
}
if request.data:
mutable = request.data._mutable
request.data._mutable = True
request.data.update(auth_data)
request.data._mutable = mutable
if request.POST:
mutable = request.POST._mutable
request.POST._mutable = True
request.POST.update(auth_data)
request.POST._mutable = mutable
return TokenView().create_token_response(request=request)当端点被Postman击中时,它工作正常,request.data具有_mutable属性。
但是当它被角度应用击中时,就会产生误差。
'dict' object has no attribute '_mutable'以及mutable = request.data._mutable的错误点
为什么某些请求缺少_mutable?
编辑2:请求头
Postman发送的请求头是
Content-Type:"application/json"
Accept:"application/json, text/plain, /"
User-Agent:"PostmanRuntime/7.15.2"
Cache-Control:"no-cache"
Postman-Token:"b4461728-a6a9-48da-a4fa-3894920b5484"
Host:"api.staging.scanova.io"
Cookie:"messages="660481c3ce8c48b1884641ffdec0a3f701cdc9cf$..."; csrftoken=tNa6o6RDkEUTBti1cDJCvgV5oLG84qczgADeDfSY7hROsLP6cmhIgQKaamPQU7Xy; sessionid=r0l8kh58n8i14quyemj60ur6i59uhy1i"
Accept-Encoding:"gzip, deflate"
Content-Length:635
Connection:"keep-alive"来自角的请求标头是
Accept: application/json, text/plain, */*
Authorization: false false
Content-Type: application/json
Origin: https://localhost:4200
Referer: https://localhost:4200/auth/register
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36编辑3:请求类型
从端点调用的主要视图是CreateAPIView。从此视图调用generate_token,该视图使用TokenView生成访问令牌。TokenView使用Django的通用View。
发布于 2020-06-04 08:56:04
对于后人(尽管这个问题很老):
似乎django/DRF以一种不同的方式对待multipart/form-data和application/json内容类型,从而引发问题。
因此,即使使用相同的端点(视图集),并且取决于表单是作为多部分发送还是以app/json - request.data的形式发送,也将是一个不同的对象。
在一种情况下,它将是“正常”的,而在另一种情况下,它将是QueryDict类型的。因此,为了使用hacky _mutable on/off,需要进行类似于此的额外检查:
...
# one can also use:
# if 'multipart/form-data' in request.META.get('CONTENT_TYPE'):
# instead of the condition below
if isinstance(request.data, QueryDict):
auth_data = json.dumps(auth_data) # <----- QueryDict expects string values
request.POST._mutable = True # <----- mutable needs to be modified on POST and not on data
request.data.update(auth_data)
request.POST._mutable = False
...发布于 2020-06-25 20:43:26
我使用了(request.POST._mutable = True),这种方式对我不起作用。然后,我在一个新变量中复制了request.POST,并且在我的整个代码中使用了新变量,这样可以很好地工作。
https://stackoverflow.com/questions/57285037
复制相似问题