Gunicorn:无法在模块中找到属性“app”

Vai*_*han 3 python gunicorn sanic

嗨,我正在尝试跑步,

gunicorn --bind localhost:8000 --worker-class sanic_gunicorn.Worker module:app
Run Code Online (Sandbox Code Playgroud)

我有以下文件

# ls
build                            
setup.py
dist                             
module         
module.egg-info 
venv

#cd module

#ls
__init__.py
__pycache__
__main__.py
app.py
Run Code Online (Sandbox Code Playgroud)

内容__main__.py如下

from module.app import create_app_instance


if __name__ == '__main__':
    app = create_app_instance()
    app.run()
Run Code Online (Sandbox Code Playgroud)

app.py 的内容是

#some imports

def create_app_instance():
    app = Sanic(name = "app_name")
    .....
    return app

Run Code Online (Sandbox Code Playgroud)

我正在使用 Sanic Web 框架,当我运行它的开发服务器时,python -m module它工作正常

python3 -m module
[2021-06-16 22:31:36 -0700] [80176] [INFO] Goin' Fast @ http://127.0.0.1:8000
[2021-06-16 22:31:36 -0700] [80176] [INFO] Starting worker [80176]
Run Code Online (Sandbox Code Playgroud)

有人可以让我知道我做错了什么吗?

Edo*_*kse 6

app简单的答案是模块内部没有暴露。您有该create_app_instance()方法,但未调用该方法。

我建议您按如下方式重构代码。文件结构为:

./wsgi.py
./module/__init__.py
Run Code Online (Sandbox Code Playgroud)

这些文件的内容如下:

.\wsgi.py

from module import create_app_instance


app = create_app_instance()


if __name__ == '__main__':
    app.run()
Run Code Online (Sandbox Code Playgroud)

.\模块\__init__.py

# this is the contents of your current app.py
#some imports

def create_app_instance():
    app = Sanic(name = "app_name")
    .....
    return app
Run Code Online (Sandbox Code Playgroud)

然后启动服务器的gunicorn行将是(请注意下面来自The Brewmaster的评论):

gunicorn --bind localhost:8000 --worker-class sanic_gunicorn.Worker wsgi:app
Run Code Online (Sandbox Code Playgroud)

它的作用是调用app内部公开的实例wsgi.py。不需要__main__.py,并且您的代码app.py已移至__init__.py

我强烈建议您阅读Application Factory PatternFlask 的文档/教程。原理本身与 Sanic 相同,但还有更多文章描述 Flask 的原理...