前提
Flaskで非同期処理を実行するAPIシステムを作っています。
@app.route()からclassで定義した関数に引数を渡そうとした時に以下のエラーメッセージが発生しました。
実現したいこと
- @app.route()からclassで定義した関数に引数(session['text'])を渡せるようにする。
発生している問題・エラーメッセージ
127.0.0.1 - - [08/May/2022 15:13:13] "GET / HTTP/1.1" 200 - Exception in thread Thread-8: Traceback (most recent call last): File "/Users/admin/.pyenv/versions/3.9.7/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Users/admin/Documents/Python/Flask_Oauth-master/test3.py", line 25, in run print(session['text']) File "/Users/admin/.pyenv/versions/3.9.7/lib/python3.9/site-packages/werkzeug/local.py", line 422, in __get__ obj = instance._get_current_object() File "/Users/admin/.pyenv/versions/3.9.7/lib/python3.9/site-packages/werkzeug/local.py", line 544, in _get_current_object 127.0.0.1 - - [08/May/2022 15:13:13] "GET /?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 - 127.0.0.1 - - [08/May/2022 15:13:13] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 - 127.0.0.1 - - [08/May/2022 15:13:13] "GET /?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 - return self.__local() # type: ignore File "/Users/admin/.pyenv/versions/3.9.7/lib/python3.9/site-packages/flask/globals.py", line 33, in _lookup_req_object 127.0.0.1 - - [08/May/2022 15:13:13] "GET /?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 - raise RuntimeError(_request_ctx_err_msg) RuntimeError: Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.
該当のソースコード
Python
1from flask import Flask, render_template, session ,make_response,request 2import sched,time,threading 3from time import sleep 4 5app = Flask(__name__) 6app.secret_key = 'hogehoge' 7 8class MyThread(threading.Thread): 9 def __init__(self): 10 super(MyThread, self).__init__() 11 self.stop_event = threading.Event() 12 13 def stop2(self): 14 self.stop_event.set() 15 16 def run(self): 17 try: 18 for _ in range(1000): 19 print(session['text']) 20 time.sleep(3) 21 # 定期的にフラグを確認して停止させる 22 if self.stop_event.is_set(): 23 break 24 finally: 25 print('時間のかかる処理が終わりました\n') 26 27@app.route('/') 28def admin(): 29 with app.test_request_context(): 30 session['text'] = "成功" 31 t = MyThread() 32 t.start() 33 return make_response("出力成功") 34 35app.run(debug=True, host='localhost', port=3000, threaded=True)
試したこと
はじめはwithを使用せず実行していたのですが、エラー文で検索した所withを使用する公式ドキュメントを見つけ、現在の形で実行しました。ただドキュメントを見てもwithの配置場所やお作法がわからなかったため質問させていただきました。
よろしくお願いいたします。
あなたの回答
tips
プレビュー