Python Django-要解压缩的值太多(应为2个)
我正在尝试创建一个自定义后端,其中用户使用私钥和密钥查看我在Django Rest框架中创建的API端点。我已经知道这在安全性方面不是最好的,但是由于端点仅用于查看数据(它只有GET方法),所以这里没什么大不了的 这是我的密码:Python Django-要解压缩的值太多(应为2个),python,django,Python,Django,我正在尝试创建一个自定义后端,其中用户使用私钥和密钥查看我在Django Rest框架中创建的API端点。我已经知道这在安全性方面不是最好的,但是由于端点仅用于查看数据(它只有GET方法),所以这里没什么大不了的 这是我的密码: class TokenMiddleware(AuthenticationMiddleware): def process_request(self, request): try: token = request.GET[T
class TokenMiddleware(AuthenticationMiddleware):
def process_request(self, request):
try:
token = request.GET[TOKEN_QUERY_PUBLIC]
secret = request.GET[TOKEN_QUERY_SECRET]
except KeyError:
raise ValidationError(detail="Missing parameter in auth")
user = auth.authenticate(request, token=token, secret=secret)
if user:
# The token is valid. Save the user to the request and session.
request.user = user
auth.login(request, user)
else:
raise ValidationError(detail="AUTH FAILED")
class TokenBackend(ModelBackend):
def authenticate(self, request, token=None, secret=None):
if not token:
return None
try:
publicQuery = User.objects.get(api_keys__public=token)
if publicQuery != None:
privateQuery = Api_keys.objects.get(public=token, secret=secret)
if privateQuery.secret == secret:
return User.objects.get(username=publicQuery)
else:
return None
else:
return None
except User.DoesNotExist:
# A user with that token does not exist
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
下面是Api\u密钥
模型:
class Api_keys(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
public = models.CharField(max_length=30, blank=True)
secret = models.CharField(max_length=30, blank=True)
此代码的问题在于每次尝试进行身份验证时,都会出现以下错误:
too many values to unpack (expected 2)
更多详情:
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\request.py", line 220, in user
self._authenticate()
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\request.py", line 380, in _authenticate
self.user, self.auth = user_auth_tuple
我的进口:
from django.contrib import auth
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.contrib.auth.middleware import AuthenticationMiddleware
from rest_framework.exceptions import ValidationError
from api.models import Api_keys
问题应该出现在第
行auth.login(请求,用户)
之后,直到我看到返回了一个有效的用户。感谢您的任何帮助 “太多值无法解包”异常,该异常表示您正在尝试解包一个元组,但该元组相对于目标变量的数量有太多值,您的目标和源元组不是sameCheck。DRF auth后端与普通djangoauth\u后端不同。它们应该返回一个用户/令牌对,而不仅仅是用户!多谢各位!那么,在这种情况下,我需要向auth.login传递什么?@undoos问题是,如果我不传递身份验证请求,那么身份验证将不会执行像您这样混淆django的authenticate()
与djangorest的authenticate()
的任务。你能把进口的东西也寄出去吗