flask的数据库操作-防范sql注入

最近写代码,用flask的次数比较多。

这货还真是挺好用的,简单方便。

不过,写web程序,一切用户数据都是脏数据,需要防范各种攻击(xss啦,sqlinjection啦)。

sql注入(sql injection)是最最常见的web攻击方式了。查看

刚熟悉写flask的时候(其实也就是几天前),代码都是这样的:

1
2
3
con = get_db()
c = con.cursor()
c.execute("update user set email='{}',password='{}'".format(email,password))

看起来就怪怪的……

果然,查阅文档后:

Security Note

Be sure to use question marks when building SQL statements, as done in theexample above. Otherwise, your app will be vulnerable to SQL injection when you use string formatting to build SQL statements.See Using SQLite 3 with Flask for more.

所以说,还是这种方式会安全:

1
2
3
con = get_db()
c = con.cursor()
c.execute("insert or IGNORE INTO user (email,password,level) values (?,?,1)" , [email,password])

算是个小tips吧~