【requests】params和data

import requests

URL = "https://api.seniverse.com/v3/weather/now.json?"
city = '北京'

param = {
    "location": city,
    "key": "SCYrvkytJze9qyzOh"

}
# 第一种,使用get方法,参数有url,params
result = requests.get(url=URL, params=param)

# 第二种,使用post方法, 参数有url,params
# result = requests.post(url=URL,params=param)

第三种,使用post方法,参数有url,data
# result = requests.post(url=URL, data=param)   #{'status': 'The API key is invalid.', 'status_code': 'AP010003'}

res_json = result.json()
print(res_json)
# print(res_json['results'][0]['location']['path'])
# print(res_json['results'][0]['now']['text'])
# print(res_json['results'][0]['now']['temperature'])
# print(res_json['results'][0]['last_update'])

断言
assert res_json['results'][0]['location']['path'] == '北京,北京,中国' #正确,不报错

assert res_json['results'][0]['location']['path'] == '北京,中国'  # 报错,AssertionError

  小结:

    get请求,参数一般使用params(parameters), post请求一般使用data

    get请求一般是参数放在url地址里面,post请求一般放在body里面

    post可以使用data之外,还可以使用data,但是返回结果可能不同

上述代码结果:

    get和post的params参数,得到结果一样:  

{'results': [{'location': {'id': 'WX4FBXXFKE4F', 'name': '北京', 'country': 'CN', 'path': '北京,北京,中国', 'timezone': 'Asia/Shanghai', 'timezone_offset': '+08:00'}, 'now': {'text': '阴', 'code': '9', 'temperature': '22'}, 'last_update': '2022-06-13T15:50:05+08:00'}]}

    post的data参数,结果:

{'status': 'The API key is invalid.', 'status_code': 'AP010003'}

 

 
posted @ 2022-06-13 16:14  淫鬻  阅读(182)  评论(0编辑  收藏  举报