[英]Django + Tastypie - user_logged_in signal doesn't work
我有一个Tastypie ModelResource
定义了可以按预期工作的各种端点。
现在,我已经将此ModelResource
配置为具有BasicAuthentication
:
class Meta:
authentication = BasicAuthentication()
我已经通过Django Admin Interface定义了一些测试用户。
根据Django 1.7文档 ,我创建了一个signals.py
,其中注册了一些测试信号:
from django.core.signals import request_finished
from django.contrib.auth.signals import user_logged_in
from django.dispatch import receiver
@receiver(user_logged_in)
def on_login(sender, request, user, **kwargs):
print('******* LOGIN DETECTED *********')
@receiver(request_finished)
def on_request_finished(sender, **kwargs):
print('******* REQUEST FINISHED *******')
这是由我的AppConfig
在apps.py
成功加载的:
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'myapp'
verbose_name = 'verbose description of myapp'
def ready(self):
import myapp.signals
我使用Requests
库成功地与我的API通信,从而为我的一个测试用户提供了基本的身份验证凭据:
auth = HTTPBasicAuth(username, getpass('Enter password: '))
response = requests.get(self.url(endpoint), auth=self.auth, params = params)
REQUEST FINISHED
打印显示在Django服务器的输出中,但LOGIN DETECTED
没有显示。
在使用Tastypie时,我们是否必须手动触发登录信号,或者使用除BasicAuthentication
之外的其他内置/自定义Authentication
类? 换句话说,是否期望user_logged_in
信号不会自动触发?
任何信息,将不胜感激。
检查完Tastypie源代码后,它通过调用authenticate
方法绑定到Django auth后端,因此不会触发通常将authenticate
作为一个组件的login
周期。 因此,永远不会调用login
方法,因此永远不会触发user_logged_in
信号。
我最终通过扩展BasicAuthentication
并覆盖is_authenticated
自己提供了信号,如下所示:
class MyBasicAuthentication(BasicAuthentication):
def is_authenticated(self, request, **kwargs):
orig_user = request.user
has_authenticated = super(MyBasicAuthentication, self).is_authenticated(request, **kwargs)
if has_authenticated:
was_authenticated = orig_user == request.user
if not was_authenticated:
user_logged_in.send(sender=self.__class__, request=request, user=request.user)
return has_authenticated
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.