标签:记录 python response token params print requests 上传 post
描述:
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)
在此备注下,以防以后再次踩坑!!!
标签:记录,python,response,token,params,print,requests,上传,post 来源: https://www.cnblogs.com/longweiqiang/p/11918033.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。