织梦CMS - 轻松建站从此开始!

欧博ABG官网-欧博官方网址-会员登入

How to implement a search fun皇冠ction using a raw S

时间:2025-08-24 16:33来源: 作者:admin 点击: 1 次
I created a github with full solution for you :) https://github.com/researcher2/stackoverflow_57120430 A couple of things: Avoiding SQL Injection

I created a github with full solution for you :)

https://github.com/researcher2/stackoverflow_57120430

A couple of things:

Avoiding SQL Injection

I recommend using bindings when doing raw sql statements, my code reflects that. I spent ages trying to get this working with your statement before stumbling upon this:

Python SQLite parameter substitution with wildcards in LIKE

Basically you can't put bindings inside the LIKE '%?%' because the quotes cause the replacement token to be ignored.

Instead you just have to do LIKE ? and build the replacement manually.

Using Session

All session information is JSON serialized and then sent to the client. In this case the row records weren't JSON serializable. This showed up as an error for me:

TypeError: Object of type 'RowProxy' is not JSON serializable

I probably wouldn't use the session here as there is no need for the client to be aware of this, as you're going to build them a nice html page with the information anyway. Just use a python dictionary and pass it to the template engine. My code did use the session because this is what you started with.

In case github ever goes down:

from flask import request, render_template, session from 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")

(责任编辑:)
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:
发布者资料
查看详细资料 发送留言 加为好友 用户等级: 注册时间:2025-08-25 21:08 最后登录:2025-08-25 21:08
栏目列表
推荐内容