使用Gunicorn运行Flask引发TypeError:index()获取0个位置参数,但给出了2个

nul*_*ter 5 python flask gunicorn

我正在尝试用Gunicorn运行Flask应用程序.当我跑gunicorn app:index,我得到错误TypeError: index() takes 0 positional arguments but 2 were given.我见过的所有例子都没有显示index需要两个参数.这个错误是什么意思?如何使用Gunicorn运行Flask?

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return 'Hello, World!'
Run Code Online (Sandbox Code Playgroud)
gunicorn app:index
Run Code Online (Sandbox Code Playgroud)
    respiter = self.wsgi(environ, resp.start_response)
TypeError: index() takes 0 positional arguments but 2 were given
Run Code Online (Sandbox Code Playgroud)

我改变index了两个参数,但得到了一个不同的错误.

@app.route("/")
def index(arg1, arg2):
    return 'Hello, World!'
Run Code Online (Sandbox Code Playgroud)
  /python3.4/site-packages/flask/templating.py, line 132, in render_template
    ctx.app.update_template_context(context)
AttributeError: 'NoneType' object has no attribute 'app'
Run Code Online (Sandbox Code Playgroud)

vrs*_*vrs 7

您必须将Flask实例传递给gunicorn,而不是像您一样传递函数名称index.因此,如果您的应用保存为app.py,则必须gunicorn按以下方式运行:

$ gunicorn --bind 127.0.0.1:8000 app:app
Run Code Online (Sandbox Code Playgroud)

  • 答案可能是正确的 - 或者至少有助于找到问题的原因 - 但在我看来,示例代码很容易让人困惑;澄清一下:OP使用 `gunicorn app:index` 调用 Gunicorn,即 `<模块名称>:<函数名称>`;Gunicorn 需要 `<模块名称>:<Flask 实例>`;`index()` 返回 Flask 实例,因此应该在函数名称后使用括号调用 Gunicorn:`gunicorn app:index()` (3认同)
  • 我的文件名不是“ app.py”,但我仍然需要调用“ my_file_name:app”。似乎取决于此处定义的变量名`app = Flask(__ name __)`,在这种情况下为`app`。 (2认同)