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

作者:Lockeyi 时间:2022-02-26 23:50:51 

本文实例讲述了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})

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

(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")
   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框架单元测试之文件上传测试示例

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

来源:https://blog.csdn.net/Lockey23/article/details/80653091

标签:Python,Django,单元测试,文件上传
0
投稿

猜你喜欢

  • 如何对PHP程序中的常见漏洞进行攻击(下)

    2023-11-16 14:50:19
  • Asp 日期格式化问题

    2011-03-31 10:47:00
  • perl 简明教程 perl教程集合

    2023-08-08 19:58:12
  • Python程序设计入门(4)模块和包

    2023-06-18 11:37:36
  • 网站tab导航的设计

    2008-11-10 12:36:00
  • asp最简单的生成验证码代码

    2011-03-07 11:05:00
  • PHP实现网页内容html标签补全和过滤的方法小结【2种方法】

    2023-09-06 22:28:26
  • ASP 写的判断 Money 各个位值的函数

    2008-04-13 06:36:00
  • 用js更好地截取定长字符串

    2008-01-16 12:48:00
  • spyder快捷键与python符号化输出方式

    2023-08-23 11:58:24
  • PHP session反序列化漏洞深入探究

    2023-05-30 04:53:04
  • django框架模板中定义变量(set variable in django template)的方法分析

    2021-11-18 03:28:04
  • asp在sql server2000中新建帐号和给帐号权限代码

    2008-01-29 13:46:00
  • Python+Pygame制作"长沙版"大富翁

    2023-10-05 06:53:08
  • Python Pygame实战之打砖块小游戏

    2021-04-10 01:41:11
  • Python Tornado批量上传图片并显示功能

    2023-08-07 22:33:21
  • 在macOS上搭建python环境的实现方法

    2021-10-07 07:29:56
  • asp的日期转换星座函数

    2010-06-09 21:05:00
  • 如何使用postman(新手入门)

    2023-06-12 14:00:31
  • PHP完全二叉树定义与实现方法示例

    2023-07-04 10:49:10
  • asp之家 网络编程 m.aspxhome.com