将HTML插入到mysql数据库中,显示类型错误

时间:2017-12-27 12:52:24

标签: python mysql json flask mysql-python

我正在使用Flask开发Web应用程序。在某些时候,我必须将某个HTML脚本插入MySQL数据库:

<h3>Welcome!</h3>
<p>Some text</p>

当我将它插入数据库时​​(当它被烧瓶&#39; render_template&#39;函数返回时):

\n\n<h3>Welcome!</h3>\n\n\n\n<p>Some text</p>

我收到以下错误:

  

TypeError: ProgrammingError(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '\\\\\\\\n\\\\n<h3>Welcome!</h3>\\\\n\\\\n\\\\n\\\\n<p>Some text' at line 1") is not JSON serializable

我首先不明白什么是JSON可序列化的&#39;意思是,我想知道我做错了什么。我已经尝试取消换行符(\n)但它仍然显示相同的错误。为什么?我很感谢您提供的任何答案。

1 个答案:

答案 0 :(得分:0)

将HTML写入数据库时​​常用的解决方案:

1)只需将数据库字段类型转换为blob,即可接受二进制数据,然后将HTML编码为二进制(以下示例)。 2)将数据库字段保留为文本字段,但base64对数据进行编码,以便数据库不会抱怨非法字符。

# Example for case 1.
# Note that you need to make sure the database field is a blob:
html = '<h3>Welcome!</h3>\n<p>Some text</p>'
bin = html.encode()
dbhandle.execute('INSERT INTO script (various fields, binhtml) VALUES (..., bin)')
# When you read back the data, remember to decode.
dbhandle.execute('SELECT binhtml FROM script WHERE...')
resultset = dbhandle.fetchall()
htmlresult = resultset.decode()

# Example for case 2.
# Database field can be a text/varchar type because base64 ensures it will work.
import base64
html = '<h3>Welcome!</h3>\n<p>Some text</p>'
# Convert HTML into base64 encoded *text* so it can be stored in text field.
encoded =  base64.b64decode(html.encode()).decode()
# Do the database INSERT.
...
# Retrieve the stored text from the database and convert back to HTML
dbhandle.execute('SELECT encodedhtml FROM script WHERE...')
resultset = dbhandle.fetchall()
htmlresult = base64.b64decode(resultset).decode()