0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

変数のスコープについて。。。

0
Last updated at Posted at 2020-10-08

flaskを使ってローカルサーバを立ち上げ、
ToDoタスクのwebアプリケーションを出力する。

その後、テンプレをアレンジしてflask runを実行したところ以下のエラーが発生。

app.py
UnboundLocalError: local variable 'count' referenced before assignment

以下、エラーになった部分を抜粋

app.py
count = 0
@app.route("/updatedone/<int:item_id>")
def update_todoitemdone(item_id):
    todolist.update(item_id)
    count = count + 1
    return render_template("showtodo.html", todolist=todolist.get_all(), result=count)

関数外で宣言された変数countを
関数内でも使用する場合、グローバル宣言する必要があった。

以下、修正後。

app.py(修正後)
count = 0
@app.route("/updatedone/<int:item_id>")
def update_todoitemdone(item_id):
    todolist.update(item_id)
    global count
    count = count + 1
    return render_template("showtodo.html", todolist=todolist.get_all(), result=count)

doneを押すたびに数値が加算されるようになった!(('ω')ノ


↓参考記事↓
VS CodeとFlaskで作成するToDoリストアプリ


0
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?