Jinja2Exception Flask template not found - python

I am getting the error jinja2.exceptions.TemplateNotFound. Even I have my HTML files in the templates folder, still I am receiving this error. It was working fine sometime ago, and now I am getting this error.
Full error code:
Traceback (most recent call last)
File "E:\price\web\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "E:\price\web\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "E:\price\web\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "E:\price\web\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\price\web\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "E:\price\web\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "E:\price\web\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "E:\price\web\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\price\web\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "E:\price\web\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "E:\price\web\flasktest.py", line 6, in index
return render_template('about.html')
File "E:\price\web\Lib\site-packages\flask\templating.py", line 138, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 1068, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 997, in get_template
return self._load_template(name, globals)
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 958, in _load_template
template = self.loader.load(self, name, self.make_globals(globals))
File "E:\price\web\Lib\site-packages\jinja2\loaders.py", line 125, in load
source, filename, uptodate = self.get_source(environment, name)
File "E:\price\web\Lib\site-packages\flask\templating.py", line 60, in get_source
return self._get_source_fast(environment, template)
File "E:\price\web\Lib\site-packages\flask\templating.py", line 89, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: about.html
Here's my code snippet:
from flask import Flask, render_template
app = Flask('test', template_folder= 'templates')
#app.route('/')
def index():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug = True, host = '127.0.0.1', port = 5000)
Here is the screenshot of my directories:
Update:
My code is working perfectly in a new file. Is it due to cache?
Tried app = Flask(name) but still same issue.
A new Test.py file works completely fine but not the old ones.

have a look at this topic https://flask.palletsprojects.com/en/2.0.x/api/#application-object and head over this section About the First Parameter
so my guess, you should import the right package name,
so try __name__ instead of test
app = Flask(__name__, template_folder='templates')
BTW, Flask already expects templates as default folder to look at, meaning it's optional and you can define your app like so
app = Flask(__name__)

Flask looks for templates by default in the "templates" folder https://flask.palletsprojects.com/en/2.0.x/quickstart/#rendering-templates.
Try this:
app = Flask(__name__)
#app.route('/')
def index():
return render_template('about.html')

Finally I got the solution where it went wrong.
I was doing this:
app = Flask('__name__')
But the correct way was this:
app = Flask(__name__)

Related

TikTokApi throws an error in Flask but works outside of it

I have a strange problem when using flask + TikTok API that I can't figure out.
I have the following code:
from flask import Flask
from flask_restful import Resource, Api
from TikTokApi import TikTokApi
tikTokApi = TikTokApi()
app = Flask(__name__)
api = Api(app)
#app.errorhandler(404)
def page_not_found(e):
return {'status': 'fail'}, 404
class TikTokProfile(Resource):
def get(self):
profileResponse = tikTokApi.getUserObject('rosiethepygmygoat')
return {'user' : profileResponse}
class TikTokMedia(Resource):
def get(self):
data = tikTokApi.getUserObject('rosiethepygmygoat')
response = tikTokApi.userPage(data["id"],data["secUid"])
return response
api.add_resource(TikTokProfile, '/profile')
api.add_resource(TikTokMedia, '/media')
if __name__ == '__main__':
app.run(debug=True)
When I visit /profile I get the user object, but when I try to get his user page via the /media route I get the following error:
INFO:werkzeug:127.0.0.1 - - [08/Jan/2021 09:20:45] "GET /media HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 468, in wrapper
resp = resource(*args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 583, in dispatch_request
resp = meth(*args, **kwargs)
File "D:\server\norway_group\tokmatic-sass\python\start.py", line 22, in get
response = tikTokApi.userPage(data["id"],data["secUid"])
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\TikTokApi\tiktok.py", line 562, in userPage
return self.getData(url=api_url, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\TikTokApi\tiktok.py", line 159, in getData
verify_fp, did, signature = self.browser.sign_url(**kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\TikTokApi\browser.py", line 164, in sign_url
page = self.create_page()
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\TikTokApi\browser.py", line 116, in create_page
context = self.browser.newContext(**iphone)
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\playwright\sync_api.py", line 6710, in newContext
self._sync(
File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\playwright\_sync_base.py", line 95, in _sync
self._dispatcher_fiber.switch()
greenlet.error: cannot switch to a different thread
I thought that there is an issue with the TikTokApi package but when I try the same code outside the flask resource:
data = tikTokApi.getUserObject('rosiethepygmygoat')
response = tikTokApi.userPage(data["id"],data["secUid"])
print(response)
I get the object I need.
So am I missing a specific configuration for flask or something else? Any insights will be much appreciated.
Run your flask application using this comands:
flask run --without-threads

Flask error: werkzeug.routing.BuildError when connecting to web service

For educational purposes, we're building a very simple Flask app. While it runs smoothly locally, it no longer does when I copy the code to my virtual private server.
The route is defined as follows:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def sign_up():
...
This is the function that uses autocomplete:
with connection.cursor() as cursor:
sql = f"SELECT * FROM movies WHERE title"
query = cursor.execute(sql)
data = cursor.fetchall()
# from flask import jsonify
results = [data[i]['title'] for i in range(len(data))]
return render_template("autocomplete.html", results=results)
autocomplete.html is located in the templates folder, which sits next to the Python program file.
And the web service is started like this:
if __name__ == '__main__':
app.run(host='0.0.0.0')
I can start the web service successfully, but when I connect using the URL, it returns a 500 error, and the server console shows:
[2020-05-28 16:19:47,099] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/root/miniconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "app.py", line 94, in sign_up
return render_template("autocomplete.html", results=results)
File "/root/miniconda3/lib/python3.7/site-packages/flask/templating.py", line 140, in render_template
ctx.app,
File "/root/miniconda3/lib/python3.7/site-packages/flask/templating.py", line 120, in _render
rv = template.render(context)
File "/root/miniconda3/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render
self.environment.handle_exception()
File "/root/miniconda3/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
reraise(*rewrite_traceback_stack(source=source))
File "/root/miniconda3/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
raise value.with_traceback(tb)
File "/root/recommender/app-flask/templates/autocomplete.html", line 10, in top-level template code
$.getJSON("{{url_for('autocomplete')}}",{
File "/root/miniconda3/lib/python3.7/site-packages/flask/helpers.py", line 370, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 2216, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/root/miniconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/root/miniconda3/lib/python3.7/site-packages/flask/helpers.py", line 358, in url_for
endpoint, values, method=method, force_external=external
File "/root/miniconda3/lib/python3.7/site-packages/werkzeug/routing.py", line 2179, in build
raise BuildError(endpoint, values, method, self)
werkzeug.routing.BuildError: Could not build url for endpoint 'autocomplete'. Did you mean 'static' instead?
I assume this is because of a change in the URL, but I don't know how to solve this.
Can anyone help?
$.getJSON("{{url_for('autocomplete')}}",{
=> your code wrong at this line, read more about url_for in flask.
It's need to render route like: <blueprint_name>.<function_name> If use app as route use can skip blueprint_name => Ex: .sign_up
sample

Flask: peewee.OperationalError: no such table:

I'm trying to run https://github.com/swifthorseman/flask-peewee-heroku-setup locally on win 10, using python 3.6. I'm not sure if this project is designed to be run locally, maybe its only designed for heroku.
I have run the file teletubbies.py locally which created the db and table as you can see in the screenshot. To run it locally (or try to) I added the lines:
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
and I'm running it using
python server.py
The entire server.py file as I have it:
from flask import Flask, render_template, g
from tellytubbies import retrieve_all, db_proxy
app = Flask(__name__)
#app.before_request
def before_request():
g.db = db_proxy
g.db.connect()
#app.after_request
def after_request(response):
g.db.close()
return response
#app.route('/')
def index():
tellytubbies = retrieve_all()
return render_template("index.html", tellytubbies=tellytubbies)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
By stepping through the code I don't see an error until the line:
tellytubbies = retrieve_all()
Which then crashes giving the following Traceback:
Traceback (most recent call last):
File "....myfile\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "....myfile\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "....myfile\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "....myfile\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "....myfile\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "....myfile\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "....myfile\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "....myfile\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "....myfile\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "....myfile\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "...\server.py", line 18, in index
tellytubbies = retrieve_all()
File "...\tellytubbies.py", line 32, in retrieve_all
for tellytubby in TellyTubby.select().order_by(TellyTubby.name):
File "....myfile\lib\site-packages\peewee.py", line 3281, in __iter__
return iter(self.execute())
File "....myfile\lib\site-packages\peewee.py", line 3274, in execute
self._qr = ResultWrapper(model_class, self._execute(), query_meta)
File "....myfile\lib\site-packages\peewee.py", line 2939, in _execute
return self.database.execute_sql(sql, params, self.require_commit)
File "....myfile\lib\site-packages\peewee.py", line 3837, in execute_sql
self.commit()
File "....myfile\lib\site-packages\peewee.py", line 3656, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "....myfile\lib\site-packages\peewee.py", line 135, in reraise
raise value.with_traceback(tb)
File "....myfile\lib\site-packages\peewee.py", line 3830, in execute_sql
cursor.execute(sql, params or ())
peewee.OperationalError: no such table: tellytubby
The retrieve_all() function comes from the teletubbies.py file:
def retrieve_all():
results = []
for tellytubby in TellyTubby.select().order_by(TellyTubby.name):
results.append(tellytubby)
return results
the teletubbies.py does work when I run it as
python teletubbies.py
How can I get this working?
Your flask server works fine for me, after I run python teletubbies.py to initialize the sqlite database. However, if I remove the tellytubbies.db file that was created by running the script directly, the flask server fails with the same exception you quote.
Something to consider here is that when you run tellytubbies.py, the database file tellytubbies.db will be created in whatever directory you run it from. If you then run server.py from a different directory - for instance, if your IDE is running it - it won't find the other tellytubbies.db, so a new one will be created; but becase the tables were only created in your __main__ section in tellytubbies.py, the tables won't be created.
So your flask server needs to do some of the initialization that teletubbies.py is doing. I replaced the if __name__ == '__main__': section of your server.py with the following and it it works. It will work whether you keep the same database file or remove it between runs to start from scratch. I've added a check to make sure the same rows don't get inserted repeatedly.
if __name__ == '__main__':
from teletubbies import add_tellytubbies, TellyTubby
db_proxy.connect()
db_proxy.create_tables([TellyTubby], safe=True)
if TellyTubby.select().count() == 0:
add_tellytubbies()
app.run(debug=True, use_reloader=True)

Can't find Flask template specified by relative path

I am trying to render the index.html template in my Flask app's templates folder. However, I get a TemplateNotFound error. The template exists. How do I render it?
#app.route('/')
def index():
return render_template('../../templates/index.html')
Traceback (most recent call last):
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "G:\Projects\Intellij\Python\HelloPython\controller\web\WebHomeController.py", line 10, in webIndex
return render_template('../../templates/index.html', message=message)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\templating.py", line 133, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\jinja2\environment.py", line 869, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\jinja2\environment.py", line 830, in get_template
return self._load_template(name, self.make_globals(globals))
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\jinja2\environment.py", line 804, in _load_template
template = self.loader.load(self, name, globals)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\jinja2\loaders.py", line 113, in load
source, filename, uptodate = self.get_source(environment, name)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\templating.py", line 57, in get_source
return self._get_source_fast(environment, template)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\templating.py", line 85, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: ../../templates/index.html
render_template takes the name to be looked up by the Jinja env, which has the templates folder it its lookup path. Only specify the path after that.
# index.html is in the templates folder
render_template('index.html')
# users/detail.html is in a sub-folder under templates
render_template('users/detail.html')

Python Flask, Uploading a file - raise BuildError(endpoint, values, method)

I followed this tutorial for uploading files to a webserver via Flask, with the notable exception of the return part.
My intention is to upload pictures.
Here's my code:
from flask import Flask, request, jsonify, json, Blueprint, redirect, url_for, send_from_directory
from werkzeug import secure_filename
app = Flask(__name__)
allowed_extensions = set(['png', 'jpg', 'jpeg', 'gif', 'bmp'])
folder_upload = '/Users/myusername/Documents/Project_Upload/'
#CustomersAPI.route('/customers/addpicture', methods=['POST'])
def add_picture():
file = request.files['value']
print file.filename
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#return redirect(url_for('uploaded_file', filename=filename))
return str(url_for('uploaded_file', filename=filename))
return "Unable to upload."
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in allowed_extensions
if __name__ == '__main__':
app.config['UPLOAD FOLDER'] = folder_upload
app.run(host = '0.0.0.0', debug=True)
As I do not have the HTML files yet (hence the commented out return redirect), I use CocoaRestClient for testing, and here are the parameters I used:
Everything okay so far, until I hit the Submit button. Then, the following error appears:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/myusername/Documents/Project_Omnimoda/API/main.py", line 192, in add_picture
return redirect(url_for('uploaded_file', filename=filename))
File "/Library/Python/2.7/site-packages/flask/helpers.py", line 312, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1641, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/helpers.py", line 305, in url_for
force_external=external)
File "/Library/Python/2.7/site-packages/werkzeug/routing.py", line 1649, in build
raise BuildError(endpoint, values, method)
BuildError: ('uploaded_file', MultiDict([('filename', '3611571-dc_holiday.jpg')]), None)
Funny thing is, the image '3611571-dc_holiday.jpg' actually did get copied from my Downloads folder to the Project_Upload folder, so it worked, there's just an error that I'm not sure how to solve.
Any ideas? Thanks.
You haven't defined the uploaded_file endpoint. You need to do that.
#CustomersAPI.route('/customers/SOMETHINGOGESTHERE')
def uploaded_file(filename):
# Do something here with the file, like return it.
return send_from_directory(
folder_upload, filename, as_attachment=True)

Categories

Resources