python使用requests實(shí)現(xiàn)發(fā)送帶文件請(qǐng)求功能
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)
你可以顯式地設(shè)置文件名,文件類型和請(qǐng)求頭:
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ā)送一個(gè)非常大的文件作為 multipart/form-data 請(qǐng)求,你可能希望將請(qǐng)求做成數(shù)據(jù)流。默認(rèn)下 requests 不支持, 但有個(gè)第三方包 requests-toolbelt 是支持的。你可以閱讀 toolbelt 文檔 來了解使用方法。
2. requests發(fā)送多個(gè)文件請(qǐng)求
只要把文件設(shè)到一個(gè)元組的列表中,其中元組結(jié)構(gòu)為 (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.text
3. Django 接收文件
附帶介紹Django里面如何接收?qǐng)D片文件數(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
到此這篇關(guān)于python使用requests實(shí)現(xiàn)發(fā)送帶文件請(qǐng)求的文章就介紹到這了,更多相關(guān)python requests發(fā)送文件請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Selenium中免登錄的實(shí)現(xiàn)方法option詳解
在selenium中有很多種可以實(shí)現(xiàn)網(wǎng)站的免登錄,option就是其中的一種做法,這篇文章主要介紹了Selenium中免登錄的實(shí)現(xiàn)方法option,需要的朋友可以參考下2022-12-12將.ipynb文件轉(zhuǎn)換成.py文件詳細(xì)步驟(一看就會(huì))
這篇文章主要給大家介紹了關(guān)于如何將.ipynb文件轉(zhuǎn)換成.py文件的詳細(xì)步驟,文中通過圖文介紹的非常詳細(xì),大家基本一看就會(huì),需要的朋友可以參考下2023-07-07Python3 列表,數(shù)組,矩陣的相互轉(zhuǎn)換的方法示例
這篇文章主要介紹了Python3 列表,數(shù)組,矩陣的相互轉(zhuǎn)換的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08對(duì)python中詞典的values值的修改或新增KEY詳解
今天小編就為大家分享一篇對(duì)python中詞典的values值的修改或新增KEY詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01