【发布时间】:2021-03-30 14:24:41
【问题描述】:
这是我的views.py文件:
url = "https://covid-193.p.rapidapi.com/statistics"
headers = {
'x-rapidapi-key': "c5e4f10fa8msh519e24367741e55p1dcabajsn27df4eda14e0",
'x-rapidapi-host': "covid-193.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers).json()
def home(request):
noofresults = int(response['results'])
mylist = []
for x in range(0,noofresults):
mylist.append(response['response'][x]['country'])
if request.method=='POST':
selectedcountry= request.POST['selectedcountry']
# noofresults = int(response['results'])
for x in range(0,noofresults):
if selectedcountry==response['response'][x]['country']:
new = response['response'][x]['cases']['new']
active = response['response'][x]['cases']['active']
critical = response['response'][x]['cases']['critical']
recoverd = response['response'][x]['cases']['recovered']
total = response['response'][x]['cases']['total']
deaths = int(total)-int(active) - int(recoverd)
context = {'selectedcountry':selectedcountry,'mylist':mylist, 'new':new, 'active':active, 'critical':critical, 'recoverd':recoverd, 'total':total, 'deaths':deaths}
return render(request,'home.html',context)
context = {'mylist': mylist}
return render(request, 'home.html',context)
选择国家后出现的错误是:
UnboundLocalError at / local variable 'new' 在赋值前引用
【问题讨论】:
-
在for循环之前初始化
new, active, critical, recoverd, total, deaths
标签: python python-3.x django django-views