Flask views in separate module
If you want to move views to other file you need to register blueprint:
flask.py
# flaskr.py
from flask import Flask
from .views import my_view
app = Flask(__name__)
app.register_blueprint(my_view)
if __name__ == "__main__":
app.run()
views.py
# views.py
from flaskr import app
from flask import render_template, g
my_view = Blueprint('my_view', __name__)
@app.route('/')
def show_entries():
entries = None
return render_template('show_entries.html', entries=entries)
Similar questions:
- URL building with Flask and non-unique handler names
- Using flask/blueprint for some static pages
I solved this issue for me by adding a wilcard in flaskr.py. I saw this idea first at https://github.com/jennielees/flask-sqlalchemy-example, however I am now trying to do a blueprint as it is better to maintain the code in the long run I believe.
flaskr.py
# flaskr.py
from flask import Flask
app = Flask(__name__)
# import views
from views import *
if __name__ == "__main__":
app.run()
views.py
# views.py
from flaskr import app
from flask import render_template, g
@app.route('/')
def show_entries():
entries = None
return render_template('show_entries.html', entries=entries)
Apparently, this has to do with app.root_path
.
- In views.py,
app.root_path
is/path/to/project/flaskr
- But in flaskr.py,
app.root_path
is/path/to/project
So Flask expects views.py to be put into a package.