Wrapping a blueprint group with an arbitrary path

Hi there

I have a blueprint group that contains all the routes of my app. e.g. /report, /home /users. Seeing as there will be multiple tenants on my app, I would like to further segment these by organization e.g. /myorg/report, /myorg/home, /myorg/users. What would be the best way to achieve this behaviour bearing in mind that the name of the organization is arbitrary?

Thanks!

I am assuming that each organization would have the same endpoints available. I would personally organize it like this:

from sanic import Blueprint, Sanic
from sanic.response import text

app = Sanic("app")
report = Blueprint("report", url_prefix="/report")
home = Blueprint("home", url_prefix="/home")
users = Blueprint("users", url_prefix="/users")
bundle = Blueprint.group(report, home, users, url_prefix="/<org>")


@report.get("/sales")
async def sales_report(request, org):
    return text(f"Sales Report // {org=}")


@report.get("/profit_loss")
async def profit_loss_report(request, org):
    return text(f"Profit & Loss Report // {org=}")


@home.get("/")
async def index(request, org):
    return text(f"Home page // {org=}")


@home.get("/about")
async def about_us(request, org):
    return text(f"About Us // {org=}")


@users.get("/")
async def list_all(request, org):
    return text(f"List Users // {org=}")


@users.get("/<username>")
async def profile(request, org, username):
    return text(f"Profile for {username} // {org=}")


@app.listener("after_server_start")
def show(app, listener):
    for route in app.router.routes_all:
        print(route)


app.blueprint(bundle)
app.run(port=8888, debug=True)

This is obviously oversimplified, but I think illustrates that you can have variable path matching on the group prefix. If this is not what you are looking for, please let me know.

This is exactly what I am looking for, thank you!

1 Like