使用 `gunicorn -c ` 命令启动 flask 应用程序时发生 ImportError

ImportError occurs when launching flask application using `gunicorn -c ` command

我使用 gunicorn 来处理 Flask 应用程序。这是我的项目结构。

flask-application
|-- non_web/
|   |--...
|
|-- web/
    |--app/
    |  |--api/
    |  |  |--...
    |  |--...
    |  |--__init__.py  # Here's def create_app()
    |
    |--config.py  # Here's config of flask application
    |--config_gunicorn.py  # Here's config of gunicorn
    |--run.py

当我执行命令行[XXX@XXXX flask-application]# gunicorn -c web/config_gunicorn.py web.run:app时,出现了一个错误ImportError: cannot import name 'XXX' from 'web.run' (/root/flask-application/web/run.py)

这里是run.py

```python
from web.app import create_app
app, whitelist = create_app(conf_type='default')

if __name__ == '__main__':
    app.run(host=app.config['HOST'], port=app.config['PORT'])
```

这里是__init__.py

```python
from flask import Flask
import redis

from ..config import config

def create_app(conf_type):
    app = Flask(__name__)
    app.config.from_object(obj=config[conf_type])
    config[conf_type].init_app(app=app)

    from .api import api as api_blueprint
    app.register_blueprint(blueprint=api_blueprint,
                           url_prefix='/api')
   
    whitelist = redis.StrictRedis(host=config[conf_type].REDIS_HOST,
                                  port=config[conf_type].REDIS_PORT,
                                  db=config[conf_type].REDIS_DB_WHITELIST,
                                  decode_responses=True)
    
    return app, whitelist
```

并且 config_gunicorn.py 如下:github.com/benoitc/gunicorn/blob/master/examples/example_config.py

在 windows 上没有 gunicorn 的情况下启动 run.py 时运行良好。有什么帮助吗?谢谢。

我的答案来了。原来与def create_app()返回的whitelist对象有关。通过创建连接池,我在使用 gunicorn 时解决了这个问题。这个post对我帮助很大