繁体   English   中英

如何在防止安全漏洞的同时将文本框中的输入文本存储在数据库中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM