1.自己写:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
class UserView(APIView): versioning_class = ParamVersion def get(self,request,*args,**kwargs): v1 = request._request.GET.get('version') v2 = request.query_params.get('version') #获取结果是一样的,两种获取方式 print(v1,v2)
2.使用自带类:
from rest_framework.versioning import BaseVersioning class ParamVersion(BaseVersioning): def determine_version(self, request, *args, **kwargs): version = request.query_params.get('version') return version class UserView(APIView): versioning_class = ParamVersion def get(self,request,*args,**kwargs): v=request.version print(v)
3.使用类方法,不用写:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from rest_framework.versioning import QueryParameterVersioning class UserView(APIView): versioning_class = QueryParameterVersioning def get(self,request,*args,**kwargs): v=request.version print(v) settings中编写默认配置: REST_FRAMEWORK = { 'DEFAULT_VERSION':'v1', 默认版本 'ALLOWED_VERSIONS':['v1','v2'], 允许版本 'VERSION_PARAM':'version', 前端传参,可以写v }
4.URL读取版本:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
全局配置: 'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning', URLS配置: re_path(r'^(?P<version>[v1|v2]+)/userview/$',UserView.as_view()) v1,v2要遵循默认的版本配置
5.反向生成url:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
def get(self,request,*args,**kwargs): v=request.version url=request.versioning_scheme.reverse(viewname='uuu',request=request) print(v,url) urls配置: re_path(r'^(?P<version>[v1|v2]+)/userview/$',UserView.as_view(),name='uuu')