全局变量和python烧瓶 [英] Global variable and python flask
问题描述
定义一个全局变量
$ $ p $ $ $ $ $ $全球首发
发送这个变量一个随机值,它应该是 events [ 'items'] [1] ['end']
firstevent = 1
在网站上显示firstevent的价值。
$ b $返回'User% s'%firstevent
我不确定现在发生了什么,也许是范围问题?我在网上查了很多答案,但仍然找不到解决方案。
以下是详细信息(不是整个代码)
import os
#检索Flask,我们的框架
#request模块可以访问传入的请求数据
import argparse
import httplib2
import os
import sys
从jar文件中导入json文件
从bicher导入文件中请求
从oauth2client中导入文件
从oauth2client中导入文件
导入客户端
从oauth2client导入工具
从apiclient.discovery导入构建$ b $从oauth2client.client导入OAuth2WebServerFlow
导入httplib2
全局firstevent
app = Flask(__ name__)
def main(argv):
#解析命令行标志。
flags = parser.parse_args(argv [1:])
#如果证书不存在或无效,则通过本地客户端
#flow运行。存储对象将确保如果成功,良好的
#凭证将被写回到文件中。
storage = file.Storage('sample.dat')
credentials = storage.get()
如果凭证是None或credentials.invalid:
credentials = tools.run_flow( FLOW,存储,标志)
#创建一个httplib2.Http对象来处理我们的HTTP请求,并用我们良好的证书授权
#。
http = httplib2.Http()
http = credentials.authorize(http)
#构建与Calendar API交互的服务对象。
calendar = discovery.build('calendar','v3',http = http)
created_event = calendar.events()。quickAdd(calendarId='XXXX@gmail.com',text ='Appointment execute()
#firstevent()。 = events ['items'] [1] ['end']
firstevent = 1
#print events ['items'] [1] ['end']
主页路由
@ app.route(/)
def index():
return'User%s'%firstevent
#第二页路由
@ app.route(/ page2)
def page2():
return< html>< body>
< h2>欢迎使用第2页< / h2>
< p>这真是太神奇了!< / p>
< / body>< / html>
#启动网络服务器
if __name__ ==__main__:
app.debug = True
app.run()
是一个范围问题。在 main()
函数的开头添加:
全球首富
这应该做到。任何未在函数内定义的变量都是全局变量。你可以直接从任何函数访问它。但是,要修改这个变量,你需要在你的函数中写入 global var
。
$ b
这个函数创建一个局部变量firstevent:
< code $ f
$ b $修改全局变量'firstevent'
firstevent = 0
def modify():
global firstevent
firstevent = 1
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='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()
解决方案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
这篇关于全局变量和python烧瓶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!