如何注解Django视图的方法?

m3eecexj  于 2022-12-20  发布在  Go
关注(0)|答案(3)|浏览(147)

我想在我的Django项目中使用Python type hints。在Django中注解简单class-based viewget/post方法的正确方法是什么?
我已经搜索了Django代码本身,但它似乎不包含任何类型提示。

7rtdyuoh

7rtdyuoh1#

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})
  • HttpRequestMap到函数或方法中的请求变量。
  • HttpResponse, JsonResponse, StreamingResponse, Redirect将是视图函数/方法返回的值。
  • *args, **kwargs既简单又复杂,因为它可以是 * 任意 * 元组值或字典值。*args: Any*args: tuple[Any](如果您知道,也可以使用特定类型)。
  • 无论何时传递或返回类,都使用type[cls]

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

kpbwa7wx

kpbwa7wx2#

  • *[更新15/12/2022]:我忘记了这个答案,但是如果你使用Python 3.6 +,你似乎不需要一个过去6年都没有维护的项目。

只需使用typing(如果需要)并像平常一样键入提示即可。
示例:

def get(self, request: HttpRequest, question_id: typing.Optional[str] = None) -> HttpResponse:
    # code here

存在您可能感兴趣的存储库:https://github.com/machinalis/mypy-django
这样你就可以像这样使用注解:

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

pbwdgjma3#

如果您使用基于函数的视图,并且不需要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

相关问题