top of page

Flaskとpythonを学ぼう その1:グローバル変数

執筆者の写真: snackvirtualsnackvirtual

まずはグローバル変数の確認(下記はstateがグローバル変数)

def定義の外に書くのと、def内で「global 変数名」とすることで、代入が可能となる

from flask import *  # 必要なライブラリのインポート 

app = Flask(__name__)  # アプリの設定

print("---------------before function-----------------")
state = 1

@app.route('/room/talk/data/<contents>', methods=['GET'])
def get_data(contents):
    
    global state
    state = state + 1
    print(state)
    print("---------------CONTENTS-----------------")
    print(contents + "  " + str(state))

    return contents + "  " + str(state)
    
print("---------------after function-----------------")


if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=8888, threaded=True)

print("---------------end-----------------")

これを実行すると

PS D:\htdocs> & C:/Python310/python.exe d:/htdocs/room/Fee_communication.py
---------------before function-----------------
---------------after function-----------------
 * Serving Flask app 'Fee_communication'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:8888
 * Running on http://192.168.0.50:8888
Press CTRL+C to quit
 * Restarting with stat
---------------before function-----------------
---------------after function-----------------
 * Debugger is active!
 * Debugger PIN: 229-769-619

なぜだか2回実行しているけど、まあ気にせず、Chromeに

「localhost:8888/room/talk/data/テストです」と入力してアクセスすると、

アクセスするたびに



のように数字がインクリメントしていく

閲覧数:0回0件のコメント

最新記事

すべて表示

Comments


bottom of page