Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask unable to find templates

Tags:

My project structure is like below

run.py lib/ mysite/     conf/         __init__.py (flask app)         settings.py     pages/         templates/             index.html         views.py         __init__.py 

This is mysite.conf.__init__

from flask import Flask  app = Flask(__name__) app.debug = True 

My idea is to now import app to every other module to use it to create views. Here in this case there is a module pages.

In pages.views I have some code like

from flask import render_template from mysite.conf import app  @app.route('/') def index():     return render_template('index.html') 

The index.html is placed in pages/templates

When I run this app from run.py which is like below

from mysite.conf import app app.run() 

I'm getting template not found error. How to fix it? and why is this happening!

I'm basically a django guy, and facing a lot of inconvenience with importing the wsgi object every time to create a view in every module! It kinda feels crazy -- Which in a way encourages circular imports. Is there any way to avoid this?

like image 290
Iamcool Avatar asked May 24 '14 15:05

Iamcool


1 Answers

Flask expects the templates directory to be in the same folder as the module in which it is created; it is looking for mysite/conf/templates, not mysite/pages/templates.

You'll need to tell Flask to look elsewhere instead:

app = Flask(__name__, template_folder='../pages/templates') 

This works as the path is resolved relative to the current module path.

You cannot have per-module template directories, not without using blueprints. A common pattern is to use subdirectories of the templates folder instead to partition your templates. You'd use templates/pages/index.html, loaded with render_template('pages/index.html'), etc.

The alternative is to use a Blueprint instance per sub-module; you can give each blueprint a separate template folder, used for all views registered to that blueprint instance. Do note that all routes in a blueprint do have to start with a common prefix unique to that blueprint (which can be empty).

like image 186
Martijn Pieters Avatar answered Sep 21 '22 07:09

Martijn Pieters