我正在尝试通过烧瓶邮件通过gevent在Flask中异步发送电子邮件.我正在“在应用程序上下文之外工作”.我知道app.app_context(),但无法使其与我的设置配合使用.
我的应用程序是使用这样的应用程序工厂创建的:
myproject / 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()
myproject / myproject / app.py
def create_app(config=None, app_name=None, blueprints=None):
app = Flask(app_name)
configure_app(app, config)
<other stuff>
return app
以及我用来发送电子邮件的代码:
myproject / myproject / mymodule / views.py
@mymodule.route('/some/path/')
def do_something():
do_stuff(something)
myproject / myproject / mymodule / 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)
myproject / myproject / 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
解决方法:
出于历史目的:将myproject.app中的import create_app从myproject.app放入send_async_email内,而不是在其余导入的顶部解决了ImportError,因为它引起了循环依赖.