是否可以将URL查询字符串值中的变量设置为SQLite3 LIMIT值?例如,当用户打开带有查询字符串?per_page = 10的端点/城市时,网站只返回来自城市的10个元素。
当我在LIMIT浏览器返回sqlite3.OperationalError: no such column: limit_page
from flask import (
Flask,
g,
redirect,
render_template,
request,
url_for,
jsonify,
) import sqlite3, itertools
app = Flask(__name__)
DATABASE = 'database.db'
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
@app.route('/cities')
def city_list():
limit_page = request.args.get('per_page')
db = get_db()
data = db.execute('''
SELECT city FROM city LIMIT *limit_page*
''').fetchall()
data_json = []
for i in data:
data_json.extend(list(i))
return jsonify(data_json)
if __name__ == '__main__':
app.run(debug=True)
答案 0 :(得分:0)
使用参数化查询:
limit_page = request.args.get('per_page')
if limit_page is not None:
query = 'SELECT city FROM city LIMIT ?'
args = (limit_page,)
else:
query = 'SELECT city FROM city'
args = ()
db = get_db()
data = db.execute(query, args).fetchall()
这将安全地将来自GET args的per_page
值插入到SQL查询中并执行它。使用参数化查询可以避免常见的SQL注入攻击。