使用线程时如何将变量传递给Flask函数?

时间:2019-11-07 07:58:43

标签: python flask python-multithreading

我想创建多个线程,每个线程都应创建flask应用程序。 我不确定该怎么做,但这就是我所拥有的:

app = Flask(__name__)
app.url_map.strict_slashes = False

@app.route('/api/v1/something/<string:FirstArgument>/<string:SecondArgument>/', methods=['POST'])
def do_it(FirstArgument, SecondArgument):
request_str = request.get_data().decode('utf-8').strip()
response = somefunction(mydata.state, request_str)
return response, 200

def run_app(this_port, mydata):
    currentThread = threading.current_thread()    
    mydata.state = some_function_that_returns_6GB_of_data()    
    app.run(host='0.0.0.0',port=this_port)

if __name__ == '__main__':
    mydata = threading.local()
    thread1 = Thread(target=run_app, args=(4100, mydata,))
    #thread2 = Thread(target=run_app, args=(4101,mydata,))
    thread1.start()
    #thread2.start()

现在我只想测试一个线程。而且我不知道如何将mydata.state传递给'do_it'。如果我添加新的参数(def do_it(FirstArgument,SecondArgument,mydata.state)),Flask表示他想从app.route获取此变量。如何将这些数据传递给do_it函数?

还有一个问题。该程序会将N个状态实例传递给N个端口上的N个线程吗? 或者我应该做这样的事情:

def do_it(FirstArgument, SecondArgument):
    request_str = request.get_data().decode('utf-8').strip()
    response = somefunction(mydata.state[threading.get_ident()], request_str)
    return response, 200

def run_app(this_port, mydata):
    currentThread = threading.current_thread()
    mydata.state[threading.get_ident()] = some_function_that_returns_6GB_of_data()
    app.run(host='0.0.0.0',port=this_port)

0 个答案:

没有答案