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

网友投稿 896 2022-09-10

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

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

描述:

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库的参与者回复了我的疑问,提示我需要在第一次读取文件后,把光标挪到首位,或关闭文件,在第二次调用时,再次从文件首位开始读取

提问地址:https://github.com/psf/requests/issues/5270

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',

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:dos命令关机开机
下一篇:Windows切换内外网ip
相关文章

 发表评论

暂时没有评论,来抢沙发吧~