给人家做的网站想改怎么改,在wordpress能做些什么,长春火车站出入最新规定,汕头seo网站推广1.认证Authentication
在 Django REST framework (DRF) 中#xff0c;可以在配置文件中配置全局默认的认证方案。常见的认证方式包括 cookie、session、和 token。DRF 提供了灵活的认证机制#xff0c;可以在全局配置文件中设置默认认证方式#xff0c;也可以在具体的视图类…1.认证Authentication
在 Django REST framework (DRF) 中可以在配置文件中配置全局默认的认证方案。常见的认证方式包括 cookie、session、和 token。DRF 提供了灵活的认证机制可以在全局配置文件中设置默认认证方式也可以在具体的视图类中设置单独的认证方式。
以下是默认的配置文件示例位于
REST_FRAMEWORK { # 配置认证方式的选项 DEFAULT_AUTHENTICATION_CLASSES: ( rest_framework.authentication.SessionAuthentication, # session认证 rest_framework.authentication.BasicAuthentication, # 基本认证 )
}
可以在具体的视图类中通过设置 authentication_classes 类属性来设置单独的不同的认证方式。例如
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView
class ExampleView(APIView): # 类属性 authentication_classes [SessionAuthentication, BasicAuthentication] def get(self, request): pass
认证失败会有两种可能的返回值这需要配合权限组件来使用
401 Unauthorized 未认证403 Permission Denied 权限被禁止
2.自定义认证
在一些特定场景中可能需要自定义认证方式。以下是一个自定义认证的示例位于 drfdemo.authentication 模块中
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import APIException
class CustomAuthentication(BaseAuthentication): 自定义认证方式 def authenticate(self, request): print(:::) 认证方法 request: 本次客户端发送过来的HTTP请求对象 token request._request.META.get(HTTP_TOKEN) if token ! 123456789: raise APIException(认证失败) user root return (user, token) # 按照固定的返回格式填写用户模型对象, None
3.在视图中使用自定义认证
在视图中可以通过设置 authentication_classes 类属性来使用自定义认证
from django.contrib.auth.models import AnonymousUser
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication
from drfdemo.authentication import CustomAuthenticationclass HomeAPIView(APIView):# authentication_classes [CustomAuthentication, ]def get(self, request):单独设置认证方式print(request.user) # 在中间件AuthenticationMiddleware中完成用户身份识别的如果没有登录request.user值为AnonymousUserif request.user.id is None:return Response(未登录用户游客)else:return Response(f已登录用户{request.user})当然也可以注释掉视图中的配置改成全局配置。以下是在 settings.py 中的配置示例
drf配置信息必须全部写在REST_FRAMEWORK配置项中
REST_FRAMEWORK {# 配置认证方式的选项【DRF的认证是内部循环遍历每一个注册的认证类一旦认证通过识别到用户身份则不会继续循环】DEFAULT_AUTHENTICATION_CLASSES: (drfdemo.authentication.CustomAuthentication, # 自定义认证rest_framework.authentication.SessionAuthentication, # session认证rest_framework.authentication.BasicAuthentication, # 基本认证)
}4.详细解释 DEFAULT_AUTHENTICATION_CLASSES: 定义了认证类的列表DRF 会按照顺序依次尝试每一个认证类。 CustomAuthentication: 自定义认证类用于特定的认证需求。SessionAuthentication: 使用 Django 的会话认证适用于浏览器和持久会话。BasicAuthentication: 使用 HTTP 基本认证适用于简单的 API 认证。 视图中使用认证类: 可以在具体的视图类中通过设置 authentication_classes 类属性来覆盖全局设置定义特定视图的认证方式。 认证失败的返回值: 401 Unauthorized: 未认证。403 Permission Denied: 权限被禁止。
通过这些配置您可以灵活地定制 DRF 的认证机制以满足不同的需求。这种灵活性使得 DRF 能够适应各种复杂的应用场景从简单的基本认证到自定义的复杂认证逻辑。