Forums

Global variables in Flask

This is the code I deployed on pythonanywhere

from flask import Flask, jsonify
import estimateR

app = Flask(__name__)

# to make flask point to our current app
app.app_context().push()

reproductive_nos = estimateR.get_reproductive_nos()

dates = estimateR.get_dates()

response = list()

for i in range(len(dates)):
    d = dict()
    d["date"] = dates[i]
    d["R"] = reproductive_nos[i]
    response.append(d)

response.reverse()

json_response = jsonify({'values': response})


@app.route('/', methods=['GET'])
def return_data():
    return json_response


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

END

Now, reproductive_nos and dates are gloabl variables imported from another file. These variables change as they're computed by making some API calls in which data changes. My question is will this change be reflected on the global variables? Or will they remain static? Thanks

[edit by admin: formatting]

I think you should probably try to not use global variables- perhaps try storing it into a database instead?

I'm actually fetching them from an API directly. I have now reloaded the module before any request is made. Guess that should solve the problem. I'll know for sure only tomorrow because the API gets updated on a daily basis.

The thing to keep an eye out for with global variables is that they are per-process, not per-website. With a free account you have only one process handling all requests to your site, so you may be OK, but if you ever need to upgrade to get more processes to handle more traffic, then confusing things may happen because each process will have its own copies.

Additionally, looking at the code that you posted earlier, your globals are explicitly initialised when the website is started up. Those will never change unless the website is reloaded, as that is when the code that is outside your views is run. This may happen without you needing to explicitly reload the site from our web interface, if your site is moved from one server to another as part of our load-balancing process, but the timing will not be predictable, as it depends on how busy the other sites we host are.