我为您创建了一个具有完整解决方案的github :)
https://github.com/researcher2/stackoverflow_57120430
有两件事:
避免SQL注入
我建议在执行原始sql语句时使用绑定,我的代码反映了这一点。我花了很长时间尝试使它与您的陈述相符,然后才绊倒于此:
在LIKE中使用通配符替换Python
SQLite参数
基本上,您不能将绑定放在LIKE’%?%’内,因为引号会导致替换令牌被忽略。
相反,您只需要执行LIKE?并手动建立替代品。
使用会议
所有会话信息都是JSON序列化的,然后发送到客户端。在这种情况下,行记录不是JSON可序列化的。这对我来说是一个错误:
TypeError: Object of type 'RowProxy' is not JSON serializable
我可能不会在这里使用该会话,因为客户端不需要知道这一点,因为无论如何您将用信息来构建一个漂亮的html页面。只需使用python字典并将其传递给模板引擎即可。我的代码确实使用了会话,因为这是您开始的过程。
万一github崩溃了:
from flask import request, render_template, sessionfrom app import app, db@app.route("/", methods=['GET','POST'])def index(): if request.method == "POST": searchQuery = request.form.get("searchQuery") print(searchQuery) # Avoid SQL Injection Using Bindings sql = "SELECt isbn, author, title FROM book WHERe isbn LIKE :x OR author LIKE :y OR title LIKE :z" # I spent an hour wondering why I couldnt put the bindings inside the wildcard string... # https://stackoverflow.com/questions/3105249/python-sqlite-parameter-substitution-with-wildcards-in-like matchString = "%{}%".format(searchQuery) stmt = db.text(sql).bindparams(x=matchString, y=matchString, z=matchString) results = db.session.execute(stmt).fetchall() print(results) session["books"] = [] for row in results: # A row is not JSON serializable so we pull out the pieces book = dict() book["isbn"] = row[0] book["author"] = row[1] book["title"] = row[2] session["books"].append(book) return render_template("index.html", searchedFor=searchQuery, books=session["books"]) return render_template("index.html")


