非同期リクエスト処理をチェックするために、トルネードサーバでフラスコアプリケーションを実行しようとしています。私は2つのファイル 'flask_req.py'と 'tornado_ex.py'を持っています。私の両方のファイルは、以下のようになります。フラスコアプリケーションでトルネードWebサーバを実行し、非同期リクエスト処理を確認する
flask_req.py
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/hello',methods=['GET'])
def hello():
print "hello 1"
time.sleep(20)
x= 2*2
print(x)
return "hello"
@app.route('/bye',methods=['GET'])
def bye():
print "bye 1"
time.sleep(5)
y = 4*4
print(y)
return "bye"
tornado_ex.py
from __future__ import print_function
from tornado.wsgi import WSGIContainer
from tornado.web import Application, FallbackHandler
from tornado.websocket import WebSocketHandler
from tornado.ioloop import IOLoop
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
import time
from flask_req import app
class WebSocket(WebSocketHandler):
def open(self):
print("Socket opened.")
def on_message(self, message):
self.write_message("Received: " + message)
print("Received message: " + message)
def on_close(self):
print("Socket closed.")
@gen.coroutine
def fetch_and_handle():
"""Fetches the urls and handles/processes the response"""
urls = [
'http://127.0.0.1:8080/hello',
'http://127.0.0.1:8080/bye'
]
http_client = AsyncHTTPClient()
waiter = gen.WaitIterator(*[http_client.fetch(url) for url in urls])
while not waiter.done():
try:
response = yield waiter.next()
except Exception as e:
print(e)
continue
print(response.body)
if __name__ == "__main__":
container = WSGIContainer(app)
server = Application([
(r'/websocket/', WebSocket),
(r'.*', FallbackHandler, dict(fallback=container))
])
server.listen(8080)
fetch_and_handle()
IOLoop.instance().start()
私は竜巻サーバを使用して要求を処理する非同期動作を確認したいです。今すぐ実行しているときに、両方のURLが渡されると、20秒+ 5秒= 25秒待機しています。 1つのリクエストに時間がかかる場合は、それ以上のコードを処理する必要がある待機時間の合計が25秒ではなく20秒になるように、他のリクエストを処理する必要があります。どのように私はここでこの行動を達成することができます。 「hello1」を印刷した後、それが25秒を待って、その後、さらに処理を行うと、それが再び待っている「bye1」印刷後だ
$ python tornado_ex.py
hello 1
4
bye 1
16
hello
bye
:私のように応答を取得していて今、私は上記のコードを実行していたときに5秒。私が欲しいのは、 'hello1'を印刷した後です。それが非常に時間がかかる場合は、 '/ bye'を処理する必要があります。
Flaskは非同期ではないため、複数の要求に対応するには複数のスレッドが必要です。しかし、Tornadoはシングルスレッドです。あなたのFlaskアプリをTornadoで実行すると、パフォーマンスが非常に悪くなります。これについてのドキュメントには[警告](http://www.tornadoweb.org/en/stable/wsgi.html#tornado.wsgi.WSGIContainer)さえあります。 – xyres