gunicorn flask服务器为现有端点返回404

时间:2020-09-05 22:05:38

标签: flask gunicorn

我正在重构我的工作烧瓶服务器应用程序(一个机器人),以使用gunicorn来利用其多工作人员模型以及WSGI的其他好处。我能够启动侦听默认(5000)端口的gunicorn服务器。以某种方式为/端点执行GET时,它返回404。并且/端点存在并返回'Hello'

在客户端看到错误

curl http://localhost:5000/
404
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again

文件组织

├── wsgi.py
├── bot.py

使用gunicorn启动服务器

(venv) % gunicorn --bind 0.0.0.0:5000 bot:app 
[2020-09-05 14:52:49 -0700] [45263] [INFO] Starting gunicorn 20.0.4
[2020-09-05 14:52:49 -0700] [45263] [INFO] Listening at: http://0.0.0.0:5000 (45263)
[2020-09-05 14:52:49 -0700] [45263] [INFO] Using worker: sync
[2020-09-05 14:52:49 -0700] [45266] [INFO] Booting worker with pid: 45266

wsgi.py

from bot import launch_bot

if __name__ == "__main__":
    launch_ria_bot()

bot.py

import logging
import os

from flask import Flask

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)

app = Flask(__name__)

def launch_ria_bot():

    @app.before_first_request
    def init_bot():
        log.info(os.getcwd())
        

    @app.route('/')
    def bot_home():
        return 'Hello!'

    @app.route('/bot/query', methods=["GET"])
    def query():
        # process_query()
        return response, 200

    app.run()

我在这里可能做错了什么?直视我。 附言我在StackOverflow上看到过一些帖子,说使用名称app表示文件或模块可能会发生冲突。因此,我完全避免使用该名称作为文件/模块。

1 个答案:

答案 0 :(得分:0)

该代码有一个问题,隐藏了第二个问题。

首先,由于将“ gunicorn”指向bot:applaunch_ria_bot()永远不会运行,因此不会添加任何路线。 wsgi.py永远不会卷入其中,但是如果这样做,您将遇到第二个问题:uwsgi提供了与app.run()等效的东西。

最简单的前进方式是内联launch_ria_bot(),离开

...
app = Flask(__name__)

@app.before_first_request
def init_bot():
   ...

@app.route('/')
def bot_home():
   ...

@app.route('/bot/query', methods=["GET"])
def query():
   ...

,然后删除app.run(),因为uwsgi将为您完成此操作,或者将其重写为

if __name__ == '__main__':
    app.run()

以便python bot.py将在开发服务器下启动应用程序。