Flask with Jinja2 throws AttributeError: 'TemplateData' object has no attribute 'data' - python

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.

Related

How would i fix this error in python WTForms?

I have attempted to make a Full-Feature Web App, and this includes using WTForms as the databasing resource, I am stumped at this error,
jinja2.exceptions.UndefinedError: 'wtforms.fields.core.StringField object' has no attribute 'username'
Traceback (most recent call last):
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 2328, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 2314, in wsgi_app
response = self.handle_exception(e)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 1760, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 2311, in wsgi_app
response = self.full_dispatch_request()
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 1834, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 1737, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 1832, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 1818, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/lkendon/flaskblog/flaskblog.py", line 36, in register
return render_template('register.html', title='Register', form=form)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/templating.py", line 135, in render_template
context, ctx.app)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/templating.py", line 117, in _render
rv = template.render(context)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/jinja2/asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/jinja2/environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/jinja2/_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "/Users/lkendon/flaskblog/templates/register.html", line 1, in top-level template code
{% extends "layout.html" %}
File "/Users/lkendon/flaskblog/templates/layout.html", line 41, in top-level template code
{% block content %}{% endblock %}
File "/Users/lkendon/flaskblog/templates/register.html", line 10, in block "content"
{{form.username.username(class="form-control form-control-lg")}}
jinja2.exceptions.UndefinedError: 'wtforms.fields.core.StringField object' has no attribute 'username'
What on earth is the issue here, I was following a tutorial and i have the same details inputted through the provided snippets.
Looking at the traceback, you're calling {{form.username.username(... which should be {{form.username(...

Flask Pdfkit create pdf from template and save it

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

Object of type 'bytes' is not JSON serializable when upgrading my python environment

I have developed an application in Flask that worked. I try to upgrade my environment from version 2.7 to 3.6.
When I am hitting an endpoint that is calling a form It generated the following error:
Traceback (most recent call last):
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/TheSwitchWebApp/controllers/account/register.py", line 15, in display_signup_form
form = RegisterForm(request.form)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/wtforms/form.py", line 212, in __call__
return type.__call__(cls, *args, **kwargs)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask_wtf/form.py", line 88, in __init__
super(FlaskForm, self).__init__(formdata=formdata, **kwargs)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/wtforms/form.py", line 278, in __init__
self.process(formdata, obj, data=data, **kwargs)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/wtforms/form.py", line 132, in process
field.process(formdata)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/wtforms/csrf/core.py", line 43, in process
self.current_token = self.csrf_impl.generate_csrf_token(self)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask_wtf/csrf.py", line 134, in generate_csrf_token
token_key=self.meta.csrf_field_name
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/flask_wtf/csrf.py", line 47, in generate_csrf
setattr(g, field_name, s.dumps(session[field_name]))
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/itsdangerous.py", line 565, in dumps
payload = want_bytes(self.dump_payload(obj))
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/itsdangerous.py", line 847, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/itsdangerous.py", line 550, in dump_payload
return want_bytes(self.serializer.dumps(obj))
File "/Users/Melvyn/Documents/personnel/python/TheSwitchWebApp/venv/lib/python3.6/site-packages/itsdangerous.py", line 51, in dumps
return json.dumps(obj, separators=(',', ':'))
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'bytes' is not JSON serializable
It generate this error when I'm hitting the following endpoint:
#register_endpoint.route('/', methods=['GET'])
def display_signup_form():
error = None
form = RegisterForm(request.form)
return render_template("auth/register.html", form=form, error=error)
The error seem to come from the form:
class RegisterForm(Form):
first_name = StringField('First name', [InputRequired(message='First name is mandatory')])
email = StringField('Email Address', [Email(), InputRequired(message='Forgot your email address?')])
I don't get the source of the error. In this piece of code I do not try to serialise in JSON anything. Where does the error come from?
As #Arpit Solanki mentioned, py2.x and py3.x are very different in case of encoding. You'd better clear your cookies in your browser, probably the browser had cookies set by python2 code, but your new python3 interpreted the cookie content as byte strings. Please clear your cookie will solve the issue.
You can also selectively wipe just the offending cookie.

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')

Flask error "cannot concatenate 'str' and 'NoneType' objects" when POSTing multipart form data

So I'm using flask to receive form data, which has worked fine with url-encoded data (application/x-www-form-urlencoded). I can just access the request.form in my routing functions.
However if I try to instead send data using multipart/form-data, I consistently get the error: TypeError: cannot concatenate 'str' and 'NoneType' objects
This error occurs as soon as I try to access the request form, e.g. the line:
f = request.form. So it's nothing to do how I'm actually using the form data. It also happens regardless if I send the data from Fiddler, Postman or my own custom Java app.
Am I missing some code in flask to handle multipart form data, or is the request somehow invalid? Here's an example request from postman that causes the error:
And here's the full traceback (Locus is my app, so only line 18/19 are from my own code):
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask_debugtoolbar\__init__.py", line 125, in dispatch_request
return view_func(**req.view_args)
File "D:\Programming\VS\Visual Studio 2013\Projects\Locus Backend\Locus Backend\locus\Routing.py", line 67, in url_api_create
f = request.form
File "C:\Python27\lib\site-packages\werkzeug\local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "C:\Python27\lib\site-packages\werkzeug\utils.py", line 71, in __get__
value = self.func(obj)
File "C:\Python27\lib\site-packages\werkzeug\wrappers.py", line 483, in form
self._load_form_data()
File "C:\Python27\lib\site-packages\flask\wrappers.py", line 165, in _load_form_data
RequestBase._load_form_data(self)
File "C:\Python27\lib\site-packages\werkzeug\wrappers.py", line 355, in _load_form_data
mimetype, content_length, options)
File "C:\Python27\lib\site-packages\werkzeug\formparser.py", line 193, in parse
content_length, options)
File "C:\Python27\lib\site-packages\werkzeug\formparser.py", line 99, in wrapper
return f(self, stream, *args, **kwargs)
File "C:\Python27\lib\site-packages\werkzeug\formparser.py", line 208, in _parse_multipart
form, files = parser.parse(stream, boundary, content_length)
File "C:\Python27\lib\site-packages\werkzeug\formparser.py", line 518, in parse
return self.cls(form), self.cls(files)
File "C:\Python27\lib\site-packages\werkzeug\datastructures.py", line 371, in __init__
for key, value in mapping or ():
File "C:\Python27\lib\site-packages\werkzeug\formparser.py", line 516, in <genexpr>
form = (p[1] for p in formstream if p[0] == 'form')
File "C:\Python27\lib\site-packages\werkzeug\formparser.py", line 475, in parse_parts
for ellt, ell in self.parse_lines(file, boundary, content_length):
File "C:\Python27\lib\site-packages\werkzeug\formparser.py", line 382, in parse_lines
next_part = b'--' + boundary
TypeError: cannot concatenate 'str' and 'NoneType' objects

Categories

Resources