vandit_left_join
vandit_left_join

Reputation: 11

Why am I not able to use a global variable from Flask program to another python file?

I am trying to use a dictionary from file1 in another file2, but in file2 it prints empty dictionary. Can you please help me with the reason, thanks in advance.

Following is my file1:

from flask import Flask, render_template, request
global user_pincode
user_pincode={}
app = Flask(__name__)

@app.route('/', methods=["GET", "POST"])
def index():
       global user_pincode
       #user_pincode getting updated here

@app.route('/delete', methods=["GET", "POST"])
def delete():
       global user_pincode
       #user_pincode getting updated here

if __name__ == "__main__":
    app.run(debug=True)

Following is my file2:

import file1
print(file1.user_pincode)

Upvotes: 0

Views: 631

Answers (2)

Alex Yu
Alex Yu

Reputation: 3547

You did import file1

That's why file1.user_pincode is equal to {}

But you did not call any function that could change the value.

Take a look.

A. Let's modify function delete in file1

@app.route('/delete', methods=["GET", "POST"])
def delete():
    #    global user_pincode 
       user_pincode['key'] = 'delete'

B. Modify caller module main.py:

import file1
print(file1.user_pincode)
file1.delete()
print(file1.user_pincode)

C. Run it:

python main.py 
{}
{'key': 'delete'}

Everything as expected.

Note that global is not needed anywhere for dict.

Upvotes: 1

Udo G
Udo G

Reputation: 1

I assume this is an compile time/runtime issue.

The global variable is initialized as empty dictionary at compile time. Your file2 is evaluated at compile time so it prints an empty dict.

What is your use case anyway? If you'd like to have a value surviving a single request you will probably have to store it in some file or database.

Upvotes: 0

Related Questions