python使用requests實現(xiàn)發(fā)送帶文件請求功能
1. requests發(fā)送文件功能
Requests 使得上傳多部分編碼文件變得很簡單
url = 'http://httpbin.org/post'
files = {'file': open('D:/APPs.png', 'rb')}
r = requests.post(url, files=files)
print(r.text)你可以顯式地設置文件名,文件類型和請求頭:
url = 'http://httpbin.org/post'
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
print(r.text)如果你想,你也可以發(fā)送作為文件來接收的字符串:
url = 'http://httpbin.org/post'
files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
r = requests.post(url, files=files)
print(r.text)如果你發(fā)送一個非常大的文件作為 multipart/form-data 請求,你可能希望將請求做成數(shù)據(jù)流。默認下 requests 不支持, 但有個第三方包 requests-toolbelt 是支持的。你可以閱讀 toolbelt 文檔 來了解使用方法。
2. requests發(fā)送多個文件請求
只要把文件設到一個元組的列表中,其中元組結構為 (form_field_name, file_info)
按照如下格式發(fā)送數(shù)據(jù)
data = {'ts_id': tsid}
files = [('images',('1.png', open('/home/1.png', 'rb'),'image/png')),('images',('2.png', open('/home/2.png', 'rb'),'image/png'))]
r = requests.post(url, data=data, files=files)
print r.text3. Django 接收文件
附帶介紹Django里面如何接收圖片文件數(shù)據(jù):
讀取文件:
from werkzeug.utils import secure_filename
def upload_file(request):
if request.method == 'POST':
uploaded_files = request.FILES.getlist("images")
try:
for file in uploaded_files:
filename = secure_filename(file.name)
handle_uploaded_file(os.path.join(ft, filename), file)
except Exception as e:
result_json = {"msg": str(e)}
result = {
'json': result_json
}
return JsonResponse(result, safe=False)保存文件:
def handle_uploaded_file(filename, f):
try:
destination = open(filename, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
except Exception as e:
raise Exception('save %s failed: %s' % (filename, str(e)))requests 官網(wǎng):http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#post-multipart-encoded
到此這篇關于python使用requests實現(xiàn)發(fā)送帶文件請求的文章就介紹到這了,更多相關python requests發(fā)送文件請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python Pygame實戰(zhàn)之趣味籃球游戲的實現(xiàn)
這篇文章主要為大家分享了一個基于Python和Pygame實現(xiàn)的一個趣味籃球游戲,文中的示例代碼講解詳細,對我們學習Python有一定幫助,需要的可以參考一下2022-04-04
Python使用嵌套循環(huán)實現(xiàn)圖像處理算法
這篇文章主要給大家詳細介紹Python如何使用嵌套循環(huán)實現(xiàn)圖像處理算法,文中有詳細的代碼示例,具有一定的參考價值,需要的朋友可以參考下2023-07-07

