Reputation:
I'm using Gunicorn (on nginx) with Flask. Let's say I have two Python files, linked with a Flask Blueprint: app.py
and api.py
where api.py
has the url prefix /api
. Why is it that any routes in app.py
work although all Blueprinted (i.e. /api
) routes return 404s?
app.py
looks something like this:
from flask import Flask, Blueprint
app = Flask(__name__)
@app.route('/')
def index():
return '''cheese-bread'''
if __name__ == '__main__':
app.register_blueprint(api, url_prefix='/api')
app.run(host='0.0.0.0')
and api.py
from flask import Blueprint, jsonify
api = Blueprint('/api', __name__)
@api.route('/')
def index():
return jsonify({'bread' : 'cheese, please'})
wsgi.py
is as simple as possible
from app import app
if __name__ == "__main__":
app.run()
Startup scripts are not relevant as the 404s appear when running for development with gunicorn -b 0.0.0.0:8000 wsgi:app
Any help would be greatly appreciated.
Upvotes: 3
Views: 3612
Reputation: 113930
you need to register the blueprint outside of if __name__ == "__main__"
, since when you say from app import app
it will not run any code in the guardblock
from flask import Flask, Blueprint
app = Flask(__name__)
@app.route('/')
def index():
return '''cheese-bread'''
app.register_blueprint(api, url_prefix='/api')
if __name__ == '__main__':
app.run(host='0.0.0.0')
that way when you import it in wsgi it also has the blueprint registered ...
alternatively you could register the blueprint in the wsgi.py
Upvotes: 10