requests
Posted 欧阳物语
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了requests相关的知识,希望对你有一定的参考价值。
import requests,json
def fun1():
url = "http://yun.zenm.vip/iot/account/login/"
#生成状态保持的session对象
session = requests.Session()
data = {
\'username\': \'peter\',
\'password\': \'admin\'
}
#使用session的时候,请求的参数要先转化为json格式
import json
json_data = json.dumps(data)
header= {
"Content-Type":"application/json"
}
res2 = session.post(url=url,data=json_data,headers = header)
print(res2)
print(res2.json())
#后续请求继续在session对象里发起即可
url_mine = \'http://yun.zenm.vip/iot/account/get/companys/\'
res4 = session.get(url = url_mine)
print(res4.json())
# requests操作请求头以及携带参数,获取响应的json数据
# 准备请求头
def fun2():
url = "http://ihrm-test.itheima.net/api/sys/login"
data = {
\'mobile\':\'13800000002\',\'password\':\'123456\'
}
json_data = json.dumps(data)
deader = {
"Content-Type": "application/json"
}
res = requests.post(url=url,data=json_data,headers=deader)
res_data = res.json()
token = res_data[\'data\']
print(token)
new_token = \'Bearer \'+token
new_deader = {
"Authorization":new_token,
"Content-Type":"application/json"
}
url = "http://ihrm-test.itheima.net/api/sys/user"
data = {
"page":1,
"size":10
}
#发起请求,headers是请求头的数据,params是请求所携带的参数。
res1 = requests.get(url=url, headers = new_deader, params=data)
print(res1)
res_data = res1.json()
print(res_data)
return new_deader
def post1():
URL = "http://ihrm-test.itheima.net/api/sys/login"
data = {
"mobile": "13800000002", "password": "123456"
}
json_data = json.dumps(data)
deader = {
"Content-Type": "application/json"
}
res = requests.post(url=URL,data=json_data,headers=deader)
res_data = res.json()
token = res_data["data"]
print(token)
new_token = "Bearer "+token
new_deader = {
"Authorization":new_token,
"Content-Type":"application/json"
}
url = \'http://ihrm-test.itheima.net/api/sys/user\'
data = {
"username":"立刻恢复",
"mobile":"13454563025",
"workNUmber":"222229"
}
json_data = json.dumps(data)
res = requests.post(url=url,headers=new_deader,data=json_data)
print(res)
res_data = res.json()
print(res_data)
def get1():
a = fun2()
url = \'http://ihrm-test.itheima.net/api/sys/user/1407169981648588800\'
res = requests.get(url=url,headers=a)
print(res)
res_data = res.json()
print(res_data)
def put1():
a = fun2()
url = \'http://ihrm-test.itheima.net/api/sys/user/1407169141227507712\'
data = {
"usernam":"立e刻恢复"
}
json_data = json.dumps(data)
res = requests.put(url=url,headers=a,data=json_data)
print(res)
res_data = res.json()
print(res_data)
def delete1():
a = fun2()
url = \'http://ihrm-test.itheima.net/api/sys/user/1407169981648588800\'
res = requests.delete(url=url,headers=a)
print(res)
res_data = res.json()
print(res_data)
if __name__ == "__main__":
post1()
以上是关于requests的主要内容,如果未能解决你的问题,请参考以下文章
C#-WebForm-★内置对象简介★Request-获取请求对象Response相应请求对象Session全局变量(私有)Cookie全局变量(私有)Application全局公共变量Vi(代码片段
Motan在服务provider端用于处理request的线程池
[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段