在Flask中使用SQLAlchemy时发生AttributeError(“'list'对象没有属性'keys'”)。

2024-10-01 00:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉flask和python,当我尝试用“LIKE%s”从我的数据库检索flask应用程序时,我得到AttributeError(“'list'object has no attribute'keys'”),但如果我使用占位符“title=:result”,我将只检索一行,但不能使用LIKE子句,我只能检索数据库中的确切数据不知道如何检索解决我手头的问题,任何帮助都将不胜感激。在

在应用程序.py在

@app.route("/search",methods=['GET', 'POST'])
def search():    
  if request.method=='GET':
       return render_template("search.html")
       #search=request.form.get['search']
    else:
        try:
            res =request.form.get('search')
            likeString = "'%%"+res+"%%'"
            if likeString!="":
                #return (res)
                results=db.execute('''SELECT title FROM books WHERE title LIKE %s;''', likeString).fetchall()
                #results=db.execute("SELECT title FROM books WHERE title =:result",
                #{"result": res}).fetchall()
                if results is None:
                   return render_template("error.html", message="No such book")
                else:

                   return render_template("search.html",results=results)
            else:
                return ("you didn't enter a search value")

        except Exception as e:
                raise ValueError ("could not retrieve from database",e)

如果我能得到任何帮助,我将不胜感激。提前谢谢!在

回溯

^{pr2}$

Tags: 数据库flasksearchreturniftitlerequesthtml
2条回答

我强烈建议使用sqlalchemyorm功能,而不是构建自己的sql查询。首先你声明一个类

class Book(db.Model):
    __tablename__ = 'books'
    title = Column(String, primary_key = True)

然后你可以使用

^{pr2}$

谢谢大家我能解决我的问题我运行了这个查询

 res =request.form.get('search')
        #likeString = "'%%"+res+"%%'"
        if res!="":
            #return(res)
            results=db.execute("SELECT * FROM books WHERE (LOWER(isbn) LIKE LOWER(:res)) OR (LOWER(title) LIKE LOWER(:res)) OR (author LIKE LOWER(:res)) LIMIT 10",
            { "res": '%' + res + '%'} ).fetchall()

它对我有魔力!在

相关问题 更多 >