簡體   English   中英

我不斷收到 TypeError: can only concatenate str (not "NoneType") to str

[英]I kept getting TypeError: can only concatenate str (not “NoneType”) to str

我一直在嘗試運行此代碼,但一直收到類型錯誤,我搜索了 web 但沒有找到解決問題的方法。 注意:這是整個代碼的一小部分

@app.route("/search", methods = ["GET", "POST"])
def search():
    if "user_email" not in session:
        return render_template("sign.html", error="Please Login First", work="Failed")

    if request.method == 'GET':
        title = request.form.get('title')
        isbn = request.form.get('isbn')
        author = request.form.get('author')     
        searchs = db.execute("SELECT * FROM books WHERE author iLIKE '%"+author+"%' OR title iLIKE '%"+title+"%' OR isbn iLIKE '%"+isbn+"%'").fetchall()
        return render_template('search.html', work = 'Success', searchs = searchs )

作為初學者,該問題的一個相當簡單的解決方案是對每個變量運行單獨的查詢,如果它們被提供,並將它們合並到模板的單個列表中(我們可以擺脫這個,因為我們總是查詢相同的表,因此 output 行將始終具有相同的結構)。

@app.route("/search", methods = ["GET", "POST"])
def search():
    if "user_email" not in session:
        return render_template("sign.html", error="Please Login First", work="Failed")

    if request.method == 'GET':
        # Make a list to hold the results.
        searches = []
        title = request.form.get('title')
        if title is not None:
            titles = db.execute("SELECT * FROM books WHERE title ILIKE %s", ('%'+title+'%',)).fetchall()
            searchs.extend(titles)
        isbn = request.form.get('isbn')
        if isbn is not None:
            isbns = db.execute("SELECT * FROM books WHERE isbn ILIKE %s", ('%'+isbn+'%',)).fetchall()
            searchs.extend(isbns)
        author = request.form.get('author')    
        if author is not None:
            authors = db.execute("SELECT * FROM books WHERE author ILIKE %s", ('%'+author+'%',)).fetchall()
            searchs.extend(authors) 
        return render_template('search.html', work = 'Success', searchs = searchs )

有更好的方法可以做到這一點,但現在應該可以了。 注意查詢的形式

result = db.execute("SELECT thing FROM table WHERE thing = %s", (value,))

ensures that the query values are sent to the database in the format it expects (they are "quoted", in the jargon), and prevents SQL injection attacks, when a malicious user enters SQL scripts into your web form to see if they can download數據庫中的數據,或者更改或刪除其中包含的數據。

我假設您收到此錯誤,因為 request.form.get() 返回 None 值。 此外,request.form 用於檢索 POST 數據,但您似乎將其用於 GET 請求。

過去,我使用此命令從 GET 請求中獲取參數

search = request.args.get("search_query", "")

request.args.get 中的第二個參數是默認值

the.fetchall() 不需要,可能是原因,你應該使用 db.engine.execute()

query = ('SELECT State_name, count(State_name) FROM "University" group by State_name')

res = db.engine.execute(query)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM