我在Django应用中覆盖了ModelBackend
。我覆盖的模型后端要求标头包含在请求中以登录用户。
HEADER = 'testing'
class TestingModelBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
testing_header_value = None
if request is not None and request.META is not None:
testing_header_value = request.META.get(HEADER, None)
if username is None:
username = kwargs.get(User.USERNAME_FIELD)
try:
user = User.objects.get_by_natural_key(username, testing_header_value)
except User.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
User().set_password(password)
else:
# now validate password and whether the user is active
if user.check_password(password) and self.user_can_authenticate(user):
return user
这在非测试方案中非常有效。但是,当我进行测试时,遇到了与测试客户端传递标头的问题。
Django测试客户端有一个login方法,但是它没有通过request
when authenticating,这意味着我的模型后端无法正常运行-我无法通过我需要的标题。请注意,authenticate
函数中的参数之一是当前请求。
我看到我可以使用force_login
,但这似乎有点不客气。正确的方法是什么?我怀疑最好继承默认测试客户端的子类并覆盖login
方法可能是最好的方法,但是我不确定。
答案 0 :(得分:1)
我相信force_login()
是您的最佳选择。