路由、认证
路由
1 普通路由书写
path('test/',views.TestAPIView.as_view()),
re_path('test/(?P<pk>\d+)',views.TestDetailAPIView.as_view()),
2 视图类继承ViewSetMinxin的路由,对应的请求方式执行对应的方法
path('test2/',views.Test2View.as_view(actions={'get':'list','post':'create'})),
re_path('test2/(?P<pk>\d+)',views.Test2DetailView.as_view(actions={'retrieve','put':'update','delete':'destory'})),
3 视图类继承ModelViewSet自动生成路由,只有继承视图集的可以自动生成路由
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('test',views.Test)
urlpatterns += router.urls
认证
1 写一个类,继承BaseAuthentication,重写authenticate,里面写逻辑,认证通过,返回两个值,一个值最终给了Requet对象的user,认证失败,抛异常:APIException或者AuthenticationFailed
2 全局使用,局部使用
def _authenticate(self):
for authenticator in self.authenticators:
try:
user_auth_tuple = authenticator.authenticate(self)
except exceptions.APIException:
self._not_authenticated()
raise
if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple
return
self._not_authenticated()
认证组件的完整使用
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01.models import UserToken
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
token = request.GET.get('token')
if token:
user_token = UserToken.objects.filter(token=token).first()
if user_token:
return user_token.user,token
else:
raise AuthenticationFailed('认证失败')
else:
raise AuthenticationFailed('请求地址需要携带token')
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.app_auth.MyAuthentication"]
}
authentication_classes=[MyAuthentication]
authentication_classes=[]
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· C# 13 中的新增功能实操
· Supergateway:MCP服务器的远程调试与集成工具
· Vue3封装支持Base64导出的电子签名组件