如何将我的unicode字典转换为纯文本

时间:2017-07-22 16:19:35

标签: python jinja2 flask-sqlalchemy

我想在python和flask中使用jinja 2来显示我的消息。消息发布在sql数据库中,我想要检索它。到目前为止,我的server.py文件如下所示:

message_pull = mysql.query_db("SELECT messages.id, messages.user_id, 
messages.message, messages.created_at, users_table.first_name, 
users_table.last_name FROM messages JOIN users_table ON messages.user_id = 
users_table.id")
messages= mysql.query_db('SELECT * FROM messages')
print messages
return render_template('loggedin.html', messages = messages)

和我对应这个应用程序路线的html页面如下所示:

<p>{{messages}}</p>

它会在网页上显示如下:

[{u'created_at': datetime.datetime(2017, 7, 21, 14, 1, 58), u'message': u'We are posting for the first time out here!', u'user_id': 26L, u'id': 1L, u'updated_at': datetime.datetime(2017, 7, 21, 14, 1, 58)}, {u'created_at': datetime.datetime(2017, 7, 21, 14, 32, 3), u'message': u'This is the second post', u'user_id': 26L, u'id': 2L, u'updated_at': datetime.datetime(2017, 7, 21, 14, 32, 3)}]

如何将其显示为没有字典格式的常规帖子和&#34; u&#34;在每个键和值之前?

1 个答案:

答案 0 :(得分:0)

你有几个选择来解决这个问题:

不要在unicode中对数据库进行编码,只需将其存储为字符串信息即可。它不是非常用户友好,编码/解码步骤只是额外的不必要的工作。

或者,假设在方法中运行以下代码:

# i'm presuming the string data you provided is what's in this array
messages = mysql.query_db('SELECT * FROM messages')

# create a list to store our encoded messages in so we can return them
encoded_messages = []

for message in messages:
    # create a new dict to store the encoded information in
    message_info = dict()

    for key in message:
        if type(message[key]) == String:
            message_info[key.encode()] = message[key].encode()
        else:
            message_info[key.encode()] = message[key]

    # store our encoded message
    encoded_messages.append(message_info)

# return our info
return encoded_messages

老实说,在网站上显示数据结构并不是一个好主意。除非你对数据库的安全性非常有信心,否则它真的不安全。 (即便如此,这不是一个好主意)除此之外,用这种方式呈现数据对用户不是很友好。

回读你的问题,我怀疑你也希望能够以某种方式呈现数据。有很多方法可以做到这一点,但答案并不真正属于这里。我建议调查各种其他网站的方式。