首頁  >  文章  >  後端開發  >  如何從 Python 腳本透過 POST 請求傳送檔案?

如何從 Python 腳本透過 POST 請求傳送檔案?

DDD
DDD原創
2024-10-28 05:09:02328瀏覽

How to Send Files via POST Requests from Python Scripts?

從 Python 腳本透過 POST 發送檔案

使用 Requests 函式庫可以輕鬆實現利用 Python 腳本透過 POST 請求傳送檔案。該庫提供了一種簡單有效的方法來上傳多部分編碼的檔案。

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

這一行程式碼上傳文件,如以下回應所示:

{
  "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": ""
}

This回應確認文件已成功傳送。利用 Requests 函式庫的簡單功能簡化了透過 Python 腳本的 POST 請求傳送檔案的過程。

以上是如何從 Python 腳本透過 POST 請求傳送檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn