简体   繁体   中英

Type checking variables on the sanic context object?

The sanic python http server provides a context object for global state. A nice newer feature of python is type checking, which can detect misspelled attributes. Is there a way of telling a type system like mypy what attributes, and their types you want to add to context object?

Because the object is a SimpleNamespace, there is no OOTB way to handle this. But, you have a few alternatives.

First, you can use Sanic Extensions to inject an object that is typed.

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.

class CustomContext:
    foo: int

app = Sanic(..., ctx= CustomContext())


ctx: CustomContext = app.ctx

Third, you could subclass the Sanic class and provide a typed object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM