Python Django框架單元測試之文件上傳測試示例
本文實例講述了Python Django框架單元測試之文件上傳測試。分享給大家供大家參考,具體如下:
Submitting files is a special case. To POST a file, you need only provide the file field name as a key, and a file handle to the file you wish to upload as a value. For example:
>>> c = Client() >>> with open('test.jpg') as fp: ... c.post('/account/avatar_upload/',{'avatar':fp})
測試文件上傳其實沒有什么特殊的,只需要指定后端接受請求數(shù)據(jù)的對應(yīng)鍵值即可
(The name avatar here is not relevant; use whatever name your file-processing code expects.)在這里avatar是關(guān)聯(lián)的,對應(yīng)著具體的后端處理程序代碼,eg:
class Useravatar(View): def __init__(self): self.thumbnail_dir = os.path.join(STATIC_ROOT, 'avatar/thumbnails') self.dest_dir = os.path.join(STATIC_ROOT, 'avatar/origin_imgs') @method_decorator(login_required) def post(self, request): nt_id = request.session.get('user_id', 'default') user = User.objects.get(pk=nt_id) if User.objects.filter(pk=nt_id).exists() else None avatarImg = request.FILES['avatar'] if not os.path.exists(self.dest_dir): os.mkdir(self.dest_dir) dest = os.path.join(self.dest_dir, nt_id+"_avatar.jpg") with open(dest, "wb+") as destination: for chunk in avatarImg.chunks(): destination.write(chunk) if make_thumb(dest,self.thumbnail_dir): avartaPath = os.path.join(STATIC_URL, 'avatar/thumbnails', nt_id + "_avatar.jpg") else: avartaPath = os.path.join(STATIC_URL, 'avatar/origin_imgs', nt_id + "_avatar.jpg") User.objects.filter(nt_id=nt_id).update(avatar=avartaPath) return render(request, 'profile.html', {'user': user})
希望本文所述對大家基于Django框架的Python程序設(shè)計有所幫助。
相關(guān)文章
python3 dict ndarray 存成json,并保留原數(shù)據(jù)精度的實例
今天小編就為大家分享一篇python3 dict ndarray 存成json,并保留原數(shù)據(jù)精度的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12通過python模糊匹配算法對兩個excel表格內(nèi)容歸類
這篇文章主要介紹了通過python模糊匹配算法對兩個excel表格內(nèi)容歸類,比如兩個不同的工程項目針對的對象都是A,那么就需要將這兩個工程項目歸類到A當(dāng)中,可以減少很大一部分工作量,,需要的朋友可以參考下2023-03-03簡單介紹Python的Django框架的dj-scaffold項目
這篇文章主要介紹了簡單介紹Python的Django框架的dj-scaffold項目,用于輔助Django框架的目錄設(shè)置,需要的朋友可以參考下2015-05-05Python根據(jù)已知鄰接矩陣?yán)L制無向圖操作示例
這篇文章主要介紹了Python根據(jù)已知鄰接矩陣?yán)L制無向圖操作,涉及Python使用networkx、matplotlib進(jìn)行數(shù)值運(yùn)算與圖形繪制相關(guān)操作技巧,需要的朋友可以參考下2018-06-06Python Web框架Django的模型和數(shù)據(jù)庫遷移詳解
Django 是一個極其強(qiáng)大的 Python Web 框架,它提供了許多工具和特性,能夠幫助我們更快速、更便捷地構(gòu)建 Web 應(yīng)用,在本文中,我們將會關(guān)注 Django 中的模型(Models)和數(shù)據(jù)庫遷移(Database Migrations)這兩個核心概念,需要的朋友可以參考下2023-08-08