您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“Python中Django框架單元測(cè)試之文件上傳測(cè)試的示例分析”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Python中Django框架單元測(cè)試之文件上傳測(cè)試的示例分析”這篇文章吧。
具體如下:
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})
測(cè)試文件上傳其實(shí)沒有什么特殊的,只需要指定后端接受請(qǐng)求數(shù)據(jù)的對(duì)應(yīng)鍵值即可
(The name avatar here is not relevant; use whatever name your file-processing code expects.)在這里avatar是關(guān)聯(lián)的,對(duì)應(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})
以上是“Python中Django框架單元測(cè)試之文件上傳測(cè)試的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。