简体   繁体   English

UnboundLocalError Python 烧瓶

[英]UnboundLocalError Python-flask

An UnboundLocalError occured when I try to query category from catogories table present in mysql database.当我尝试从 mysql 数据库中存在的目录表中查询类别时,发生 UnboundLocalError。 UnboundLocalError: Local variable 'category' referenced before assignment. UnboundLocalError:分配前引用的局部变量“类别”。 I am trying to add product to by database table product.我正在尝试通过数据库表产品添加产品。 I need to select the catogory of that product from categories table.我需要 select 类别表中该产品的类别。 I use query.all() to do so.我使用 query.all() 来做到这一点。 This is apps.py这是apps.py

@app.route('/AddProduct',methods=["GET", "POST"])
def add_product():
    if request.method =="POST":
        name=request.form['name']
        price=request.form['price']
        description = request.form['description']
        category = categories.query.all()
        image = request.files['image']
        if image and allowed_file(image.filename):
            filename = secure_filename(image.filename)
            image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #cursor = mysql.connection.cursor()
        #cursor.execute('SELECT * FROM categories')
        #account = cursor.fetchall()
        cursor.execute('INSERT INTO products VALUES(NULL,% s,% s,% s,% s,% s)',(name,price,description,image,categoryId))
        mysql.connection.commit()
    return render_template('Shopping.html',category=category)

This is my shopping.html file这是我的购物.html 文件

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Admin</title>
  </head>
  <body>
      <form action="/home" method="POST" enctype="multipart/form-data" class="register-form" id="register-form">
        <input type="text" name="name" id="name" placeholder="Product Name"/>
        <input type="" name="price" id="price" placeholder="price"/>
        <input type="text" name="description" id="description" placeholder="description"/>
         <input type="file" name="image"><br>
         <label for="category">ADD catogory</label>
         <select name="category" id="category" class="form-control" required>
           <option value="">Select a category</option>
           {% for cat in category %}
           <option value="cat.categoryId">{{cat.categoryName}}</option>
           {% endfor %}

         <input type="submit">
      </form>

It is because this line:这是因为这一行:

category = categories.query.all()

is executed only when a POST request is made.仅在发出 POST 请求时执行。 When you load the page for the first time (GET), the variable category is not initialized.首次加载页面 (GET) 时,变量category未初始化。

You can simply move this line to the top of the add_product routine, out of the if block.您可以简单地将这一行移到 add_product 例程的顶部,移出if块。

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

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