I tried implementing the code from this documentation https://flask.palletsprojects.com/en/1.1.x/patterns/errorpages/, but the custom error template I created for HTTP 404 error is not loading (it loads the default template for Flask). The method that handles the error is not being called and I'm not sure why. Am I implementing the errorhandler correctly?
_init_.py
from flask import Flask
app = Flask(__name__)
def create_app():
from flask_app.main.routes import main
from flask_app.testing_errors.routes import testing_errors
app.register_blueprint(main)
app.register_blueprint(testing_errors)
return app
run.py
from flask_app import create_app
# importing the create_app method above creates the flask application instance after executing the command: flask run
testing_errors/routes.py
from flask import Blueprint, render_template
testing_errors = Blueprint("testing_errors", __name__)
#testing_errors.errorhandler(404)
def page_not_found(e):
print("test")
return render_template("404.html"), 404
404.html
<html lang="en">
<head>
<title>404</title>
</head>
<body>
<h1>404 Page Not Found</h1>
</body>
</html>
since you are using a blueprint to handle the entire Flask app errors which is best practice you need app_errorhandler not errorhandler
#testing_errors.app_errorhandler(404)
def page_not_found(e):
print("test")
return render_template("404.html"), 404
refer to this doc https://flask.palletsprojects.com/en/1.1.x/api/?highlight=app_errorhandler#flask.Blueprint.app_errorhandler
Related
This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 2 years ago.
I have been following a YouTube tutorial made by Corey Schafer using Flask. I have reached the 2nd tutorial about using html templates, but that is the only place I have reached. This is the program I am running called hello.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
app.run()
This is the HTML file I have been using, called home.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask Template Example</title>
</head>
<body>
<div>
<p>{{ message }}</p>
</div>
</body>
</html>
Whenever I try to run my code, I always get the error jinja2.exceptions.TemplateNotFound: template.html. I've tried to look at all possible solutions, but none have seemed to work. How could I fix this? I'm on a Windows 64-bit machine.
By default un Flask, the template folder is templates/. If home.html is in the same directory as app.py, you need to set template_folder.
Here is how to fix your app.py:
from flask import Flask, render_template
app = Flask(__name__, template_folder='./')
#app.route('/')
def home():
return render_template('home.html')
app.run()
To use the default template location (which is recommended), this is the file structure you would need to have:
app.py
templates
└── home.html
I want to build a site. I have the index folder and the connected folder. Each folder also has a static folder. In the connected/static folder, I have the connected.css file, which I am trying to access, through my blueprint. However, the final page tries to access the connected.css from the index/static folder.
Where am I mistaking?
Useful code:
__init__.py:
from flask import Flask
from .index import index_routes
from .connected import connected_routes
def create_app():
app = Flask(__name__, template_folder="templates", static_folder="static")
app.register_blueprint(index_routes.index_bp)
app.register_blueprint(connected_routes.connected_bp, url_prefix='/connected')
return app
connected_routes.py
from flask import Blueprint
from flask import render_template
connected_bp = Blueprint('connected_bp', __name__, template_folder='templates', static_folder='static', url_prefix='/connected')
#connected_bp.route('/')
def connected():
return render_template('connected.html', title="Connected to Hattrick")
index_routes.py
from flask import Blueprint
from flask import render_template
index_bp = Blueprint('index_bp', __name__, template_folder='templates', static_folder='static')
#index_bp.route('/')
def home():
return render_template('index.html', title="The Best Match Predictor")
connected.html
<link href="{{url_for('static',filename='connected.css')}}" rel="stylesheet">
In the above line I have the problem.
Maybe give this a try:
<link href="{{url_for('connected.static',filename='connected.css')}}" rel="stylesheet">
For some elaboration: https://flask.palletsprojects.com/en/1.1.x/blueprints/#static-files
I'm learning Python and Flask, I have very little experience, but something that is impossible.
With the usual AJAX does not have any problems, but I decided to try sijax, and even a simple example does not work. I'm sure this is due to incorrect connection and initialization, because I did git clone from the official repository git hub, and everything worked.
In the three examples, sijax working and initialized in one-file application, I want to use in the blueprint
If i click on the Say Hi!
Traceback return : 127.0.0.1 - - [12/Sep/2016 14:19:56] "POST / HTTP/1.1" 400 -
app init.py
import os
from flask import (Flask,
redirect,
url_for,
session)
# from flask_login import LoginManager
from flask_wtf.csrf import CsrfProtect
from os import path
from .database import db
from werkzeug.contrib.fixers import ProxyFix
import flask_sijax
import hmac
from hashlib import sha1
def create_app(config=None):
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
app.wsgi_app = ProxyFix(app.wsgi_app)
db.init_app(app)
app.config["SIJAX_STATIC_PATH"] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')
app.config["SIJAX_JSON_URI"] = '/static/js/sijax/json2.js'
'''
if app.debug == True:
try:
from flask_debugtoolbar import DebugToolbarExtension
toolbar = DebugToolbarExtension(app)
except:
pass
'''
with app.test_request_context():
db.create_all()
from .general import controllers as general
from .shop import controllers as shop
from .test import controllers as test
app.register_blueprint(shop.module)
app.register_blueprint(general.module)
app.register_blueprint(test.module)
flask_sijax.Sijax(app)
CsrfProtect(app)
#app.template_global('csrf_token')
def csrf_token():
"""
Generate a token string from bytes arrays. The token in the session is user
specific.
"""
if "_csrf_token" not in session:
session["_csrf_token"] = os.urandom(128)
return hmac.new(app.secret_key, session["_csrf_token"],
digestmod=sha1).hexdigest()
#app.route('/')
def index():
return redirect(url_for('test.index'))
return app
test blueprint controllers.py
from flask import (render_template,
Blueprint,
g)
import flask_sijax
module = Blueprint('test',
__name__)
#flask_sijax.route(module, '/')
def index():
def say_hi(obj_response):
obj_response.alert('Hi there!')
if g.sijax.is_sijax_request:
g.sijax.register_callback('say_hi', say_hi)
return g.sijax.process_request()
return render_template('test/hello.html')
template hello.html
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="{{ url_for('static', filename='js/sijax/sijax.js') }}"></script>
<script src="{{ url_for('static', filename='js/sijax/json2.js') }}"></script>
<script>{{ g.sijax.get_js()|safe }}</script>
</head>
<body>
Say Hi!
</body>
</html>
The reason was not working sijax, it was the fact that the {{csrf_token ()}} was not active
It is necessary to do so either: Say Hi!
Either connect to the html file:
<script type="text/javascript">
var csrfToken = "{{ csrf_token() }}"
</script>
This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 7 years ago.
This is absolutely new field for me, and I just confused about how this work
Flask server
$ more flask-hello-world.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('index.html') #"Hello World!"
if __name__ == "__main__":
app.run()
index.html
$ more index.html
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
</head>
<body>
Hello worlds
</body>
</html>
Test
$ curl 127.0.0.1:5000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
When I return "Hello World!" it does work properly. Why am I getting an error when I try return render_template('index.html')?
First of all you should turn on debugging for your Flask app, so you see a meaningful error instead of a canned HTTP 500 Internal Server Error.
app.debug = True
app.run()
or
app.run(debug=True)
What could be wrong with your Flask app
From your source code I see you have not imported render_template
So that is at least one issue, fix it with:
from flask import Flask, render_template
# The rest of your file here
Template names and directory
There is a parameter template_folder
you can use to tell Flask where to look for your templates. According to linked documentation, that value defaults to templates which means Flask by default looks for templates in a folder called templates by default. So if your templates are on the project root instead of a folder, use:
E.g. if your templates are in the same directory is the app:
app = Flask(__name__, template_folder='.') # '.' means the current directory
You need to put your templates in templates folder, or ovride it in:
app = Flask(__name__, template_folder='.')
I want to show an image in the homepage of a python web application. So far I wrote the following program:
My directories and files
myWebApp/
app/
__init__.py
views.py
templates/
home.html
static/
Desert.jpg
run.py
__init__.py
from flask import Flask
app = Flask(__name__)
from app import views
views.py
from app import app
from flask import render_template
from flask import url_for
#app.route('/')
def root():
imag = url_for ('static', filename = 'Desert.jpg')
tle = "Hey"
return render_template('home.html', imag,tle)
home.html
<html>
<title>{{ tle }}</title>
<body>
<img src="{{ imag }}"/>
</body>
</html>
run.py
from app import app
if __name__ == "__main__":
app.run()
And when I run the run.py, I receive the following Internal Server Error:
What's wrong?
That's not the correct syntax for the render_template function. You need to use keyword arguments:
return render_template('home.html', imag=imag, tle=tle)