Python Flask Pass Global Variable To Blueprint

Advertisements

I am looking into implementing Blueprints but ran into somewhat of a snag.

My app has 3 distinct modules

  • Client
  • Product
  • Order

On the app startup I load 3 global dictionaries one for each module.
The order module uses both the client and the product dictionary, not for making changes but for reference.

How would I go about getting these global dictionaries into each module, seems rather pointless declaring them and then loading them in each Blueprint

>Solution :

If you have global dictionaries that need to be accessed by multiple modules (Client, Product, and Order), you can consider using a shared context or a global object to hold these dictionaries. This way, you don’t need to declare and load the dictionaries in each Blueprint separately.

Here’s a possible approach:

Create a separate module or file, let’s call it globals.py, to define and initialize the global dictionaries.

 # globals.py

 client_dict = {}
 product_dict = {}
 order_dict = {}

In your main application file, import the globals module and load the dictionaries.

# main.py

from flask import Flask
from globals import client_dict, product_dict, order_dict

app = Flask(__name__)

client_dict = load_client_data()
product_dict = load_product_data()
order_dict = load_order_data()

# Register your Blueprints or modules here

if __name__ == '__main__':
   app.run()

In each module or Blueprint that needs access to these dictionaries, import them from the globals module.

# client.py

from flask import Blueprint
from globals import client_dict

client_bp = Blueprint('client', __name__)

…..

# product.py

from flask import Blueprint
from globals import product_dict

product_bp = Blueprint('product', __name__)

….

# order.py

from flask import Blueprint
from globals import client_dict, product_dict, order_dict

order_bp = Blueprint('order', __name__)

By importing the dictionaries from the globals module in each module or Blueprint, you can access and use them directly without the need to declare or load them separately. Any changes made to the dictionaries in one module will be reflected across other modules since they are referencing the same global objects.

Leave a ReplyCancel reply