Flask per-application template folder - python

I implementing simple site with couple of applications (like blog, code, account, etc). I decided to split one python file to apps due to large size. I do not using blueprints or something else except basic functionality of Flask - I'd like to keep it as simple as it possible.
Unfortunately, flask still looking for templates in the
/site
|-> main.py
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('config.py')
# Import all views
from errors.views import * # Errors hasn't its specific prefix
from blog.views import *
from account.views import *
from mysite.views import *
if __name__ == "__main__":
app.run(debug=True)
|-> templates
...................
|->blog
|-> template
|-> _layout.html
|-> index.html
|-> post.html
|-> __init__.py
from main import app
import blog.views
|-> views
from blog import app
from flask import render_template
#app.route("/blog/", defaults={'post_id': None})
#app.route("/blog/<int:post_id>")
def blog_view(post_id):
if post_id:
return "Someday beautiful post will be here with id=%s" % post_id
else:
return "Someday beautiful blog will be here"
#app.route("/blog/tags/")
def tags_view():
pass
..........................

Lets say you have 2 blueprints blog and account. You can divide up your individual apps(blueprints) of blog and account as follows:
myproject/
__init__.py
templates/
base.html
404.html
blog/
template.html
index.html
post.html
account/
index.html
account1.html
blog/
__init__.py
views.py
account/
__init__.py
views.py
In your blog/views.py, you can render templates like:
#blog.route('/')
def blog_index():
return render_template('blog/index.html')
#account.route('/')
def account_index():
return render_template('account/index.html')
..and so on

Add template_folder='templates' to each app Blueprint declaration:
account = Blueprint('account', __name__, template_folder='templates')
Details: https://flask.palletsprojects.com/en/2.0.x/blueprints/#templates

Related

Flask not rendering html

This is the code read but Flask not rendering html
from flask import Flask,render_template
import psycopg2
import psycopg2.extras
app=Flask(__name__)
app.route('/')
def index():
return render_template('index.html')
if __name__=="__main__":
app.run(debug=True, port=9001)
If I'm not mistaking, it's just a typo error. Supposed you already have a file called index.html in your templates folder. So your tree look like this:
.
└── my_app/
├── templates/
│ └── index.html
└── run.py
This code should work:
from flask import Flask, render_template
app=Flask(__name__)
#app.route('/') # <-- You are missing the '#' here
def index():
return render_template('index.html')
if __name__ == "__main__": # <-- Note this too
app.run(debug=True, port=9001)
Now you can access to your project at http://127.0.0.1:9001/
To learn more about Flask view decorator, go here.
For more information about what mean if __name__ == "__main__":, you can read more here.

Template error while using Flask with blueprints

I am getting a template not found error while trying to run a flask app using blueprints. The template directory is located at the root directory as expected at the same level as the app directory. I am not very sure why this is happening.
The directory structure
root/
app/
blueprint1/
routes.py
__main__.py
templates/
base.html
index.html
routes.py
from flask import Blueprint, render_template
blueprint = Blueprint(
"blueprint", __name__, template_folder="templates")
#blueprint.route("/", methods=["GET", "POST"])
def index():
return render_template("index.html")
Error
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: index.html
main.py
from flask import Flask
from app.blueprint1.routes import blueprint
def create_app():
app = Flask(__name__)
app.register_blueprint(blueprint)
return app
def _main():
daemon_app = create_app()
daemon_app.run(debug=True)
if __name__ == "__main__":
_main()
This works, I edited it a little
routes.py
from flask import Blueprint, render_template
blueprint = Blueprint("blueprint", __name__, template_folder="../../templates")
#blueprint.route("/", methods=["GET", "POST"])
def index():
return render_template("index.html")
__main__.py
from flask import Flask
from routes import blueprint
def create_app():
app = Flask(__name__)
app.register_blueprint(blueprint)
return app
def _main():
daemon_app = create_app()
daemon_app.run(debug=True)
if __name__ == "__main__":
_main()`
Based on your file structure, your blueprint renders html files from the main template folder. It might work if you remove the template_folder argument from routes.py file.
I copied your codes and tried to emulate the error but it works for me. A year ago I have the same problem and somehow I solved it. Since I can't emulate the error I can't solve your problem.
Instead, I will just give you advise. You are making an effort to create blueprints in their own package, and yet you are using the main template folder. When you have a lot of blueprints managing the template folder will become a challenge. Thus, I recommend putting the html file within the blueprint package itself.
Here's the file structure:
root/
app/
blueprint1/
pages/blueprint1/index.html
routes.py
__main__.py
templates/
base.html
and routes.py should be like this
blueprint = Blueprint(
"blueprint", __name__, template_folder="pages")
#blueprint.route("/", methods=["GET", "POST"])
def index():
return render_template("blueprint1/index.html")

jinja2.exceptions.TemplateNotFound index.html

I'm trying to learn flask by creating a simple blog web site. My file structure for my project looks like this:
flaskBlog
setup.py
flaskBlog
__init__.py
views.py
templates
index.html
So I've got my templates directory at the same level as my __init__.py and views.py which looks like this:
# __init__.py
from flask import Flask
app = Flask('__name__')
import flaskBlog.views
# views.py
from flaskBlog import app
from flask import render_template
#app.route('/')
def index():
return render_template('index.html')
When I use flask run it starts like normal and tells me its running on localhost:5000, but when I try to navigate to it I get a jinja error saying jinja2.exceptions.TemplateNotFound index.html. Every similar question I've seen on here is answered by saying to ensure that my app and my templates folder are on the same level but I'm still getting this error. Why can't the index template be found?
You can either put the templates dir a level up (next to your blog app) or you can define the path you want to load the templates from like so:
https://flask.palletsprojects.com/en/1.1.x/api/#application-object (check the template_folder arg)
You can make your folder structure like this:
flaskBlog
templates
index.py
setup.py
flaskBlog
__init__.py
views.py
The templates folder should be in the same directory as your setup.py

Flask models not importing propertly

Well, I have a Flask, SQL-Alchemy project. So far, this is my structure:
app
|__ module1
| |__ models.py
| |__ views.py
|__ module2
| |__ models.py
| |__ views.py
|__ app.py
|__ config.py
On every models.py, I have this:
from app import db
#classes
On every views.py, I have this:
from module1.models import *
from module2.models import *
from app import app
from flask import session, request, render_template, url_for, redirect
import datetime
#views
This is my app.py file:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
db = SQLAlchemy(app)
from module1.views import *
from module2.views import *
import config
def init():
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=True)
if __name__ == "__main__":
init()
When I'm on module1.views, and call a model from module2.models, works perfect. But when calling a model from module1.models on module1.views, I get a NameError:
module1.models, module1.views --> Works
module1.models, module2.views --> Works
module2.models, module1.views --> Name Error
module2.models, module2.views --> Works
Also, the import goes well, no error on that. When I call the class, it fails. I think it's some problem with the imports statements, but I don't know how to fix it. Any ideas?
Thank you guys, in advance
You might need an __init__.py file in each of the sub directories https://docs.python.org/3/tutorial/modules.html#packages.
There's more info in this answer as well that might be helpful What is __init__.py for?
Also based on the way you are sharing model functionality between views it would probably make more sense to use a directory structure like
.
├── models
│   ├── models1.py
│   └── models2.py
└── views
├── view1.py
└── view2.py

Flask can't route to certain url with blueprint

I am trying to organize my flask project, but there's something wrong.
I have this directory:
app/
__init__.py
views/
pages.py
On my __init__.py file I've imported the pages object and
registered it as a blue print.
This is the code on my pages.py file.
from flask import Blueprint, render_template
pages = Blueprint('pages', __name__) #no prefix
#pages.route('/')
def index():
return '<h1>in index.html</h1>'
#pages.route('/home')
def home():
return '<h1>in home.html</h1>'
If I run the flask app, open the browser, and go to localhost:5000,
I will see the headline 'in index.html'.
But if I go to localhost:5000/home, I will get the message 404 Not Found message.
Does anyone know the reason for this behavior?
Ok, first the folder structure:
app/
__init__.py
main.py
views/
__init__.py
test.py
Contents of main.py:
from flask import Flask
from views.test import pages
app = Flask(__name__)
app.register_blueprint(pages) <-- blueprint registration
Contents of test.py:
from flask import Blueprint
pages = Blueprint('pages', __name__) #no prefix
#pages.route('/')
def index():
return '<h1>in index.html</h1>'
#pages.route('/home')
def home():
return '<h1>in home.html</h1>'
I believe the register_blueprint was the only thing missing.
When stuff like that happen, just turn off everything, reset your computer.
Sometimes the bug is not yours.

Categories

Resources