[英]Type checking variables on the sanic context object?
The sanic python http server provides a context object for global state. sanic python http 服务器为全局 Z9ED39E2EA931586B6EZ85A6942EF57 提供上下文object。 A nice newer feature of python is type checking, which can detect misspelled attributes.
python 的一个不错的新功能是类型检查,它可以检测拼写错误的属性。 Is there a way of telling a type system like mypy what attributes, and their types you want to add to context object?
有没有办法告诉像 mypy 这样的类型系统你想将哪些属性以及它们的类型添加到上下文 object 中?
Because the object is a SimpleNamespace, there is no OOTB way to handle this.因为 object 是一个 SimpleNamespace,所以没有 OOTB 方法来处理这个问题。 But, you have a few alternatives.
但是,你有几个选择。
First, you can use Sanic Extensions to inject an object that is typed.首先,您可以使用Sanic Extensions注入一个已键入的 object。
foo = Foo()
app.ext.dependency(foo)
@app.get("/getfoo")
async def getfoo(request: Request, foo: Foo):
return text(foo.bar())
Second, you could create a custom object that is typed and pass that to Sanic.其次,您可以创建一个自定义的 object,然后将其传递给 Sanic。
class CustomContext:
foo: int
app = Sanic(..., ctx= CustomContext())
ctx: CustomContext = app.ctx
Third, you could subclass the Sanic
class and provide a typed object.第三,您可以子类化
Sanic
class 并提供类型化的 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.