I want to do an asynchronous HTTP call to an external service at server startup and get an URL from there which I can then use in my own Sanic routing. E.g., fetch the string which needs to be my actual route via an httpx
call (for the sake of simplicity, let's say the string returned by the external service is api/users/
) and then use it as a route in my Sanic microservice.
Unfortunately it seems a before_server_start
listener does not do the trick, as that is run after routes are loaded and I get a FinalizationError("Cannot finalize router more than once.")
if I try to update the string value of a route.
Any ideas of how else I could hook up my call before defining / adding routes? I would like to keep it as coupled as possible to the Sanic app, i.e., not use a utility script that would run before it, but instead have the call to the external service triggered every time the app starts.
You can do it inside the before_server_start
event with a little roundabout.
@app.before_server_start
async def setup_dynamic_routes(app, _):
app.router.reset()
# add your routes here
app.router.finalize()