全局变量与Python Flask

24

我希望做的就是显示一个API中的第一个事件。变量名叫做“firstevent”,它的值应该在网页上显示。但是“firstevent”在一个def函数内部,所以我将其改成了全局变量,并希望它可以在不同的函数之间使用。但是它显示“NameError: global name 'firstevent' is not defined”。这是我正在做的事情:

定义一个全局变量

global firstevent

将这个变量赋予一个随机值,它应该是events['items'][1]['end']

firstevent = 1

在网站上显示firstevent的值。

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

我不确定现在发生了什么,可能是作用域的问题吗?我已经查看了许多在线答案,但仍然找不到解决方案。

以下是详细信息(非全部代码)

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='XXXX@gmail.com', text='Appointment at Somewhere on June 3rd 10am-10:25am').execute()
  events = calendar.events().list(calendarId='XXXX@gmail.com').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()

请记住,在此上下文中,全局变量不是进程安全的。请参阅 https://dev59.com/E1wY5IYBdhLWcg3wRF9S#32825482。 - frainfreeze
1个回答

29

嗯,这是一个作用域问题。在你的main()函数开头添加以下代码:

global firstevent

应该就这样了。任何没有在函数内定义的变量,都是全局的。你可以从任何函数中直接访问它。但是,如果要修改变量,你需要在函数中写上global var

示例

下面的代码在函数中创建了一个局部变量“firstevent”:

firstevent = 0
def modify():
    firstevent = 1

这会修改全局变量'firstevent'

firstevent = 0
def modify():
    global firstevent
    firstevent = 1

是的,你在任何函数之外都有一个全局变量 firstevent。这不是它的工作方式。 - kindall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接