Object Oriented Python with Flask Server?

后端 未结 5 1896
悲哀的现实
悲哀的现实 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:42

    You can create an instance of MyServer just outside the scope of your endpoints and access its attributes. This worked for me:

    class MyServer:
        def __init__(self):
            self.globalData = "hello"
    
    from flask import Flask
    app = Flask(__name__)
    
    my_server = MyServer()
    
    @app.route("/getSomeData")
    def getSomeData():
        return my_server.globalData
    
    if __name__ == "__main__":
        app.run(host="0.0.0.0")
    

提交回复
热议问题