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?
If you start with flask then initially you don't need much oop, but when you will going to use sqlalchemy, or peewee orm, or flask wtform, or marshmellow serializer or flask classy view you will understand that without OOP it will be difficult to handle those.
To run the app outside of the VS Code debugger, use the following steps from a terminal: Set an environment variable for FLASK_APP . On Linux and macOS, use export set FLASK_APP=webapp ; on Windows use set FLASK_APP=webapp . Navigate into the hello_app folder, then launch the program using python -m flask run .
Although Flask has a built-in web server, as we all know, it's not suitable for production and needs to be put behind a real web server able to communicate with Flask through a WSGI protocol. A common choice for that is Gunicorn—a Python WSGI HTTP server.
Flask is a web framework, it's a Python module that lets you develop web applications easily. It's has a small and easy-to-extend core: it's a microframework that doesn't include an ORM (Object Relational Manager) or such features. It does have many cool features like url routing, template engine.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With