Running handlers from Click

Recently, there was a question on the Discord server about integrating Sanic handlers with Click.

Here is a rough estimation of what it could look like.

# clip.py
import asyncio

import click

import server  # noqa
from handlers import handler


@click.command()
@click.option("--name", prompt="Your name", help="The person to greet.")
def hello(name):
    response = asyncio.run(handler(None, name))
    click.echo(response.body)


if __name__ == "__main__":
    hello()
# handlers.py
from sanic import Sanic, text

app = Sanic.get_app()


@app.get("/<name>")
async def handler(request, name):
    return text(f"Hello {name}")
# server.py
from sanic import Sanic


def create_app():
    app = Sanic(__name__)
    import handlers  # noqa

    return app


app = create_app()

With a setup like this, you could run this to get the server going:

sanic server:app

Or, this to hit the handler from CLI:

python cli.py

The important thing is to make sure that app.run() is no in the global scope anywhere that cli.py will run.

1 Like