我只是了解烧瓶和要求。当我向服务器发布请求时,我想获取工作线程的数量。我想衡量工作线程花费的时间。所以这是我的服务器和我的客户代码:
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()
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()
我怎么知道工作线程的数量?我只是在服务器上添加threaded = True
。我一直在寻找答案,但没有一个回答我的问题。预先感谢!
答案 0 :(得分:1)
首先,通常的免责声明:这几乎无关紧要,因为您可以在实际移至deployment server时指定此内容。
但是,我很好奇自己,所以我决定追溯到此。
起点在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,
)
因此,下一个呼叫端口是werkzeug.serving
with run_simple
。
从这里开始,您将对模块感到吃惊:
make_server
make_server
启动ThreadedWSGIServer
ThreadingMixIn
,而我们发现ThreadingMixIn = socketserver.ThreadingMixIn
现在,我们知道我们需要转到socketserver
。我们可以从the source code看到以下内容:
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()
因此,答案是它会在每个请求上启动一个新线程。如果没有别的,这是跟踪代码路径的有趣练习。