Sanic: How to add routes from another file?

Created on 12 Jul 2017  路  5Comments  路  Source: sanic-org/sanic

I have two files:

app.py

from sanic import Sanic

app = Sanic(__name__)

import endpoints

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, workers=4, debug=True)

endpoints.py

from app import app
from sanic import response


@app.route('/healthcheck/', methods=['GET'])
async def healthcheck():
    return response.text()

However I only get 404s from /healthcheck/. Is there a way to have routes in a separate file to the app?

Most helpful comment

You can do sth. like,

from sanic import response

async def healthcheck():
    return response.text()

def add_routes(app):
    app.add_route(healthcheck, '/healthcheck/', methods=['GET'])
from sanic import Sanic
from .endpoint import add_routes

app = Sanic(__name__)
add_routes(app)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, workers=4, debug=True)

All 5 comments

You can do sth. like,

from sanic import response

async def healthcheck():
    return response.text()

def add_routes(app):
    app.add_route(healthcheck, '/healthcheck/', methods=['GET'])
from sanic import Sanic
from .endpoint import add_routes

app = Sanic(__name__)
add_routes(app)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, workers=4, debug=True)

Perfect thanks!

You can also use blueprints. I think Blueprints is a more cleaner way to add routes from different modules.

I'm just experimenting with Sanic. It seems if you import your routes with from endpoints import *, then routes will be registered through the @app.route() decorator as well. Just don't add the __all__ = (routing-method-names) variable to the endpoints module, because then it won't work.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

litelife picture litelife  路  3Comments

eseglem picture eseglem  路  4Comments

mobdim picture mobdim  路  4Comments

woutor picture woutor  路  3Comments

fiecato picture fiecato  路  3Comments