Skip to main content

MyPy types for WSGI

Project description

This is an attempt to bring some type safety to WSGI applications using Python’s new typing features (TypedDicts, Protocols). It seems to work OK but it’ll be full of gaps, holes, bugs, missteps, etc. I would not recommend depending on it.

This is implemented as a Python module, rather than MyPy stubs, as it represents a protocol things can satisfy rather than a set of types for something concrete.

This package came together during an exploration documented here:

Define a callable application as a class:

class MyApplication(wsgitypes.Application[MyEnviron]):
    def __call__(
        environ: Environ,
        start_response: wsgitypes.StartResponse,
    ) -> wsgitypes.ResponseBody:
        my_header = environ.get("REQUEST_METHOD", "")
        return []

Environ should be type-safe:

class MyApplication(wsgitypes.Application):
    def __call__(self, environ: Environ, start_response: wsgitypes.StartResponse) -> wsgitypes.ResponseBody:
        environ["wsgi.input"] # Good
        environ["wsgi.unpot"] # BORK! MyPy will catch this.
        return []

You can define your own extensions to Environ using TypedDict inheritance, like so:

class MyEnviron(wsgitypes.Environ):
    HTTP_X_MY_HEADER: t.Optional[str]

class MyApplication(wsgitypes.Application):
    def __call__(self, environ: wsgitypes.Environ, start_response: wsgitypes.StartResponse) -> wsgitypes.Response:
        environ = typing.cast(MyEnviron, environ)
        return []

Note that you need to use typing.cast to convert the incoming environ to your derived version. An attempt was made to use a type param for Environ, but it wasn’t viable:

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for wsgitypes, version 0.0.4
Filename, size File type Python version Upload date Hashes
Filename, size wsgitypes-0.0.4-py3-none-any.whl (6.1 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size wsgitypes-0.0.4.tar.gz (4.9 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page