【问题标题】:How to annotate Django view's methods?如何注释 Django 视图的方法?
【发布时间】:2017-10-18 19:32:03
【问题描述】:

我想在我的 Django 项目中使用 Python type hints。在Django中注释get/post的简单class-based view方法的正确方法是什么?

我已经搜索了 Django 代码本身,但它似乎不包含任何类型提示。

【问题讨论】:

    标签: python django annotations type-hinting


    【解决方案1】:

    存在您可能感兴趣的存储库:https://github.com/machinalis/mypy-django
    这将允许您使用如下注释:

    def get(self, request: HttpRequest, question_id: str) -> HttpResponse:
    

    【讨论】:

      【解决方案2】:

      如果使用基于函数的视图,并且您不需要或不需要 mypy-django,您可以这样做:

      from django.http import HttpRequest, HttpResponse, JsonResponse
      
      def some_fbv(request: HttpRequest) -> HttpResponse:
          ....
          return foo
      
      def some_json_producing_fbv(request: HttpRequest) -> JsonResponse:
          ...
          return foo
      

      【讨论】:

        【解决方案3】:

        Django stubs 是一个维护良好的包,https://github.com/typeddjango/django-stubs

        import typing as t
        
        from django.http import HttpResponseRedirect
        from django.shortcuts import render
        from django.views import View
        from django.http import HttpRequest, HttpResponse, JsonResponse, 
        HttpResponseRedirect
        
        from .forms import MyForm
        
        # type alias when response is one of these types
        RedirectOrResponse = t.Union[HttpResponseRedirect, HttpResponse]
        
        
        class MyFormView(View):
            form_class = MyForm
            initial = {'key': 'value'}
            template_name = 'form_template.html'
        
            def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
                form = self.form_class(initial=self.initial)
                return render(request, self.template_name, {'form': form})
        
            def post(self, request: HttpRequest, *args: tuple[Any], 
                        **kwargs: dict[str, t.Union[int, str]]) -> RedirectOrResponse:
                form: MyForm = self.form_class(request.POST)
                if form.is_valid():
                     # <process form cleaned data>
                     return HttpResponseRedirect('/success/')
        
                return render(request, self.template_name, {'form': form})
        
        • HttpRequest 映射到函数或方法中的请求变量。
        • HttpResponse, JsonResponse, StreamingResponse, Redirect 将是视图函数/方法返回的值。
        • *args, **kwargs 既简单又棘手,因为它可以是任何值元组或值字典。 *args: Any*args: tuple[Any](如果您知道,也可以使用特定类型)。这同样适用于**kwargs
        • 无论何时传递或返回类,请使用type[cls]

        更多示例:https://github.com/typeddjango/django-stubs/tree/master/tests

        【讨论】:

          猜你喜欢
          • 2018-01-20
          • 2011-12-25
          • 1970-01-01
          • 2015-12-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多