Gunicron 无法在指定端口启动

cha*_*aos 2 python flask gunicorn

我试图让我的 Flask 程序监听端口 5000,以下是主要部分app/app.py

app = Flask(__name__)

@app.route('/')
def index():
    app.logger.info("Receiving a request")
    if (request.method == "POST"):
        query = request.args.get("query")
        file = request.files['file']
        app.logger.info(query)
        filePath  = '/tmp/tmpDoc'
        # write something to file
        searchResult = bootLoader.run(filePath, query)
        ans = searchResult['answers']
        return jsonify(ans)
    return "hihi"

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

和我的wsgi.py

from app.app import app

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

我使用gunicorn by 运行程序gunicorn wsgi:app,但调试功能和指定端口都不起作用。这是日志:

[2021-02-09 16:50:58 +0800] [62555] [INFO] Starting gunicorn 20.0.4
[2021-02-09 16:50:58 +0800] [62555] [INFO] Listening at: http://127.0.0.1:8000 (62555)
[2021-02-09 16:50:58 +0800] [62555] [INFO] Using worker: sync
[2021-02-09 16:50:58 +0800] [62558] [INFO] Booting worker with pid: 62558

Run Code Online (Sandbox Code Playgroud)

小智 6

那是因为if __name__ == "__main__":永远不会满足。

您可以运行python app/app.py将使用内置 WSGI 开发服务器的内容。运行后也会发生同样的情况python wsgi.py

Gunicorn 命令未触发if __name__ == "__main__":。您可以将其视为gunicorn 会导入app对象并自行运行它。这就是使用不同端口号的原因。请注意,如果删除if __name__ == ...这两个文件,guncorn 仍然能够在端口 8000 上运行服务器。

相反,您应该在gunicorn 命令中使用--bind传递主机和端口号。

gunicorn wsgi:app -b :5000
Run Code Online (Sandbox Code Playgroud)