Skip to main content
 首页 » 编程设计

python之如何不基于用户模型进行自定义身份验证

2025年05月04日14duanxz

我的身份验证方案需要一些灵 active 。通过这种灵 active ,我的意思是我不想完全依赖用户模型或任何模型。在伪代码中我想得到这种逻辑:

class MyCustomAuthentication(authentication.BaseAuthentication) 
    def authenticate(self, request): 
        email = request.META.get('X_EMAIL') 
        password = request.META.get('X_PASSWORD') 
        # Here I want to connect to my database 
        # then make a query and verify if there exists a row that 
        # corresponds to email and password 
        # If it exists, then authentication is passed 
        # if not, then it is not passed 
 
@api_view() 
@authentication_classes((MyCustomAuthentication)) 
def items(request): 
    return Response({"message":"Hello world!"}) 

所以,如您所见,我不想依赖 ORM,我只想使用我友好的 sql 自己完成整个业务。但我不知道我应该如何以及从身份验证中返回什么。

请您参考如下方法:

Jacobian ,您需要导入 @authentication_classes(...) 装饰器。为此,只需在文件顶部添加以下行:

from rest_framework.decorators import authentication_classes 

来源: http://www.django-rest-framework.org/api-guide/views/