我有一個小的Python/Flask web應用程序,它以CSV格式從SQLite表中返回數據。我發現使用sqlite3
命令行程序將查詢結果直接導出到CSV文件然後返回CSV文件比將查詢結果讀入Python,將它們寫入到內存文件然後返回內存中的文件。但是,使用sqlite3
程序意味着我必須自己構建查詢,使我的應用程序受到SQL注入攻擊。在Python中構建SQLite查詢,但使用sqlite3命令行程序執行它?
快,但容易受到SQL注入式攻擊
queries = """
.mode csv
.headers on
.output /tmp/results.csv
SELECT * FROM mytable WHERE foo = '{0}';
""".format(user_input)
subprocess.check_output(
["sqlite3", "/path/to/mydb.sqlite"], input=bytes(queries.encode("utf-8")))
return send_file("/tmp/results.csv", mimetype="text/csv")
從SQL注入安全,但速度較慢
conn = sqlalchemy.create_engine("sqlite:////path/to/mydb.sqlite")
result = conn.execute("SELECT * FROM mytable WHERE foo = ?", (user_input,))
csvfile = io.StringIO()
csvwriter = csv.writer(csvfile)
csvwriter.writerow(result.keys())
for row in result.fetchall():
csvwriter.writerow(row)
return Response(csvfile.getvalue(), mimetype="text/csv")
有沒有一種方法,我可以使用Python庫(SQLAlchemy的, sqlite3模塊或其他任何東西)來構建一個從SQL注入安全但不真正執行查詢的查詢,這樣我就可以通過子進程使用0來執行查詢命令行程序?