首要要安装requests,安装命令是pip install requests
1、发送请求和传递参数_get请求方式
import requests
r = requests.get(url=‘http://www.itwhy.org‘) #最基本的GET请求
print(r.status_code) #获取返回状态
r = requests.get(url=‘http://dict.baidu.com/s‘, params={‘wd‘:‘python‘}) #带参数的GET请求
print(r.url)
print(r.text) #打印解码后的返回数据,返回的是一个字符串类型
2、发送请求和传递参数_post请求方式
url = "http://127.0.0.1:8000/login"
data = {"username":"jmy1235","password":123456}
req = requests.post(url,data)
print(req.text) #字符串,json串
print(type(req.text)) #返回的数据类型是字符串
print(req.json()) #返回的是字典
print(type(req.json())) #返回的数据类型是字典
3、传header、cookie
def get_sign(url,data): #封装成一个函数,获取sign
res = requests.post(url,data).json() #返回一个字典,可以取sign
print(res)
return res[‘sign‘]
print(get_sign(url,data))
发带cookie、header
sign = get_sign(url,data)
cookie = {‘sign‘:sign}
header = {"sunshujiang":"haha"}
data2 = {
‘username‘:‘jmy1235‘,
‘real_name‘:‘孙树江‘,
‘class‘:‘巨蟹座‘,
‘phone‘:‘13800138000‘
}
url = ‘http://127.0.0.1:8000/add_stu2‘
r = requests.post(url,json = data2,cookies = cookie,headers = header)
print(r.text)
4、上传文件
@server.route(‘/upload‘,methods=[‘post‘])
def upload(): #上传文件接口
print(request.files)
f = request.files.get(‘file_name‘,None) #如果没有上传文件,默认是None
if f:
t =
time.strftime(‘%Y%m%d%H%M%S‘)#获取当前时间
new_file_name = t+f.filename#给文件重命名,防止有重复文件覆盖
abs_path =
os.path.join(UPLOAD_PATH,new_file_name)
f.save(abs_path)#保存文件
return
my_json({"code":"ok"})
else:
return
my_json({"msg":"请上传文件!"})
file = {‘file_name‘:open(‘上周回顾.py‘,encoding = ‘utf8‘)}
url = ‘http://127.0.0.1:8000/upload‘
r = requests.post(url,files = file)
print(r.text)