2017-12-27 3 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)을 벗으려고 시도했지만 여전히 같은 오류를 보여줍니다. 왜? 귀하가 제공 할 수있는 답변에 대해 감사드립니다. 에 데이터베이스에 HTML을 작성할 때 일반적으로 사용되는

+0

여기서 SQL 쿼리는 무엇입니까? – furas

답변

0

솔루션 :)

1 간단하게 데이터베이스 필드 형식을 변환은) 너무 블롭는 바이너리 데이터를 수신 한 후 아래의 바이너리 (예에 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() 
관련 문제