接上一篇,加入异常捕获和错误码处理
def queryweatherinfo():
url = "https://restapi.amap.com/v3/weather/weatherInfo"
key = '9bae4d790cfacdf4b54188b7758edf23'
data = {'key': key, "city": '320100'}
req = requests.post(url, data)
return req.json()
class GetWeatherInfo(View):
def get(self, request):
result = {}
try:
info = dict(queryweatherinfo())
weatherinfo = info['lives'][0]
result['status'] = 000
result['message'] = 'success'
result['info'] = {
'location': weatherinfo['province'] + weatherinfo['city'],
'weather': weatherinfo['weather'],
'temperature': weatherinfo['temperature'] + '℃',
'winddirection': weatherinfo['winddirection'],
'windpower': weatherinfo['windpower'],
'humidity': weatherinfo['humidity'],
'reporttime': weatherinfo['reporttime'],
}
return JsonResponse(
result,
json_dumps_params={'ensure_ascii': False}
)
except:
result['status'] = 500
result['message'] = '请求异常,请稍后重试'
result['info'] = {}
return JsonResponse(
result,
json_dumps_params={'ensure_ascii': False}
)
@csrf_exempt
def post(self, request):
# 查询到的数据是二进制
json_bytes = request.body
# 需要进行解码,转成字符串
json_str = json_bytes.decode()
# 在把字符串转换成json字典
weather_dict = json.loads(json_str)
city = weather_dict.get('city')
result = {}
try:
url = "https://restapi.amap.com/v3/weather/weatherInfo"
key = '9bae4d790cfacdf4b54188b7758edf23'
data = {'key': key, "city": city}
req = requests.post(url, data)
info = dict(req.json())
weatherinfo = info['lives'][0]
result['status'] = 000
result['message'] = 'success'
result['info'] = {
'location': weatherinfo['province'] + weatherinfo['city'],
'weather': weatherinfo['weather'],
'temperature': weatherinfo['temperature'] + '℃',
'winddirection': weatherinfo['winddirection'],
'windpower': weatherinfo['windpower'],
'humidity': weatherinfo['humidity'],
'reporttime': weatherinfo['reporttime'],
}
return JsonResponse(
result,
json_dumps_params={'ensure_ascii': False}
)
except:
result = {
'status': 500,
'message': '请求异常,请稍后重试',
'info': {}
}
return JsonResponse(
result,
json_dumps_params={'ensure_ascii': False}
)