1

I have a Flask app with multiple routes. I have defined an Utility class with few methods to handle the common functionalities, for eg. getting some properties etc. Now I want to create and instance of the Utility class in a common place to be used by functions in each route. How do I achieve this ?

from flask import Flask, request, jsonify
import mysql.connector as mariadb

app = Flask(__name__)

@app.route('/aaa/bbb/ccc',methods=['POST'])
def func1():
  pass
@app.route('/xxx/yyy/zzz',methods=['POST'])
def func2():
  pass
@app.route('/abc/dfg/ijk',methods=['POST'])
def func3():
  pass

class Utility:
    def get_properties():
       pass
    def get_database_conn():
       pass

if __name__ == "__main__":
    app.run(host='127.0.0.1', port=5000, debug=True)

Now, I want to do something like -

util_obj = Utility()

in the beginning of the app, so that from any of my routes I can call the utility methods without having to create the object every time.

What is the best way to achieve this ?

1 Answer 1

1

What you're describing seems to follow the same structure as most extensions to Flask, like Flask-SQLAlchemy or Flask-Caching, namely to have a globally configured instance that you import or call upon when necessary.

In a large scale application, you would create these instances in a file like extensions.py, away from where you create app to avoid circular imports, but in the case of a single file, you don't have to worry about that. Instead, I would simply move the class definition of Utility to just underneath where you define app, and create util_obj right below the class definition.

from flask import Flask, request, jsonify
import mysql.connector as mariadb

app = Flask(__name__)

class Utility:
    def get_properties():
       # you can access app here!
       pass
    def get_database_conn():
       pass

util_obj = Utility()

@app.route('/aaa/bbb/ccc',methods=['POST'])
def func1():
  # you can access util_obj here!
  pass
@app.route('/xxx/yyy/zzz',methods=['POST'])
def func2():
  pass
@app.route('/abc/dfg/ijk',methods=['POST'])
def func3():
  pass

if __name__ == "__main__":
    app.run(host='127.0.0.1', port=5000, debug=True)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.