Viorel
Viorel

Reputation: 1468

Flask views in separate module

flaskr.py

# flaskr.py    
from flask import Flask


app = Flask(__name__)

import views


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)

python3 flaskr.py

Can anyone tell me why this isn't working but if i move the whole app into a separate package it works flawless.

No errors, not nothing except a 404 like the views.py is ignored. I'm knew to Flask and i'm trying out different things to understand how it actually works.

Thanks!

Upvotes: 14

Views: 11055

Answers (4)

KiraLT
KiraLT

Reputation: 2607

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 flask import render_template, g

my_view = Blueprint('my_view', __name__)

@my_view.route('/')
def show_entries():
    entries = None
    return render_template('show_entries.html', entries=entries)

Similar questions:

Upvotes: 16

TheMathochist
TheMathochist

Reputation: 45

In version 1.1.x, there is the add_url_rule() method where the views are loaded lazily from a separate module by placing view functions undecorated in a separate module, say views.py, and in the app file, one calls it as views.app.add_url_rule(path, view_func=views.view_func) in the same way as when we placed the route decorators above their view functions in the same file.

I'd also like to add this post as a resource

Upvotes: 0

Pablo Echavarría.
Pablo Echavarría.

Reputation: 103

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)

Upvotes: 1

Viorel
Viorel

Reputation: 1468

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.

Upvotes: 2

Related Questions