如何从Jinja2模板文档中的Flask-SQLAlchemy Query对象访问属性?

时间:2022-03-20 20:46:16

Upon a successful login, I save the user object (from query) to the session dictionary.

登录成功后,我将用户对象(从查询中)保存到会话字典中。

When I try to access an attribute of the object in my Jinja template, I get an error.

当我尝试在Jinja模板中访问对象的属性时,出现错误。

Below are the codes for the affected parts:

以下是受影响部分的代码:

Python "views.py" file:

Python“views.py”文件:

session['in_session'] = True
session['active_user'] = user

Jinja2 "base.html" file:

Jinja2“base.html”文件:

{% if session.in_session %}
    <li><a href="">Signed in as {{session.active_user.username|safe|title}}!</a></li>
{%endif%}    


EDIT-1:
Here's the error traceback:

编辑-1:这是错误追溯:

TypeError

TypeError: is not JSON serializable Traceback (most recent call last)

TypeError:不是JSON可序列化的Traceback(最近一次调用最后一次)

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__

return self.wsgi_app(environ, start_response)

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app

response = self.make_response(self.handle_exception(e))

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception

reraise(exc_type, exc_value, tb)

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app

response = self.full_dispatch_request()

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1479, in full_dispatch_request

response = self.process_response(response)

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/app.py", line 1693, in process_response

self.save_session(ctx.session, response)

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/app.py", line 837, in save_session

return self.session_interface.save_session(self, session, response)

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/sessions.py", line 326, in save_session

val = self.get_signing_serializer(app).dumps(dict(session))

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/itsdangerous.py", line 537, in dumps

payload = want_bytes(self.dump_payload(obj))

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/itsdangerous.py", line 809, in dump_payload

json = super(URLSafeSerializerMixin, self).dump_payload(obj)

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/itsdangerous.py", line 522, in dump_payload

return want_bytes(self.serializer.dumps(obj))

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/sessions.py", line 85, in dumps

return json.dumps(_tag(value), separators=(',', ':'))

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/json.py", line 126, in dumps

rv = _json.dumps(obj, **kwargs)

File "/usr/lib/python2.7/json/__init__.py", line 250, in dumps

sort_keys=sort_keys, **kw).encode(obj)

File "/usr/lib/python2.7/json/encoder.py", line 209, in encode

chunks = list(chunks)

File "/usr/lib/python2.7/json/encoder.py", line 434, in _iterencode

for chunk in _iterencode_dict(o, _current_indent_level):

File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict

for chunk in chunks:

File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode

o = _default(o)

File "/home/acetakwas/web_dev/flask/flask_venv/lib/python2.7/site-packages/flask/json.py", line 83, in default

return _json.JSONEncoder.default(self, o)

File "/usr/lib/python2.7/json/encoder.py", line 184, in default

raise TypeError(repr(o) + " is not JSON serializable")

TypeError: <User 2: u'tak'; u'ace@tak.was'> is not JSON serializable


EDIT-2:
I've just figured that the issue is with storing the user object returned from my query as a dictionary value. So assuming I have a User class which extends Model (from the SQLAlchemy library), doing something like this will fail:

编辑-2:我刚刚想到的问题是将从我的查询返回的用户对象存储为字典值。假设我有一个扩展Model的User类(来自SQLAlchemy库),做这样的事情将会失败:

session['active_user'] = User.query.filter_by(username='my_user_name').first()

Why is that?

这是为什么?

1 个解决方案

#1


It would be helpful to post errors you are encountering. But if I had to guess, you stated session is a dict. In your code you are accessing session like an object. You should be able to simply do:

发布您遇到的错误会很有帮助。但是,如果我不得不猜测,你说会话是一个字典。在您的代码中,您将像对象一样访问会话。你应该能够做到:

{{session['active_user'].username|safe|title}}

#1


It would be helpful to post errors you are encountering. But if I had to guess, you stated session is a dict. In your code you are accessing session like an object. You should be able to simply do:

发布您遇到的错误会很有帮助。但是,如果我不得不猜测,你说会话是一个字典。在您的代码中,您将像对象一样访问会话。你应该能够做到:

{{session['active_user'].username|safe|title}}