mardi 13 juillet 2021

Sharing Class Instances Across Flask Blueprints

Is my Flask design pattern problematic?

I'm concerned that my handling of objects throughout my Flask app is an anti-pattern that will cause issues down the line.

Context:

I have a medium-sized flask app with 4 data-handling classes used for databasing, API resources etc. These modules are in the form of class instances, which inherit some shared state from the parent app.

I read in another answer on S.O that you can share instances by simply adding them as attributes to app like such:

# app.py
from data_model import PostgresDatabaseHandler

app = Flask(...)
app.PostgresModel = PostgresDatabaseHandler(...)

I quite like this way of managing data-handlers, since I can access the database functionality in any blueprint as such without additional imports / boilerplate:

#home.py
from flask import current_app

@home_bp.route('/home', methods=['GET'])
def home():
    """
       Simple homepage with some products.
    """
    products = current_app.SQLPostgresModel.<<method>>()
    
    return render_template('home.jinja2', 
                           products=products)

Downsides to this approach

  1. There are no hints for which methods can be called on sub-instances

  2. There are no type hints for methods arguments

  3. Just because you can, doesn't mean you should. Something seems off about arbitrarily stitching class instances onto one another.

Is this pattern problematic?

What are some viable alternatives to this design?

Aucun commentaire:

Enregistrer un commentaire