-1

I am looking for a ways to share global data across all views of the flask application

__init__.py

from flask import Flask
app = Flask(__name__)
app.gcp = googleCloudSessionObjectA()

aview.py

from flask import current_app as app

@app.route('/abc')
def foo():
    print(app.gcp)  # here it prints the string representation of A
    app.gcp = googleCloudSessionObjectB() # this one does not change the global app object
    return render_template('base.html')

I want to be able to change the value of app.gcp in a view after importing the current_app object. And I want this value to be available throughout the application.

What am I doing wrong?

caliph
  • 1,389
  • 3
  • 27
  • 52
  • 1
    Why not use session variables using os? – Swetank Poddar Apr 19 '20 at 13:05
  • Because in reality I dont want to store a string ("dog"), I want to store a python object for global use (to be exact its a session object for google cloud pltform). – caliph Apr 19 '20 at 13:10
  • If I want to make only string values available throughout the flask application I could use a datastore such as memcached. But I need to do it with a python object – caliph Apr 19 '20 at 13:12
  • Have you checked https://flask.palletsprojects.com/en/1.1.x/config/ ? – Hrishi Apr 19 '20 at 13:14
  • I am aware of flasks configuration. But whats the connection to my issue at hand? – caliph Apr 19 '20 at 13:15
  • It would be great if you could add that in the question. As there is a difference between storing primitive data types and complex python structures. – Swetank Poddar Apr 19 '20 at 13:17

1 Answers1

-3

please try use global app.bar as following example ->

x = 15
def change(): 

    # using a global keyword 
    global x 

    # increment value of a by 5 
    x = x + 5
    print("Value of x inside a function :", x) 
change() 
print("Value of x outside a function :", x) 
Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75
  • and how this will works in `production`? I mean using `gunicorn` or `uwsgi` with multiple `workers`? – Danila Ganchar Apr 19 '20 at 13:05
  • On addition to that, global variables should be ignored as much as possible. They can sometimes be really painful and dangerous if you don't exactly know what you are doing with it. – Swetank Poddar Apr 19 '20 at 13:10