How to use global variables in python

2

I'm trying to keep the value read in a webhook in the following webhook but the variable that takes the value does not keep it in the next webhook.

from flask import Flask
from flask import request
import os
from threading import Thread

app = Flask(__name__)

xml = ""

def send_email(xml):
    print xml
    return None

@app.route('/webhook', methods=['POST','GET'])
def webhook():
    xml = "hola"    
    t = Thread(target=send_email, args=(xml,))
    t.start()
    print "acabando"
    return '',200


@app.route('/response', methods=['POST','GET'])
def response():
    print xml #Comprobar como comparto la variable.
    return None

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))
    app.run(debug=True, port=port, host='0.0.0.0', threaded=True)

The code receives the first call to / webhook, where it gives xml the value "hello" and opens a thread to execute a code (print the hello value). Up there all right, but now when I make the call to / response, it prints a gap, it does not print "hello" which is what I need.

Any ideas on how to make the value I get in / webhook stay to use in / response?

Thank you very much

    
asked by Alex 12.06.2017 в 18:43
source

1 answer

2

There is an important difference between accessing the name (reading the variable) and linking it within a scope.

You assign the variable xml within the local scope of webhook which links that name to this scope. Although it also exists as a global variable, it hides it.

If you want to be able to assign values to the global name, you must explicitly indicate that the global variable is used and do not create a local binding. This is done with the reserved word global .

Your function should look like this:

def webhook():
    global xml
    xml = "hola"    
    t = Thread(target=send_email, args=(xml,))
    t.start()
    print "acabando"
    return '',200

To read the variable is not necessary but to assign values to it.

Be careful what you do with the variable and where and how you use it, even more if you put asynchronism in between.

    
answered by 12.06.2017 / 19:18
source