Flask receives a request from a client, let the view function can access the request object request, in order to process the request. We can request an object as a parameter passed to try to function in, such as:
Import the Flask Flask from, request App = the Flask (name__ __) @ app.route ( '/') DEF the hello_world (request): # where the request object as a parameter passed in Data = request.json return 'Hello World' IF = the __name__ = '__main__': app.run ()
But we may also use some other object, which passed around, affecting not only simple, but also prone to error.
To solve this problem, use the "request context", the request object "as a" global variables, that is, that a single thread is a global variable, but the request object A thread A thread is the only global variables, not thread in B global variables, in order to ensure that the request object is not confusing error
So usually we write on it:
from flask import Flask, request app = Flask(__name__) @app.route('/') def hello_world(): data = request.json return 'hello world' if __name__ == '__main__': app.run()
That is the request object can be accessed only a single thread, A thread can not access the request object B thread. For example, we use asynchronous thread pool, function sub-thread access request can not be honored, for example:
Import the Flask the Flask from, Request Import Time from concurrent.futures Import ThreadPoolExecutor App = the Flask (__ name__) Executor = ThreadPoolExecutor (2) @ app.route ( '/') DEF update_redis (): executor.submit (do_update) # Here we open a thread, running do_update return 'the Hello world' DEF do_update (): r_json request # = program will be stuck in here, because the child thread can not access the request object in the main thread of the time.sleep (5) Print ( 'Start Update', r_json, type (Request)) IF the __name__ == '__main__': app.run ()
So how do we solve this problem, with the most simple way is to request object in the main thread as a parameter to the sub-thread function. For example:
Import the Flask Flask from, Request Import Time from the ThreadPoolExecutor concurrent.futures Import App = the Flask (__ name__) Executor = the ThreadPoolExecutor (2) @ app.route ( '/') DEF update_redis (): r_json = request.json executor.submit (do_update , (r_json)) # json the data request object as a parameter passed to the sub-thread processing function return 'Hello World' DEF do_update (r_json): the time.sleep (. 3) Print ( 'Start Update', r_json) IF == the __name__ '__main__': app.run ()
This can solve the problem child thread can not access the data request of the object in the main thread. If there is a better way, I wish to contact, mutual exchanges and common progress.