pythonroutessanic

Function Not Found in Sanic Server


In Sanic server, a have a function defined in a file called controller.py with path /views/controller.py. My Sanic app is created in main.py at the root level (/) and can't find this function. The function has the decorator

@app.post("/get_x")

What do I have to do to make the Sanic app aware of this function's path? I'm getting a 404 error at the moment when calling this function from the browser. I can't seem to find any good documentation or examples on this. Any help would be greatly appreciated. Thanks.


Solution

  • As discussed in the comments, the problem is import ordering.

    When you do Sanic.get_app(), that will only work after the application instance has been created. Therefore, any imports in main.py before that happens will fail.

    You could instead look to expose and build your application's endpoints in factories.

    There are a couple methods you could try in my example here: https://github.com/ahopkins/sanicbook/blob/main/application/booktracker/server.py

    Or, you could try something like autodiscovery, discussed here: https://sanic.dev/en/guide/how-to/autodiscovery.html