【问题标题】:Python Flask REST API on Windows CherrypyWindows Cherrypy 上的 Python Flask REST API
【发布时间】:2019-02-23 14:02:56
【问题描述】:

我正在尝试创建一个 python Flask REST Web API。由于Flask开发服务器不适合生产,我尝试使用cherrypy应用服务器。

以下是我尝试通过cherrypy公开的Flask应用

from flask import Flask,request
from flask_restful import Api,Resource, reqparse

app= Flask(__name__)
api = Api(app)

class Main (Resource):
    def get(self):
        return "Hello Flask"

if __name__ == '__main__':
    api.add_resource(Main, "/testapp/")
    app.run(debug=True)

以下是我创建的cherrypy脚本

try:
from cheroot.wsgi import Server as WSGIServer, PathInfoDispatcher
except ImportError:
    from cherrypy.wsgiserver import CherryPyWSGIServer as WSGIServer, WSGIPathInfoDispatcher as PathInfoDispatcher

from stack import app

d = PathInfoDispatcher({'/': app})
server = WSGIServer(('127.0.0.1', 8080), d)

if __name__ == '__main__':
   try:
      server.start()
      print("started")
   except KeyboardInterrupt:
      server.stop()

我已将此脚本保存为我的项目目录中的“run.py”。当我运行它时,它没有显示任何错误,这让我觉得这是正确的。

但不幸的是,我无法使用 url 访问它

理论上,这个 API 的 url 应该类似于 follow http://127.0.0.1:8080/testapp/

但它会抛出 404 消息

“在服务器上找不到请求的 URL。如果您手动输入了 URL,请检查您的拼写并重试。”

我做错了什么?

【问题讨论】:

    标签: python flask cherrypy


    【解决方案1】:

    api.add_resource(Main, "/testapp/")
    

    如果文件包含在您的 run.py 中,则不会在您的文件中执行 stack.py 作为条件

    if __name__ == '__main__':
    ...
    

    不正确(在 stack.py 的上下文中)。

    将对 api.add_resource(...) 的调用移动到 if-main-condition 之外的位置(因此它总是被执行)应该可以解决问题.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-17
      • 2020-03-11
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多