从 Python 脚本使用 POST 发送文件 [英] Send file using POST from a Python script

查看:29
本文介绍了从 Python 脚本使用 POST 发送文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从 Python 脚本中使用 POST 发送文件?

解决方案

来自:https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file

请求使上传多部分编码文件变得非常简单:

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

就是这样.我不是在开玩笑——这是一行代码.文件已发送.让我们检查一下:

<预><代码>>>>r.text{起源":179.13.100.4",文件":{"report.xls": "<审查...二进制...数据>"},形式": {},"url": "http://httpbin.org/post",参数":{},标题":{内容长度":3196","Accept-Encoding": "身份,放气,压缩,gzip",接受": "*/*","用户代理": "python-requests/0.8.0","Host": "httpbin.org:80",内容类型":多部分/表单数据;边界=127.0.0.1.502.21746.1321131593.786.1"},数据": ""}

Is there a way to send a file using POST from a Python script?

解决方案

From: https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file

Requests makes it very simple to upload Multipart-encoded files:

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

That's it. I'm not joking - this is one line of code. The file was sent. Let's check:

>>> r.text
{
  "origin": "179.13.100.4",
  "files": {
    "report.xls": "<censored...binary...data>"
  },
  "form": {},
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "3196",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.8.0",
    "Host": "httpbin.org:80",
    "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"
  },
  "data": ""
}

这篇关于从 Python 脚本使用 POST 发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆