Postman请求数据为null

来源:3-2 Request&Response对象-2

慕沐1390363

2022-11-14

老师,我通过Postman请求任何一个城市天气,在Postman里数据为null,却会在pycharm终端打印出来对应城市的天气,显示是请求正常的,状态码200,就是Postman里的数据为null,GET和POST都为null

Postman 截图如下:
图片描述
图片描述
图片描述
图片描述

我换其它函数请求,postman是可以返回数据的
图片描述

Postman请求,Postman返回null时pycharm终端打印结果如下图:
图片描述
图片描述

Views下weather.py代码如下:

def weather(request):
	if request.method == 'GET':
		city = request.GET.get('city')
		data = juhe.main(city)
		return JsonResponse(data=data,safe=False,status=200)
	elif request.method =='POST':
		received_body = request.body
		received_body = json.loads(received_body)
		cities = received_body.get('cities')
		response_data = []
		for city in cities:
			result = juhe.main(city)
			response_data.append(result)
		return JsonResponse(data=response_data,safe=False,status=200)

juhe API代码如下:

import urllib
import urllib.request as request
import urllib.error as error
import json


# 天气预报查询示例
def main(city):
    api_url = 'http://apis.juhe.cn/simpleWeather/query'  # api地址
    params_dict = {
        "city":city,  # 查询天气的城市名称,如:北京、苏州、上海
        "key": "1f974163bc1098fbc9e7de8450a61b3f",  # 您申请的接口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()

麻烦老师帮我看下哈,万分感谢

写回答

2回答

咚咚呛

2022-11-15

需要把key也写上。

"key": "1f974163bc1097fbc9e8de8450a61b3f",  # 您申请的接口API接口请求Key
0
9
慕沐1390363
回复
咚咚呛
哦,知道了,改成return就可以了,谢谢老师
2022-11-23
共9条回复

咚咚呛

2022-11-14

贴一下你postman上的截图和pycharm的代码呢,我帮你看看。
0
3
慕沐1390363
回复
咚咚呛
老师截图我已经添加到上面了,key这些参数配置和代码一致的
2022-11-15
共3条回复

Django+小程序技术打造微信小程序助手

0到1完整项目实战过程,是难得的Django+小程序全栈项目体验。

991 学习 · 507 问题

查看课程