赋值前引用的局部变量 'allLibrary'

local variable 'allLibrary' referenced before assignment

我看不明白这里的问题是什么,我收到一个错误,局部变量 'allLibrary' 在赋值前被引用,请帮助

@app.route('/', methods =['GET','POST'])
def add():
    if request.method =='POST':
        bookName=(request.form['bookName'])
        authorName =(request.form['author'])
        genre = request.form['type']
        library = library(bookName=bookName, authorName=authorName, genre = genre)
        db.session.add(library)
        db.session.commit()    
    allLibrary = library.query.all()
    
    return render_template('index.html', allLibrary=allLibrary) 

The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.

因此,要解决此问题,请确保在访问 allLibrary 变量之前对其进行声明。也可能是 Scope 问题。

然而,如果 if 语句失败,似乎 library 没有被赋值,所以您应该确保它也在范围内。