当前位置: 移动技术网 > IT编程>脚本编程>Python > 记录python上传文件的坑(2)

记录python上传文件的坑(2)

2019年11月23日  | 移动技术网IT编程  | 我要评论

j21战斗机,桌面背景图片淡雅,情缘书斋

描述:

1、之前在写项目mock代码时,碰到一个上传文件的接口,但项目接口本身有token保护机制,碰到token失效时,需要重新获取一次token后,再次对上传文件发起请求,在实际调用中发现,第一次调用上传接口能正常返回,但第二次获取新token再调用上传文件接口时,一直无返回数据,直到超时报错

有问题的代码如下:

 1 from requests_toolbelt import multipartencoder
 2 import requests
 3 
 4 m = multipartencoder(fields={'upload': open('test.txt', 'rb')},
 5                      boundary='----webkitformboundarytztjqrwcjjcjimvq')
 6 params = {'path': 'test.txt',
 7           'token': '123456',
 8           'num': 0, 'offset': 0,
 9           'limit': 8}
10 response = requests.post('http://httpbin.org/post',
11                          params=params,
12                          data=m,
13                          headers={'content-type': m.content_type})
14 # print("1: ", response.text)
15 # print("2: ", response.request.body)
16 # print("3: ", response.request.headers)
17 
18 print(2)
19 response1 = requests.post('http://httpbin.org/post',
20                          params=params,
21                          data=m,
22                          headers={'content-type': m.content_type})

 

2、后面通过fiddler抓包发现,在第二次请求上传接口时,body丢失了,通过debug定位,发现第二次请求在调用requests库时,body中是有值的,当进入requests库后,body丢失,故在requests官方库中提问,最终找到了解决办法

fiddler抓包截图如下:

第一次请求:

 

第二次请求:

 

3、最终request库的参与者回复了我的疑问,提示我需要在第一次读取文件后,把光标挪到首位,或关闭文件,在第二次调用时,再次从文件首位开始读取

 

提问地址:

 

4、修改后的代码:

 1 from requests_toolbelt import multipartencoder
 2 import requests
 3 
 4 def read_file(filepath='test.txt'):
 5     fp = open(filepath, 'rb')
 6     # 这里要把光标挪到首位,或者直接fp.close()关闭文件
 7     fp.seek(0)
 8     return fp
 9 print(read_file())
10 m = multipartencoder(fields={'upload':read_file()},
11                      boundary='----webkitformboundarytztjqrwcjjcjimvq')
12 params = {'path': 'test.txt',
13           'token': '123456',
14           'num': 0, 'offset': 0,
15           'limit': 8}
16 response = requests.post('http://httpbin.org/post',
17                          params=params,
18                          data=m,
19                          headers={'content-type': m.content_type})
20 print("1: ", response.text)
21 
22 # 这里重新组装,并调用一下获取文件方法
23 m1 = multipartencoder(fields={'upload': read_file()},
24                      boundary='----webkitformboundarytztjqrwcjjcjimvq')
25 params1 = {'path': 'test.txt',
26           'token': '123456',
27           'num': 0, 'offset': 0,
28           'limit': 8}
29 response1 = requests.post('http://httpbin.org/post',
30                          params=params1,
31                          data=m1,
32                          headers={'content-type': m1.content_type})
33 print("2: ", response1.text)

在此备注下,以防以后再次踩坑!!!

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网