首页 > 编程语言 >drf源码剖析----版本、reverse

drf源码剖析----版本、reverse

时间:2024-03-11 14:16:06浏览次数:33  
标签:None reverse self args request ---- 源码 version kwargs

点击查看代码
class APIView(View):
    def dispatch(self, request, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        try:
            self.initial(request, *args, **kwargs)  

            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response

    def initial(self, request, *args, **kwargs):

        self.format_kwarg = self.get_format_suffix(**kwargs)

        neg = self.perform_content_negotiation(request)
        request.accepted_renderer, request.accepted_media_type = neg

        version, scheme = self.determine_version(request, *args, **kwargs)
        request.version, request.versioning_scheme = version, scheme

        self.perform_authentication(request)
        self.check_permissions(request)
        self.check_throttles(request)

    def determine_version(self, request, *args, **kwargs):
# 优先到类APIView()中找versioning_class,没有再到全局配置中找
        if self.versioning_class is None: 
            return (None, None)
        scheme = self.versioning_class()
# 返回自定义版本类的对象中的determine_view()方法和类对象
        return (scheme.determine_version(request, *args, **kwargs), scheme)
点击查看代码
class HomeView(APIView):

    authentication_classes = []
    versioning_class = MyVersion

    def get(self, request):
        url = request.versioning_scheme.reverse('v1', request)
        return Response("这是版本{}的信息".format(request.version))
# 自定义版本类
class MyVersion(QueryParameterVersioning):

    def determine_version(self, request, *args, **kwargs):
        version = request.query_params.get('version')
        if not version:
            version = 'v1'
        return version

class QueryParameterVersioning(BaseVersioning):
    invalid_version_message = _('Invalid version in query parameter.')

    def determine_version(self, request, *args, **kwargs):
        version = request.query_params.get(self.version_param, self.default_version)
# 找父类的is_allowed_version(),没有对应的版本则报错
        if not self.is_allowed_version(version):
            raise exceptions.NotFound(self.invalid_version_message)
        return version

    def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra):
        url = super().reverse(
            viewname, args, kwargs, request, format, **extra
        )
        if request.version is not None:
            return replace_query_param(url, self.version_param, request.version)
        return url

class BaseVersioning:
    default_version = api_settings.DEFAULT_VERSION
    allowed_versions = api_settings.ALLOWED_VERSIONS
    version_param = api_settings.VERSION_PARAM

    def determine_version(self, request, *args, **kwargs):
        msg = '{cls}.determine_version() must be implemented.'
        raise NotImplementedError(msg.format(
            cls=self.__class__.__name__
        ))

    def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra):
        return _reverse(viewname, args, kwargs, request, format, **extra)

    def is_allowed_version(self, version):
        if not self.allowed_versions:
            return True
        return ((version is not None and version == self.default_version) or
                (version in self.allowed_versions))

def _reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
    if format is not None:
        kwargs = kwargs or {}
        kwargs['format'] = format
# 返回原生的django_reverse
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
    if request:
        return request.build_absolute_uri(url)
    return url

标签:None,reverse,self,args,request,----,源码,version,kwargs
From: https://www.cnblogs.com/only-you-zta/p/18065937

相关文章

  • 云监控的核心:确保稳定性的关键监控指标
    本文分享自天翼云开发者社区《云监控的核心:确保稳定性的关键监控指标》,作者:每日知识小分享随着云计算技术的广泛应用,云监控成为了确保云服务稳定、高效运行的重要手段。在云监控中,选择合适的监控指标至关重要,它们不仅能够反映云服务的运行状态,还能帮助运维人员及时发现并解决问题......
  • 为什么要写技术方案?
    有同学留言问我:在中小型公司做测试工作,领导提出要做自动化测试,是找个框架直接落地开干呢,还是先做做调研写个技术方案?担心做调研写方案没人看,领导只关注效率和结果。又是一个难得一见的好问题,这个问题的终极拷问是效率高低和结果优劣的对比,这种现象在很多中小型公司甚至大型公司......
  • vulnhub靶机:dc-5
    一:信息收集1:主机发现arp-scan-Ieth010.9.23.0/24kali的ip10.9.23.112靶机IP10.9.23.2042:端口扫描nmap-A-p--T410.9.23.2043:端口探测发现contact里面他有输入框发现底下这个页脚会发生变化,猜测存在文件包含漏洞,先扫一下目录4:目录遍历dirsearch-u10.9.23......
  • C#100个经典面试题
    原文链接:https://www.cnblogs.com/zxdz/p/13370024.html1..NET和C#有什么区别答:.NET一般指.NETFrameWork框架,它是一种平台,一种技术。C#是一种编程语言,可以基于.NET平台的应用。2.一列数的规则如下:1、1、2、3、5、8、13、21、34......求第30位数是多少,用递归算法实现。答:p......
  • JS正则常用校验
    手机号(mobilephone)中国(严谨),根据工信部2019年最新公布的手机号段1constreg=/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/;2conststr="19119255642";3console.log(`校验${reg.test(str)?......
  • ubuntu20.04-通过docker安装jenkins并自动化发布java
    前言jenkins需要git、maven和node,其中maven和node手动添加,git和git环境是jenkins镜像自带了的。如果删除了docker对应的jenkins容器后(删除前一定备份jenkins_home整个文件夹,否则怕前功尽弃:tar-czvfjenkins_home.tar.gz/var/jenkins_home)如果删除了容器,需要重新安装并配置m......
  • 网络流量监测分析,国产、高性能、高可用
        随着网络规模不断扩大,复杂程度不断增加,给运维工作带来更大挑战。为保障网络正常、稳定、高效运行,对网络流量进行监测、存储、回溯成为不可或缺的手段,通过对流量的分析,运维人员可以更加全面的了解整体网络的运行状态,快速定位、解决网络中存在问题。    智和信......
  • Find class object in a library file
    Youmaygetalinkererrorthatsaysasysbolwasnotfoundduringlinkingstage.Thisisproblelybecausesomelibrarywasnotaddedrightly.Hereisabashscripttofindwhichlibraryisthemissing classsymbolin.!/bin/bashfunctiondoDir(){......
  • 载谭 Binomial Sum 学习笔记
    对于微分有限的生成函数\(F(x)\),有一个生成函数\(G(x)\),以及数列\(a\),如果对于\(0\lek\len\),我们已知\(\displaystyle\sum_{i=0}^na_i[x^i]G(x)^k\),那么我们能够在\(\Theta(n)\)的时间复杂度内求出\(\displaystyle\sum_{i=0}^na_i[x^i]F(G(x))\)。设\(c=[x^0]......
  • aspnet zero 12 添加登录 验证码
       aspnetzero自带的验证码是基于Google,国内当前无法使用,只能替换国内的。实现后的界面如下图: PackageManagerInstall-PackageLazy.Captcha.Core验证码后端代码publicinterfaceICaptchaAppService:IApplicationService{///<summary>......