• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python Django框架单元测试之文件上传测试示例

python 搞代码 4年前 (2022-01-08) 16次浏览 已收录 0个评论

这篇文章主要介绍了Python Django框架单元测试之文件上传测试,结合实例形式分析了Django框架单元测试中文件上传测试的操作步骤与相关实现技巧,需要的朋友可以参考下

本文实例讲述了Python Django框架单元测试之文件上传测试。分享给大家供大家参考,具体如下:

Submitting files is a special case. To POST a file, you need only provide th

来源gaodai.ma#com搞##代!^码@网

e 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-600') as fp: ...   c.post('/account/avatar_upload/',{'avatar':fp}) 

测试文件上传其实没有什么特殊的,只需要指定后端接受请求数据的对应键值即可

(The name avatar here is not relevant; use whatever name your file-processing code expects.)在这里avatar是关联的,对应着具体的后端处理程序代码,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-600") 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-600") else: avartaPath = os.path.join(STATIC_URL, 'avatar/origin_imgs', nt_id + "_avatar.jpg-600") User.objects.filter(nt_id=nt_id).update(avatar=avartaPath) return render(request, 'profile.html', {'user': user}) 

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

以上就是Python Django框架单元测试之文件上传测试示例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python Django框架单元测试之文件上传测试示例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址