Python Django框架單元測(cè)試之文件上傳測(cè)試示例
本文實(shí)例講述了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})

希望本文所述對(duì)大家基于Django框架的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
一個(gè)非常簡(jiǎn)單好用的Python圖形界面庫(PysimpleGUI)
這篇文章主要介紹了一個(gè)非常簡(jiǎn)單好用的Python圖形界面庫,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
wxPython多個(gè)窗口的基本結(jié)構(gòu)
這篇文章主要為大家詳細(xì)介紹了wxPython多個(gè)窗口的基本結(jié)構(gòu),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11
OpenCV實(shí)現(xiàn)圖像平滑處理的方法匯總
這篇文章為大家詳細(xì)介紹了在圖像上面進(jìn)行了圖像均值濾波、方框?yàn)V波 、高斯濾波、中值濾波、雙邊濾波、2D卷積等具體操作的方法,需要的可以參考一下2023-02-02
pycharm運(yùn)行程序時(shí)在Python console窗口中運(yùn)行的方法
今天小編就為大家分享一篇pycharm運(yùn)行程序時(shí)在Python console窗口中運(yùn)行的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12
TensorFlow實(shí)現(xiàn)簡(jiǎn)單線性回歸
這篇文章主要為大家詳細(xì)介紹了TensorFlow實(shí)現(xiàn)簡(jiǎn)單線性回歸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
face++與python實(shí)現(xiàn)人臉識(shí)別簽到(考勤)功能
這篇文章主要為大家詳細(xì)介紹了face++與python實(shí)現(xiàn)人臉識(shí)別簽到(考勤)功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08

