我正在尝试创建一个python Flask REST Web API。由于 Flask 开发服务器不适合生产,我尝试使用 cherry 应用服务器。
以下是我试图通过樱桃公开的 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)
以下是我创建的樱桃脚本
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 应该是类似以下内容的 http://127.0.0.1:8080/testapp/
但它抛出 404 与消息
"在服务器上找不到请求的 URL。 如果您手动输入了 URL,请检查您的拼写,然后重试。
我做错了什么?
api.add_resource(Main, "/testapp/")
在您的文件中,如果文件包含在您的 run.py中作为条件,则不会执行stack.py
if __name__ == '__main__':
...
不为真(在stack.py的上下文中(。
将调用api.add_resource移动到if-main-条件之外的位置(因此始终执行(应该可以解决问题。