python - Flask 蓝图与 gevent 在应用程序上下文之外工作

标签 python flask gevent flask-mail

我正在尝试通过 flask-mail 使用 gevent 在 Flask 中异步发送电子邮件。我正在“在应用程序上下文之外工作”。我知道 app.app_context() 但我无法让它与我的设置一起工作。

我的应用程序是使用这样的应用程序工厂创建的:

我的项目/run_dev.py

from gevent.wsgi import WSGIServer
from my_project.app import create_app
from my_project.config import DevConfig

app = create_app(DevConfig)
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()

我的项目/我的项目/app.py

def create_app(config=None, app_name=None, blueprints=None):
    app = Flask(app_name)
    configure_app(app, config)
    <other stuff>
    return app

以及我用来发送电子邮件的代码:

我的项目/我的项目/我的模块/views.py

@mymodule.route('/some/path/')
def do_something():
    do_stuff(something)

我的项目/我的项目/我的模块/utils.py

def do_stuff(something):
    send_email(msg)

@async
def send_async_email(msg):
    mail.send(msg)

def send_mail(request_id, recipients, email_type, env=None, pool=None):
    msg = Message(
        sender=sender,
        recipients=recipients,
        subject=subject,
        body=body)
    send_async_email(msg)

我的项目/我的项目/decorators.py

def async(f):
    def wrapper(*args, **kwargs):
        t = Greenlet.spawn(f, *args, **kwargs)
        gevent.joinall([t])
    return wrapper

我尝试添加:

from myproject.app import create_app
app = create_app()
with app.app_context():
    mail.send(msg)

到 send_async_email() 但后来我得到了

ImportError: cannot import name create_app

最佳答案

出于历史目的:将 from myproject.app import create_app 放在 send_async_email 中,而不是与其余导入一起放在顶部解决了 ImportError,因为它导致循环依赖。

关于python - Flask 蓝图与 gevent 在应用程序上下文之外工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21998039/

相关文章:

python - multiprocessing.Queue 是否与 gevent 一起工作?

python - 如何使用 Gevent 为 python Bottle 实现 TLS/SSL

python - 如何使用Python在hotmail中发送邮件?

python - 使用 gzip 和 pickle 时出现 UnicodeDecodeError

python - Flask-SQLAlchemy 超时错误

python - Flask 和 mimerender 异常处理

javascript - 使用 Flask 解决跨域资源共享

用于流式传输请求正文内容的 Python 服务器

python - Altair alt.condition 中的动态名称

python - 我可以同时使用 Flask-SQLAlchemy 和 SQLAlchemy 吗?