[英]How do I make input text from textboxes store in databse whilst preventing security flaws
我在 Flask 中有一个网站,它基本上是 Twitter 的克隆,其中我有一个用于记录推文的textarea
元素,我正在使用 MySQL 将推文发布到数据库。
现在的问题是,当有人发布包含符号的推文时, flask-mysql connector
无法将符号转换为文本,从而破坏了程序。 例如,当我发推文时:
# When I tweet this
The '%^&!@#:';.,}{][ characters break everything
在main.py
中使用以下代码:
# This code handles the tweet
conn = mysql.connect()
cursor = conn.cursor()
try:
cursor.execute(f"INSERT INTO tweets (username, tweet_content) values ('%s', %s)", (session['username'], content))
conn.commit()
success = True
except Exception as e:
print("!!!! error : ", e)
finally:
conn.close()
error
是:
!!!! error : (1064, "You have an error in your
SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use
near 'mohit2004'', 'The\\r\\n!@$@#%@%&^*%^!#%@!^%' at line 1")
我知道发生这种情况是因为无法将符号转换为文本字符串,并且在传递 tweet_text 时,' 符号会混合并破坏代码。
有没有一种方法可以将所有这些符号转换为可以存储到数据库中的东西,例如'
to &single_quote
, "
to &double_quote
类似的东西,然后在用户查看时将其转换回普通文本。
我在 inte.net 上找不到任何与此类服务相关的搜索词,而且我知道这个问题会非常投入,但如果您知道任何类似的服务,或者如果它们内置于 Flask 中,请让我知道。
编辑亮点: html.escape
function 在这种情况下不起作用。
您可以使用内置模块html
及其功能:
escape
将字符转换为 HTML 个实体。unescape
将 HTML 个实体转换为字符。这是你的例子:
>>> import html
>>>
>>> text = "The ' character breaks everything"
>>> html_text = html.escape(text)
>>> html_text
The ' character breaks everything
>>>
>>> html.unescape(html_text)
The ' character breaks everything
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.