2017-12-27 17 views
-3

私はFlaskを使ってWebappを開発しています。いくつかの時点で、私は、MySQLデータベースに特定のHTMLスクリプトを挿入する必要があります。タイプエラーを示すmysqlデータベースにHTMLを挿入

(それはフラスコの「render_template」関数によって返されたときに)私はデータベースに挿入
<h3>Welcome!</h3> 
<p>Some text</p> 

\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シリアライズ可能な」という意味を理解していない、と私は私が間違っているのかを知りたいです。私はすでに改行(\n)を削除しようとしましたが、それでも同じエラーが表示されます。どうして?私はあなたが提供できる答えに感謝しています。

+0

ここで、SQLクエリはありますか。 – furas

答えて

0

にデータベースにHTMLを書くときに一般的に使用されるA液:

1)は、単にそれがバイナリデータを受け入れ、次いで、以下バイナリ(例えば)にHTMLをコードするBLOBにデータベース・フィールド・タイプを変換します。 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() 
関連する問題