【问题标题】:Running a long polling flask application asynchronously using gunicorn使用 gunicorn 异步运行长轮询烧瓶应用程序
【发布时间】:2021-01-18 01:52:54
【问题描述】:

我正在尝试运行一个用于轮询 AWS SQS 队列的烧瓶应用程序,我要求该应用程序持续轮询并异步响应客户端请求,但我发现该应用程序在轮询时被阻塞。

我已阅读其他有关使用 gevent 的帖子,但我似乎无法使其正常工作。

用于运行应用程序的命令,

gunicorn src.app:app \
        --bind 0.0.0.0:8081 \
        --timeout 127 \
        -k gevent --worker-connections=2000

应用程序代码,

from flask import Flask
from werkzeug.middleware.proxy_fix import ProxyFix
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

from src import security
from src.config import config

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = config.pg_url
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
migrate = Migrate(app, db)

app.wsgi_app = ProxyFix(app.wsgi_app)


from src.app import routes
from src.app.services.sqs.queue import SQSQueue
from src.app.services.sqs.message_processor import MessageProcessor


if config.group == 'JobServer':
    SQSQueue.poll(MessageProcessor)

轮询代码,

def poll(action):
        while True:
            try:
                message = self.get_message()
                if message is None:
                    time.sleep(5)
                else:
                    # do something
            except Exception:
                pass

【问题讨论】:

    标签: python flask gunicorn


    【解决方案1】:

    使用 gevent worker 是不够的。您还需要在代码中使用它。对于您的代码,修补 IO 库可能就足够了。

    为了简单起见,我通常会在导入时尽早使用monkey.patch_all()

    例如,在您的应用程序导入中,我会将其放在顶部,如下所示

    # Use gevent to patch IO modules as soon as possible.
    from gevent import monkey; monkey.patch_all()
    from flask import Flask
    from werkzeug.middleware.proxy_fix import ProxyFix
    from flask_sqlalchemy import SQLAlchemy
    from flask_migrate import Migrate
    
    from src import security
    from src.config import config
    

    http://www.gevent.org/intro.html

    【讨论】:

      猜你喜欢
      • 2012-11-19
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      • 2020-04-16
      • 1970-01-01
      • 2016-07-12
      相关资源
      最近更新 更多