首页 > 解决方案 > 在 postgreSQL 中查询数据时出错

问题描述

在我的书评flaskwebapp 中,我正在尝试添加搜索功能。用户应该能够通过 isbn 号、书名或书的作者来搜索这本书。但是,我收到此错误TypeError: unhashable type: 'dict'

这是我在application.py

@app.route('/search',methods=['GET','POST'])
def search():
    if request.method == 'GET':
        return render_template("search.html")

    else:
        text = request.form.get("search")
        books = db.execute("SELECT * from books WHERE isbn = :isbn OR title = :title OR author = :author",
                {"isbn":text},{"title":text},{"author":text})
        if books is None:
            return render_template("notfound.html")

这是我在数据库中的书籍表,其中添加了 5000 本书。

Table "public.books"
 Column  |         Type          | Collation | Nullable |                Default                 
---------+-----------------------+-----------+----------+----------------------------------------
 isbn    | character varying(30) |           | not null | 
 title   | character varying(30) |           | not null | 
 author  | character varying(30) |           | not null | 
 year    | character varying(30) |           | not null | 
 book_id | smallint              |           | not null | nextval('books_book_id_seq'::regclass)

这是我的数据库的定义方式:

import os

from flask import Flask, session, render_template, request, redirect, url_for, flash
from passlib.apps import custom_app_context as pwd_context
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

app = Flask(__name__)

# Check for environment variable
if not os.getenv("DATABASE_URL"):
    raise RuntimeError("DATABASE_URL is not set")

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))

标签: databasepython-3.xpostgresqlflasksqlalchemy

解决方案


推荐阅读