简体   繁体   English

关于 Heroku 导入错误的 Flask 和 Gunicorn

[英]Flask and Gunicorn on Heroku import error

I have a small Flask app which uses MongoEngine.我有一个使用 MongoEngine 的小型 Flask 应用程序。

my project structure:我的项目结构:

/myproject
  -application.py
  -config.py
  /my_app
    -models.py
    -views.py

my application.py:我的应用程序.py:

#!/usr/bin/env python
from flask.ext.mongoengine import MongoEngine
from config import app
import os
app.debug = True

# get config settings
if __name__ == '__main__':
    app.config.from_object('config')
else:
    app.config.from_object('heroku_config')

# wrap app in mongengine
db = MongoEngine(app)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

my models.py:我的模型.py:

from application import db
from flask import url_for

# declare model classes
...

I am deploying on heroku.我正在 Heroku 上部署。 If my Procfile reads:如果我的 Procfile 显示:

 web: python application.py

It works fine.它工作正常。 When I try to switch to Gunicorn:当我尝试切换到 Gunicorn 时:

 web: gunicorn application:app  

When I start gunicorn it complains by way of an import error:当我启动 gunicorn 时,它通过导入错误的方式抱怨:

ImportError: cannot import name db

Why is this an issue now?为什么现在会出现这个问题? I'm guessing it's a path problem but I can't see why so.我猜这是一个路径问题,但我不明白为什么会这样。

I assume you're registering blueprints or something like that in application.py, which in turn imports the model, right?我假设您正在 application.py 中注册蓝图或类似的东西,然后导入模型,对吗?
You didn't supply the view file or how you're using the view file and if my guess isn't correct my answer below won't be either.您没有提供视图文件或您如何使用视图文件,如果我的猜测不正确,我下面的答案也不会正确。

If my guess is correct it is probably because of a circular import.如果我的猜测是正确的,那可能是因为循环导入。 You could create a db.py file that contains these lines (move from application.py):您可以创建一个包含这些行的 db.py 文件(从 application.py 移动):

from flask.ext.mongoengine import MongoEngine
db = MongoEngine(app)

and then import that file into your models ( from db import db ).然后将该文件导入您的模型( from db import db )。
That means the flow would look something like this: db -> model -> view -> app instead of app (db) -> model -> view -> app .这意味着流程看起来像这样: db -> model -> view -> app而不是app (db) -> model -> view -> app

Circular imports creates all kinds of annoying problems, try to avoid them whenever possible.循环导入会产生各种烦人的问题,请尽可能避免它们。

If you are using an init style flask module then the following works (derived from the pallet flask tutorial v Flask 2.0.1).如果您使用的是init风格的烧瓶模块,那么以下工作(源自托盘烧瓶教程 v Flask 2.0.1)。 https://www.palletsprojects.com/p/flask/ https://www.palletsprojects.com/p/flask/

web: env FLASK_APP=flaskr gunicorn -b '0.0.0.0':${PORT} 'flaskr:create_app()'

Where create_app is the "app" called from flaskr/ init .py其中 create_app 是从 flaskr/ init .py 调用的“应用程序”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM