简体   繁体   中英

Python Flask REST API on Windows Cherrypy

I'm trying to create a python Flask REST web API. Since Flask development server is not suitable for production, I tried to use cherrypy application server.

Following is the Flask app I tried to expose via cherrypy

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)

Following is the cherrypy script I have created

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()

I have saved this script as "run.py" in my project directory. When I run this it doesn't show any error, which made me to thin this is correct.

But unfortunately I cant access this using the url

Theoretically, url for this API should be some thing like follow http://127.0.0.1:8080/testapp/

But it throws 404 with the message

"The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."

What am I doing wrong ?

The

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

in your file stack.py is not executed if the file is included from your run.py as the condition

if __name__ == '__main__':
...

is not true (in the context of stack.py ).

Moving the call to api.add_resource(...) to a position outside the if-main-condition (so it is always executed) should solve the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM