Skip to main content

sanic-boom

Components injection, fast routing and non-global (layered) middlewares. Give your Sanic application a Boom!

In a nutshell

"""Example code taken from
https://marshmallow.readthedocs.io/en/3.0/quickstart.html#quickstart
"""

import datetime as dt
import inspect
import typing as t

from marshmallow import Schema, fields, post_load
from sanic.exceptions import ServerError
from sanic.response import text

from sanic_boom import Component, SanicBoom

# --------------------------------------------------------------------------- #
# marshmallow related code
# --------------------------------------------------------------------------- #


class User(object):
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.created_at = dt.datetime.now()

    def __repr__(self):
        return "<User(name={self.name!r})>".format(self=self)

    def say_hi(self):
        return "hi, my name is {}".format(self.name)


class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()
    created_at = fields.DateTime()

    @post_load
    def make_user(self, data):
        return User(**data)


# --------------------------------------------------------------------------- #
# sanic-boom related code
# --------------------------------------------------------------------------- #


class JSONBody(t.Generic[t.T_co]):
    pass


class JSONBodyComponent(Component):
    def resolve(self, param: inspect.Parameter) -> bool:
        if hasattr(param.annotation, "__origin__"):
            return param.annotation.__origin__ == JSONBody
        return False

    async def get(self, request, param: inspect.Parameter) -> object:
        inferred_type = param.annotation.__args__[0]
        try:
            return inferred_type().load(request.json).data
        except Exception:
            raise ServerError(
                "Couldn't convert JSON body to {!s}".format(inferred_type)
            )


app = SanicBoom(__name__)
app.add_component(JSONBodyComponent)


@app.post("/")
async def handler(user: JSONBody[UserSchema]):  # notice the handler parameters
    return text(user.say_hi())


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, workers=1)
$ curl -v http://localhost:8000/ -d '{"name":"John Doe","email":"john.doe@example.tld"}'
*   Trying ::1...
* TCP_NODELAY set
* connect to ::1 port 8000 failed: Connection refused
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8000 (#0)
> POST / HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.61.1
> Accept: */*
> Content-Length: 50
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 50 out of 50 bytes
< HTTP/1.1 200 OK
< Connection: keep-alive
< Keep-Alive: 5
< Content-Length: 23
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
hi, my name is John Doe

Dependencies

sanic-boom depends on two “not-so-known” libraries (both created by the author of sanic-boom):

Documentation

https://sanic-boom.readthedocs.io/en/latest/

License

sanic-boom is a free software distributed under the MIT license.

Changelog

v0.1.2 on 2018-10-23

  • Added components property on BoomRequest so any request “leftover” may be handled properly (like an open database connection).

v0.1.1 on 2018-10-18

  • Fixed a bug where handlers derived from HTTPMethodView class were not being executed (for their signature actually be *args, **kwargs).

v0.1.0 on 2018-10-17

  • First release on PyPI. (Probably) not stable.

Metadata

Release files for sanic-boom 0.1.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sanic-boom 0.1.4
File Size Uploaded Provenance
sanic-boom-0.1.4.tar.gz 30.8 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for sanic-boom 0.1.4
File Interpreter ABI Platform
sanic_boom-0.1.4-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 45.9 kB

Release files / sanic-boom-0.1.4.tar.gz

Download URL sanic-boom-0.1.4.tar.gz
Size 30.8 kB
Tags Source
SHA-256 checksum
How to use checksums
b3a509046b15536c169fac2c1dda57e7a77f6f11df6402c5b7d1480f24e67443
BLAKE2b-256 checksum
How to use checksums
1d3720382d424313e27bf63d1c4430b88540eba78aeb1272f2c7b1c725abd55d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.11.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/3.7.4

Release files / sanic_boom-0.1.4-py2.py3-none-any.whl

Download URL sanic_boom-0.1.4-py2.py3-none-any.whl
Size 15.1 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
ba84a51a64ea1a007a566fffacaf169cd840a6f2c656ecebecba47a22f985cb6
BLAKE2b-256 checksum
How to use checksums
2954813f48751ed4c311208102db5ef0c8c94e8aca67b5d7403e6a81fbed321e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.11.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/3.7.4

Security for sanic-boom 0.1.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page