使用Python上傳檔案至伺服器(不通過表單)

2021-10-08 17:57:04 字數 1125 閱讀 7692

框架:django

原理:使用requests庫的post方法上傳檔案至伺服器,後台接收並儲存檔案

1.post上傳檔案

自己新建乙個py檔案,把**複製到檔案裡,view.py裡寫好響應函式後執行

import requests

#url注意換成自己請求的應用對應的路徑

url = ''

header =

#檔案注意換成自己的對應的檔案

files =

res = requests.post(url=url, headers=header, files=files)

# print(res.text)

#返回狀態碼,200或500時為成功

print(res.status_code)

2.後台view.py裡寫對應的應用響應函式

from django.shortcuts import render

import os

def hello(request):

if request.method == 'post': # 獲取物件

#獲取上傳的檔案物件

files = request.files['file']

#獲取檔名

fname = files.name

#定義儲存路徑

fdir = 'e:\programming\python\django\project\mysite'

fpath = os.path.join(fdir, fname)

with open(fpath, 'wb') as f:

f.write(files.file.getvalue())

return render(request)

3.如果出現forbidden (csrf cookie not set.):的錯誤,把setting檔案中的django.middleware.csrf.csrfviewmiddleware注釋掉:

python上傳檔案至指定伺服器

import paramiko 建立ssh物件 ssh paramiko.sshclient ssh.load host keys c users administrator ssh known hosts 允許連線不在know hosts檔案的主機上 ssh.set missing host ke...

使用Git上傳檔案至Github

git add 新增當前資料夾下的所有檔案 git commit m baiduocr 引號中的內容為對該檔案的描述 然後在之前git bash here 的視窗,輸入命令 git remote add origin注意!如果出現錯誤 fatal remote origin already exis...

使用git 將檔案上傳至GitHub

上傳至github 遠端倉庫 git 中全域性設定使用者名稱 郵箱的操作如下,當然這一切的前提條件是已經安裝好git 的客戶端 程式。git config list git config user.name git config user.email git config global user.n...