老师,我用得是python3.10,跟据老师的代码去写,跑不通,聚合数据提供了的示python3的示例代码,放到juhe.py里能跑,用到了rullib库,另外用到了try except判断,有一些看不懂,到views/weather.py里,就不知道怎么去调用juhe.py了,就卡在这里了。麻烦帮我看一下,谢谢
聚合数据提供代码:
import urllib
import urllib.request as request
import urllib.error as error
import json
# 天气预报查询示例
def main():
api_url = 'http://apis.juhe.cn/simpleWeather/query' # api地址
params_dict = {
"city": "北京", # 查询天气的城市名称,如:北京、苏州、上海
"key": "替换成我自己的了", # 您申请的接口API接口请求Key
}
params = urllib.parse.urlencode(params_dict)
try:
req = request.Request(api_url, params.encode())
response = request.urlopen(req)
content = response.read()
if content:
try:
result = json.loads(content)
error_code = result['error_code']
if (error_code == 0):
temperature = result['result']['realtime']['temperature']
humidity = result['result']['realtime']['humidity']
info = result['result']['realtime']['info']
wid = result['result']['realtime']['wid']
direct = result['result']['realtime']['direct']
power = result['result']['realtime']['power']
aqi = result['result']['realtime']['aqi']
print("温度:%s\n湿度:%s\n天气:%s\n天气标识:%s\n风向:%s\n风力:%s\n空气质量:%s" % (
temperature, humidity, info, wid, direct, power, aqi))
else:
print("请求失败:%s %s" % (result['error_code'], result['reason']))
except Exception as e:
print("解析结果异常:%s" % e)
else:
# 可能网络异常等问题,无法获取返回内容,请求异常
print("请求异常")
except error.HTTPError as err:
print(err)
except error.URLError as err:
# 其他异常
print(err)
if __name__ == '__main__':
main()