路由组件
2022/6/17 23:28:21
本文主要是介绍路由组件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
目录- 路由组件
- SimpleRouter
- DefaultRouter
- action装饰器
路由组件
在使用CBV继承ViewSetMixin及其子类时,路由需要我们配置映射关系,手动配置过于麻烦,DRF提供了路由组件自动生成5个映射关系。
SimpleRouter
方式一:
from rest_framework.routers import SimpleRouter # 实例化 router = SimpleRouter() # 注册路由 router.register('books', views.BookView, 'books_view') """ 第一个参数:路由地址(不要加斜杠,会自动添加) 第二个参数:CBV类(需要继承ViewSetMixin类及其子类) 第三个参数:别名,用于反向解析 """ urlpatterns = [] # 将自动生成的路由添加到总路由中 urlpatterns += router.urls
方式二:
from rest_framework.routers import SimpleRouter from django.conf.urls import include # 实例化 router = SimpleRouter() # 注册路由 router.register('books', views.BookView, 'books_view') """ 第一个参数:路由地址(不要加斜杠,会自动添加) 第二个参数:CBV类(需要继承ViewSetMixin类及其子类) 第三个参数:别名,用于反向解析 """ urlpatterns = [ path('', include(router.urls)) ]
DefaultRouter
在实际使用中DefaultRouter和SimpleRouter的功能并无区别,主要的区别在于总路由中多了路由:
使用方式于SimpleRouter一样。
浏览器直接访问127.0.0.1:8000:
action装饰器
因为路由自动生成只会有5个映射关系,无法映射我们自己写在CBV中的函数,这个时候就需要用到action装饰器。
action装饰器各项参数:
- methods:请求方法,值为['get', 'post']代表get和post请求触发
- detail:是否是带id的路由
- url_path:路由路径,默认为函数名
- url_name:别名,用于反向解析
detail为False时
CBV:
class UserView(ViewSet): @action(methods=['get'], detail=False, url_path='login', url_name='login-view') def login(self, request): return Response('login')
路由:
from rest_framework.routers import SimpleRouter router = SimpleRouter() router.register('user', views.UserView, 'user') urlpatterns = [] urlpatterns += router.urls
detail为True时
CBV:
class UserView(ViewSet): @action(methods=['get'], detail=True, url_path='login', url_name='login-view') def login(self, request): return Response('login')
路由:
from rest_framework.routers import SimpleRouter router = SimpleRouter() router.register('user', views.UserView, 'user') urlpatterns = [] urlpatterns += router.urls
这篇关于路由组件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求
- 2024-10-01使用 golang 将ETH账户的资产平均分散到其他账户
- 2024-10-01JWT用户校验课程:从入门到实践
- 2024-10-01Server Component课程入门指南