简体   繁体   English

为什么我在 Flask 中收到 UnboundLocalError?

[英]Why i am getting UnboundLocalError in Flask?

this is my app.py code but i am receiving unbound local error after adding another path for delete and creating the function delete.这是我的 app.py 代码,但在添加另一个删除路径并创建 function 删除后,我收到未绑定的本地错误。

from crypt import methods
from email.policy import default
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todo.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


class Todo(db.Model):
    sno = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    desc = db.Column(db.String(200), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self) -> str:
        return f"{self.sno} - {self.title}"


@app.route('/', methods=['GET', 'POST'])
def hello_world():
    if request.method == 'POST':
        title = request.form["title"]
        desc = request.form["desc"]
    todo = Todo(title=title, desc=desc)
    db.session.add(todo)
    db.session.commit()
    mytodo = Todo.query.all()
    return render_template('index.html', mytodo=mytodo)


@app.route('/delete/<int:sno>')
def delete(sno):
    todo = Todo.query.filter_by(sno==sno).first()
    db.session.delete(todo)
    db.session.commit()
    return redirect('/')


if __name__ == "__main__":
    app.run(debug=True, port=8000)


Below i've added the screenshot of the errors i am getting even when i just visit the root url.下面我添加了我在访问根 url 时遇到的错误的屏幕截图。

错误

Problem问题

If the server receive a GET / , then you won't define te title variable, but would try to use it at Todo(title=title, desc=desc) so an error如果服务器收到GET / ,那么您将不会定义 te title变量,会尝试在Todo(title=title, desc=desc)处使用它,因此会出错


Fix使固定

All the creation code should be in the if POST branch所有创建代码都应该在if POST分支中

@app.route('/', methods=['GET', 'POST'])
def hello_world():
    if request.method == 'POST':
        title = request.form["title"]
        desc = request.form["desc"]
        todo = Todo(title=title, desc=desc)
        db.session.add(todo)
        db.session.commit()
    mytodo = Todo.query.all()
    return render_template('index.html', mytodo=mytodo)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM