我遇到键盘错误:“ main”。我搜索了许多站点,但仍然找不到任何令人满意的答案来解决此错误。如果有人可以给我一些指导,我将不胜感激。提前致谢。
我尝试通过在站点建议的 init .py上添加一个函数来解决此问题。但是它仍然没有用。 https://forum.inductiveautomation.com/t/error-on-sys-modules/6431/2
代码:view.py
#special-deals-animation {
position: relative;
width: 100%;
background-color: #fff;
height:auto;
overflow :hidden;
margin: 20px 0;
}
#animation-container {
width: 50%;
margin: 2% 25%;
display: none;
text-align: center;
}
#special-deals-animation.active {
border: 1px solid #f00;
width: 100%;
transition: left 0.15s ease 0.15s, height 0.5s ease 0.5s;
animation-iteration-count: 1;
}
#special-deals-animation.inactive {
width: 0;
height: 0;
transition: left 0.15s ease 0.5s, height 0.5s ease;
animation-iteration-count: 1;
}
终端:
from django.shortcuts import render
import requests
from .models import City
def index(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=MYKey'
cities = City.objects.all() # return all the cities in the database
city = 'Dhaka'
# request the API data and convert the JSON to Python data types
city_weather = requests.get(url.format(city)).json()
weather_data = []
for city in cities:
# request the API data and convert the JSON to Python data types
city_weather = requests.get(url.format(city)).json()
weather_app = {
'city': city,
'temperature': city_weather['main']['temp'],
'description': city_weather['weather'][0]['description'],
'icon': city_weather['weather'][0]['icon']
}
# add the data for the current city into our list
weather_data.append(weather_app)
#context = {'weather' : weather_app}
context = {'weather_data': weather_data}
# returns the index.html template
return render(request, 'weather_app/index.html')
答案 0 :(得分:1)
您无需检查是否已找到特定城市的数据。您遍历数据库中的所有城市,并尝试获取每个城市的天气;但您不检查结果是否实际返回。您应该这样做:
for city in cities:
response = requests.get(url.format(city))
if response.status_code == 404:
continue
city_weather = response.json()
此外,您应该检查自己是否正确设置了网址格式。就目前而言,您是将City对象直接插入URL中-仅当您定义了仅返回城市名称的__str__
方法时,此方法才有效。最好直接使用该名称:
response = requests.get(url.format(city.name)) # or whatever the name field is
答案 1 :(得分:-1)
我不确定。我有个建议。在制作city_weather
之前,您可以检查weather_app
数据(使用print())以查看密钥'main'
是否确实在city_weather
中,也许密钥恰巧不在数据。