[英]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.