记录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',
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)

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

猜你喜欢

转载自www.cnblogs.com/longweiqiang/p/11918033.html
今日推荐