Far*_*nii 5 python multithreading flask
i just learn about flask and requests. i want to get the number of working threads when i post request to the server. and i want to measure the time spent of the working threads. so this is my server and my client code:
server.py
from flask import Flask
from flask import request
import time
from flaskthreads import AppContextThread
app = Flask(__name__)
@app.route("/", methods = ['GET', 'POST'])
def home():
timeout = time.time() + 10 # 5 minutes from now
while True:
test = 0
if test ==5 or time.time() > timeout:
break
return 'Hello', 200
def main():
app.run(host='0.0.0.0', threaded = True, debug = True)
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
client.py
import os
import requests
import glob
import time
import base64
url = 'http://0.0.0.0:5000/'
def load_data():
os.chdir('./500_mb')
for image in glob.glob('*.jpg'):
with open(image, 'rb') as imageFile:
# image_s = base64.b64encode(imageFile.read())
image_s = {'file_image':open(image, 'rb')}
return image_s
def send_data():
start = time.time()
r = requests.post(url, files = load_data())
end = time.time()
print('client 1: {} ms'.format((end - start)*1000))
if __name__ == "__main__":
send_data()
Run Code Online (Sandbox Code Playgroud)
how do i know the number of working threads ? i just add threaded = True on the server. i've been searching the answer and none of them answer my question. thanks in advance !
首先,通常的免责声明:这几乎无关紧要,因为您可以在实际移动到部署服务器时指定这一点。
然而,我自己很好奇,所以我决定追溯。
起点是在app.run()所以让我们看看它的作用:
def run_command(
info, host, port, reload, debugger, eager_loading, with_threads, cert, extra_files
):
...
from werkzeug.serving import run_simple
run_simple(
host,
port,
app,
use_reloader=reload,
use_debugger=debugger,
threaded=with_threads,
ssl_context=cert,
extra_files=extra_files,
)
Run Code Online (Sandbox Code Playgroud)
因此,下一个港口呼叫外是werkzeug.serving有run_simple。
从这里开始,您将对模块感到震惊:
make_servermake_server 发射 ThreadedWSGIServer ThreadingMixIn我们发现它只是ThreadingMixIn = socketserver.ThreadingMixIn所以现在,我们知道我们需要去socketserver. 我们可以从源代码中看到以下内容:
class ThreadingMixIn:
"""Mix-in class to handle each request in a new thread."""
...
def process_request(self, request, client_address):
"""Start a new thread to process the request."""
t = threading.Thread(target = self.process_request_thread,
args = (request, client_address))
t.daemon = self.daemon_threads
if not t.daemon and self.block_on_close:
if self._threads is None:
self._threads = []
self._threads.append(t)
t.start()
Run Code Online (Sandbox Code Playgroud)
因此,答案是它在每个请求上启动一个新线程。如果不出意外,这是跟踪代码路径的一个有趣的练习。