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?
http://sanic.readthedocs.io/en/latest/sanic/routing.html#the-add-route-method
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.
Most helpful comment
You can do sth. like,