Object Oriented Python with Flask Server?

后端 未结 5 1887
悲哀的现实
悲哀的现实 2021-02-04 02:18

I\'m using Flask to expose some data-crunching code as a web service. I\'d like to have some class variables that my Flask functions can access.

Let me walk you through

5条回答
  •  隐瞒了意图╮
    2021-02-04 02:46

    I know this is a late reply, but I came across this question while facing a similar issue. I found flask-classful really good. You inherit your class from FlaskView and register the Flask app with your MyServer class

    http://flask-classful.teracy.org/#

    In this case, with flask-classful, your code would look like this:

    from flask import Flask
    from flask_classful import FlaskView, route
    
    app = Flask(__name__)
    
    class MyServer(FlaskView):
      def __init__(self):
        globalData = json.load(filename)
    
      @route('/getSomeData')
      def getSomeData():
        return random.choice(globalData) #select some random data to return
    
    
    MyServer.register(app, base_route="/")
    
    
    if __name__ == "__main__":
      app.run(host='0.0.0.0')
    

提交回复
热议问题