Python UnboundLocalError:局部变量';参与者';分配前参考

Python UnboundLocalError:局部变量';参与者';分配前参考,python,variables,flask,Python,Variables,Flask,这个错误是显而易见的 @app.route('/list', methods=['GET', 'POST']) def list(): if request.method == 'POST': participant = Participant.query.all() return render_template('admin/list.html', participant=participant) 变量的范围就是问题所在,只需确保return语句位于list(

这个错误是显而易见的

@app.route('/list', methods=['GET', 'POST'])
def list():
    if request.method == 'POST':
        participant = Participant.query.all()
    return render_template('admin/list.html', participant=participant)

变量的范围就是问题所在,只需确保
return
语句位于
list()函数中即可解决此问题。此外,请确保避免使用保留用于命名函数或变量的python。

考虑一下如果request.method!=“POST”
?是的,它很有效,谢谢。这是否回答了您的问题?
@app.route('/list', methods=['GET', 'POST'])
def list():
    if request.method == 'POST':
        participant=Participant.query.all()
    return render_template('admin/list.html', participant=participant)
If you are fetching any value then you need to handle it with request or you can initialise participant before performing query on it. This error is because you haven't initialised participant before and referring it for query.
@app.route('/list', methods=['GET', 'POST']) 
def list():
 
 if request.method == 'POST':
    participant=request.args.get('participant')

    participant=Participant.query.all()
   
return render_template('admin/list.html', participant=participant)