首页 > Web开发 > 详细

requests上传文件的方法

时间:2021-01-14 11:28:28      阅读:35      评论:0      收藏:0      [点我收藏+]

 

基本方式一:

r = requests.post(http://httpbin.org/post, files={file: open(report.xls, rb)})

 

方式二(带其他参数):

import requests
import json

session = requests.session()
url = "http://cdht-sentinel.testing.bbdops.com/api/v1.0/auth/sso/login?t=669259"
data = {
    "ip": "--",
    "location": "--",
    "password": "71b44033d3814ca82c7d079e046d6765",
    "systemState": 2,
    "username": "adminc"
}
headers = {
    "Connection": "keep-alive",
    "Content-Encoding": "gzip",
    "Content-Type": "application/json;charset=UTF-8"
}
# 登录,获取cookie
response = session.post(url=url, data=json.dumps(data), headers=headers)
ret = json.loads(response.text)
print("登录成功?:", ret.get(success))

# 上传文件
url_upload = "http://cdht-sentinel.testing.bbdops.com/api/v1.0/building/company/employees/import?t=640796"
files = {file: open(0, rb)}
ret_upload = session.post(url_upload, data={buildingId: 23}, files=files)
print(ret_upload)
print(ret_upload.text)
print(ret_upload.content)

 

方式三(不使用requests.session(),而采用原生方式):

import requests

# 原生方式登录,得到cookie
response = requests.post(url="http://cdht-sentinel.testing.bbdops.com/api/v1.0/auth/sso/login?t=862637",
                         json={"ip": "182.150.28.190",
                               "location": "四川省成都市",
                               "password": "71b44033d3814ca82c7d079e046d6765",
                               "systemState": 2,
                               "username": "adminc"})
cookies = response.cookies

# 上传图片时带上cookie
response = requests.post(url="http://cdht-sentinel.testing.bbdops.com/api/v1.0/building/file/upload?t=670869",
                         files={"file": open("1920_1080.jpg", "rb")},
                         cookies=cookies)

print(response.text)  # 上传图片成功

 

requests上传文件的方法

原文:https://www.cnblogs.com/staff/p/14275561.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!