How to overwrite a route when using blueprint.copy?

I want to overwrite the implement of route partially when they belong to different version blueprint, and it raises sanic_routing.exceptions.RouteExists.

How can I get this target by a recommanded way?

from sanic import Blueprint
from sanic.response import json
from sanic import Sanic

app = Sanic('test')

bpv1 = Blueprint('bpv1', version=1)

async def root(request):
    return json('hello v1')


bpv2 = bpv1.copy('bpv2', version=2)

async def root(request):
    return json('hello v2')


Looking into this. Will get back.

I am not sure that we have a great way to support this right now. That is mainly because when you go to add the route with bpv2, it already exists having been defined on bpv1. There is no “overwrite” functionality yet. I suppose the best way would be to remove it manually, but that might be a bit messy.

bpv2 = bpv1.copy("bpv2", version=2)

bpv2._future_routes = {
    route for route in bpv2._future_routes if route.uri != "/hello"

async def root2(request):
    return json("hello v2")

Might be a nice addition to add that as a feature request on the GitHub issue board.

1 Like

Thank you so much ~ This way is just i want.

Thanks for adding the request. We used to actually have a method app.delete_route or something like that. But it was sort of being misused and causing a lot of troubles during the running of an application and causing problems. We figured it was safer to remove as there was no use case, and someone that had a particular use case could handle it on their own.

This does seem like a legit use case. Might need to think how it might look. I am currently leaning towards this:

bpv2 = bpv1.copy("bpv2", version=2, allow_overwrite=True)

In the normal course, you would get the exact same behavior you ran into. But, there is the bail out option to allow overwriting on a BP if needed.

1 Like