我有以下Django观点:
@login_required
def view(request: HttpRequest) -> HttpResponse:
if not request.user.some_attribute:
return redirect("somewhere")
return render(request, "template_name")
以及具有属性some_attribute
的自定义User
模型
我使用mypy
强制执行类型检查,使用此mypy.ini
:
[mypy]
ignore_missing_imports = True
plugins = mypy_django_plugin.main
[mypy.plugins.django-stubs]
django_settings_module = [PROJECT NAME].settings
但是,mypy
错误如下:
Item "AnonymousUser" of "Union[User, AnonymousUser]" has no attribute "some_attribute"
这是有意义的,因为匿名用户没有这个属性,但我有一个login_required
装饰器,使得AnonymousUser
不可能(这将是一个User
)
我如何告诉mypy
忽略这个,而不使用# type: ignore
我认为将
request.user
转换为所需类型应该可以:您还可以将
HttpRequest
子类化,并显式地将子类上的user
字段设置为将类型显式定义为User
,而不是默认的联合对,如下所示:然后,每当您想要使用
login_required
装饰器时,将request
参数的类型提示设置为您的子类(在本例中是AuthenticatedHttpRequest
),如下所示:此方法在^{} readme file 中指定为推荐的方法,显然您正在使用该方法为
mypy
获取Django骨骼相关问题 更多 >
编程相关推荐