Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable and python flask [duplicate]

Tags:

What i want to do is just display the firstevent from one API. The variable is called “firstevent” and the value should display on the webpage. But firstevent is inside a def, so i change it into a global variable and hope it can be used across different functions. But it shows “NameError: global name 'firstevent' is not defined”. This is what I am doing:

define a global variable

global firstevent 

send this variable a random value, it supposed to be events['items'][1]['end']

firstevent = 1 

displaying firstevent’s value on website.

@app.route("/") def index():     return 'User %s' % firstevent 

I am not sure what’s happening now, maybe it’s a scope issue? I have check many answers online but still cannot find the solution.

Here are the details(not the whole code)

import os  # Retrieve Flask, our framework # request module gives access to incoming request data import argparse import httplib2 import os import sys import json  from flask import Flask, request from apiclient import discovery from oauth2client import file from oauth2client import client from oauth2client import tools  from apiclient.discovery import build from oauth2client.client import OAuth2WebServerFlow  import httplib2  global firstevent   app = Flask(__name__)  def main(argv):   # Parse the command-line flags.   flags = parser.parse_args(argv[1:])    # If the credentials don't exist or are invalid run through the native client   # flow. The Storage object will ensure that if successful the good   # credentials will get written back to the file.   storage = file.Storage('sample.dat')   credentials = storage.get()   if credentials is None or credentials.invalid:     credentials = tools.run_flow(FLOW, storage, flags)    # Create an httplib2.Http object to handle our HTTP requests and authorize it   # with our good Credentials.   http = httplib2.Http()   http = credentials.authorize(http)    # Construct the service object for the interacting with the Calendar API.   calendar = discovery.build('calendar', 'v3', http=http)   created_event = calendar.events().quickAdd(calendarId='[email protected]', text='Appointment at Somewhere on June 3rd 10am-10:25am').execute()   events = calendar.events().list(calendarId='[email protected]').execute()   #firstevent = events['items'][1]['end']    firstevent = 1   #print events['items'][1]['end']   # Main Page Route @app.route("/") def index():     return 'User %s' % firstevent   # Second Page Route @app.route("/page2") def page2():   return """<html><body>   <h2>Welcome to page 2</h2>     <p>This is just amazing!</p>     </body></html>"""   # start the webserver if __name__ == "__main__":     app.debug = True     app.run() 
like image 209
user2592038 Avatar asked Oct 04 '13 13:10

user2592038


People also ask

Can you use global variables in Flask?

To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request.

Are global variables thread safe in Flask how do I share data between requests?

You can't use global variables to hold this sort of data. Not only is it not thread safe, it's not process safe, and WSGI servers in production spawn multiple processes. Not only would your counts be wrong if you were using threads to handle requests, they would also vary depending on which process handled the request.

What happens when both local and global variables have the same name in Python?

If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.

Can we declare same variable in two times globally?

In C, multiple global variables are "merged" into one. So you have indeed just one global variable, declared multiple times.


1 Answers

Yep, it's a scope problem. In the beginning of your main() function, add this:

global firstevent 

That should done it. Any variable that is not defined inside a function, is a global. You can access it straightly from any function. However, to modify the variable you'll need to write global var in your function.

Example

This creates a local variable "firstevent" on the function:

firstevent = 0 def modify():     firstevent = 1 

And this modifies the global variable 'firstevent'

firstevent = 0 def modify():     global firstevent     firstevent = 1 
like image 99
aIKid Avatar answered Sep 18 '22 13:09

aIKid