Gunicorn 20 未能在“索引”中找到应用程序对象“app.server”

Abd*_*rim 5 python gunicorn plotly-dash

我正在使用 Gunicorn 部署我的 Dash 应用程序。升级到 Gunicorn 20.0.0 后,找不到我的应用程序。

gunicorn --bind=0.0.0.0 --timeout 600 index:app.server
Run Code Online (Sandbox Code Playgroud)
Failed to find application object 'app.server' in 'index'
[INFO] Shutting down: Master
[INFO] Reason: App failed to load.
Run Code Online (Sandbox Code Playgroud)

Gunicorn 的问题跟踪器上的这个问题似乎与错误有关,但我不知道我应该怎么做来修复它。如何让 Gunicorn 20 找到我的应用程序?

index.py

import os
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from pages import overview
from webapp import app

app.index_string = open(os.path.join("html", "index.html")).read()
app.layout = html.Div([
    dcc.Location(id="url", refresh=False),
    html.Div(id="page-content")
])

@app.callback(Output("page-content", "children"), [Input("url", "pathname")])
def display_page(pathname):
    if pathname == "/a-service/overview":
        return overview.layout
    else:
        return overview.layout

if __name__ == "__main__":
    app.run_server(debug=True, port=8051)
Run Code Online (Sandbox Code Playgroud)

webapp.py

import dash

description = "a description"
title = "a title"
creator = "@altf1be"
app = dash.Dash(
    __name__,
    meta_tags=[
        {"name": "viewport", "content": "width=device-width, initial-scale=1"},
        {"name": "description", "content": description},
        {"name": "twitter:description", "content": description},
        {"property": "og:title", "content": description},
        {"name": "twitter:creator", "content": creator}
    ]
)
server = app.server
app.config.suppress_callback_exceptions = True
Run Code Online (Sandbox Code Playgroud)

dav*_*ism 8

Gunicorn 20 更改了解析和加载应用程序参数的方式。它曾经使用eval, 跟随属性访问。现在它只对给定模块中的单个名称进行简单的查找。Gunicorn 理解 Python 语法(如属性访问)的能力没有记录在案或有意为之。

Dash 有关部署的文档并未使用您正在使用的语法。他们说要执行以下操作,这适用于任何版本的 Gunicorn:

webapp.py

server = app.server
Run Code Online (Sandbox Code Playgroud)
$ gunicorn webapp:server
Run Code Online (Sandbox Code Playgroud)

您已经serverwebapp模块中添加了别名,但是您的代码布局有点偏离并且让您感到困惑。您忽略了您所做的设置,而是webapp将其index用作切入点。您将所有内容都放在单独的顶级模块中,而不是放在一个包中。

如果您想从索引视图中拆分应用程序设置,您应该遵循定义应用程序的标准 Flask 模式,然后在此之后导入视图,所有这些都在一个包中。

project/
  myapp/
    __init__.py
    webapp.py
    index.py
Run Code Online (Sandbox Code Playgroud)

webapp.py

app = dash.Dash(...)
server = app.server

# index imports app, so import it after app is defined to avoid a circular import
from myapp import index
Run Code Online (Sandbox Code Playgroud)
$ gunicorn myapp.webapp:server
Run Code Online (Sandbox Code Playgroud)