gpt4 book ai didi

python - 全局变量和 python flask

转载 作者:太空狗 更新时间:2023-10-29 16:54:31 26 4
gpt4 key购买 nike

<分区>

我想做的只是显示来自一个 API 的第一个事件。该变量称为“firstevent”,其值应显示在网页上。但是firstevent在一个def里面,所以我把它改成一个全局变量,希望它可以跨不同的函数使用。但它显示“NameError:未定义全局名称'firstevent'”。这就是我正在做的:

定义一个全局变量

global firstevent

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

firstevent = 1

在网站上显示 firstevent 的值(value)。

@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()

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com