使用flask应用程序运行tornado web服务器并检查异步请求处理[重复]

问题描述 投票:0回答:1

我试图在tornado服务器上运行flask应用程序来检查异步请求处理。我有两个文件'flask_req.py'和'tornado_ex.py'。我的两个文件如下所示:

flask_热情.朋友

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_恶心.朋友

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()

我想检查使用tornado服务器处理请求的异步行为。现在当我运行它时,当两个URL都通过时,它等待20秒+ 5秒= 25秒。我希望运行它,如果一个请求花费时间,那么它应该处理另一个请求,以便从上面的代码中它应该花费的总等待时间仅为20秒,而不是25秒。我怎么能在这里实现这种行为。现在,当我运行上面的代码时,我得到的响应是:

$ python tornado_ex.py 
hello 1
4
bye 1
16
hello
bye

打印'hello1'后,它等待25秒,然后进行进一步处理,打印'bye1'后再等待5秒。我想要的是在打印'hello1'之后,如果花了这么多时间就应该处理'/ bye'。

python flask tornado
1个回答
1
投票

使用WSGI容器意味着一次只处理一个请求,并且在第一个请求完成之前不会处理后续请求。

当您需要并发时,使用Tornado运行WSGI应用程序通常不是一个好主意。

使用多个进程或将项目转换为使用ASYNC TornadoWeb框架而不是WSGI。

© www.soinside.com 2019 - 2024. All rights reserved.