'local variable 'allLibrary' referenced before assignment

I can't seen to understand what the issue here is, I am getting an error that local variable 'allLibrary' referenced before assignment, Please help

@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) 


Solution 1:[1]

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.

So to fix this make sure that the allLibrary variable is declared before you're accessing it. It could also be a Scope problem.

However it would seem that library is not assigned a value if the if statement fails, so you should probably ensure that that is within scope as well.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Liam