Skip to content
Advertisement

Object Oriented Python with Flask Server?

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 where I’m stuck:

from flask import Flask
app = Flask(__name__)

class MyServer:
  def __init__(self):
    globalData = json.load(filename)

  @app.route('/getSomeData')
  def getSomeData():
    return random.choice(globalData) #select some random data to return

if __name__ == "__main__":
  app.run(host='0.0.0.0')

When I run getSomeData() outside of Flask, it works fine. But, when I run this with Flask, I get 500 internal server error. There’s no magic here, and Flask has no idea that it’s supposed to initialize a MyServer object. How can I feed an instance of MyServer to the app.run() command?

I could admit defeat and put globalData into a database instead. But, is there an other way?

Advertisement

Answer

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")
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement