This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(14 answers)
Closed 7 years ago.
i use flask and i got this error when i call this url: /login
Here's my login method:
#app.route('/login')
def login():
if authenticateForPanel():
return redirect(url_for("panel"))
else:
getParam = request.args.getlist('redirect_uri')
if getParam:
ref =getParam[0]
else:
ref="/panel"
return render_template( themesDir + g.blogOptions['active_theme']+'/login.html', blogOptions = g.blogOptions, ref=ref )
And the traceback:
Traceback (most recent call last):
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/ozcan/Documents/python/app.py", line 209, in login
return render_template( themesDir + g.blogOptions['active_theme']+'/login.html', blogOptions = g.blogOptions, ref=ref )
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/templating.py", line 124, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/environment.py", line 758, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/environment.py", line 719, in get_template
return self._load_template(name, self.make_globals(globals))
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/environment.py", line 693, in _load_template
template = self.loader.load(self, name, globals)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/loaders.py", line 115, in load
source, filename, uptodate = self.get_source(environment, name)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/templating.py", line 61, in get_source
raise TemplateNotFound(template)
TemplateNotFound: static/themes/default/login.html
I am absolutely sure the login.html is there(static/themes/default/404.html).Why can this occur?
You put your template in the wrong place. From the Flask docs:
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:
See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates
I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.
Related
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__)
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
I use pdfkit to create an invoice pdf. At the moment I just want to save it. Later I will save the invoice filename in the DB and store in on AWS3.
But for now I get an IO Error when trying to save the file, probably because I request it the wrong way:
pdfkit.from_file(render_template('invoice_template.html', invoice_id=1, invioce_date_start=str(date.today()),
invioce_date_end=str(date.today()), invioce_company_name=form.zahlung_firma.data, invioce_user_vorename=form.vorname.data,
invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')
The Error:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Python27\lib\site-packages\flask_login.py", line 758, in decorated_view
return func(*args, **kwargs)
File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 114, in decorated_function
return func(*args, **kwargs)
File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 1252, in logged_in
invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')
File "C:\Python27\lib\site-packages\pdfkit\api.py", line 47, in from_file
configuration=configuration, cover_first=cover_first)
File "C:\Python27\lib\site-packages\pdfkit\pdfkit.py", line 41, in __init__
self.source = Source(url_or_file, type_)
File "C:\Python27\lib\site-packages\pdfkit\source.py", line 12, in __init__
self.checkFiles()
File "C:\Python27\lib\site-packages\pdfkit\source.py", line 32, in checkFiles
raise IOError('No such file: %s' % self.source)
IOError: No such file: <!doctype html>
The template itself can be found here, I just edited the jinja variables:
pdfkit.from_file() expects a file object as its input, but render_template() returns a string. Try pdfkit.from_string() instead.
More information: pypi - pdfkit
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')
I am trying to render a simple Jinja template. No matter what the template is, or what variables are passed to it, I get an error when trying to render. Why am I getting this error and how do I fix it?
frontend = Blueprint('frontend', __name__, template_folder='templates')
#frontend.route('/')
def index():
stuff = dict()
stuff['page_title'] = 'Something'
stuff['center_piece'] = 'Random'
return render_template('base.html', stuff=stuff)
Basic template, without variables, still causes error.
<html>
<head>
<title>Something</title>
</head>
<body>Something else</body>
</html>
File "/env/lib/python3.4/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/env/lib/python3.4/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/env/lib/python3.4/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/env/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/env/lib/python3.4/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/env/lib/python3.4/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/env/lib/python3.4/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/env/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/env/lib/python3.4/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/env/lib/python3.4/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/app/frontend/controller.py", line 12, in index
return render_template('base.html', stuff=stuff)
File "/env/lib/python3.4/site-packages/flask/templating.py", line 127, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/env/lib/python3.4/site-packages/jinja2/environment.py", line 851, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/env/lib/python3.4/site-packages/jinja2/environment.py", line 812, in get_template
return self._load_template(name, self.make_globals(globals))
File "/env/lib/python3.4/site-packages/jinja2/environment.py", line 786, in _load_template
template = self.loader.load(self, name, globals)
File "/env/lib/python3.4/site-packages/jinja2/loaders.py", line 125, in load
code = environment.compile(source, name, filename)
File "/env/lib/python3.4/site-packages/jinja2/environment.py", line 555, in compile
defer_init=defer_init)
File "/env/lib/python3.4/site-packages/jinja2/environment.py", line 515, in _generate
return generate(source, self, name, filename, defer_init=defer_init)
File "/env/lib/python3.4/site-packages/jinja2/compiler.py", line 62, in generate
generator.visit(node)
File "/env/lib/python3.4/site-packages/jinja2/visitor.py", line 38, in visit
return f(node, *args, **kwargs)
File "/env/lib/python3.4/site-packages/jinja2/compiler.py", line 816, in visit_Template
self.blockvisit(node.body, frame)
File "/env/lib/python3.4/site-packages/jinja2/compiler.py", line 492, in blockvisit
self.visit(node, frame)
File "/env/lib/python3.4/site-packages/jinja2/visitor.py", line 38, in visit
return f(node, *args, **kwargs)
File "/env/lib/python3.4/site-packages/jinja2/compiler.py", line 1250, in visit_Output
const = child.as_const(frame.eval_ctx)
File "/env/lib/python3.4/site-packages/jinja2/nodes.py", line 467, in as_const
return Markup(self.data)
AttributeError: 'TemplateData' object has no attribute 'data'
I got this error when I refactored a variable called data to data_repo in PyCharm and somehow changed my Jinja2 installation's "nodes.py" file as well. This is the function that throws the error:
class TemplateData(Literal):
"""A constant template string."""
fields = ('data',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
if eval_ctx.autoescape:
return Markup(self.data)
return self.data
My refactor changed the string in the fields tuple but not the return value, leading to an AttributeError with any template.