>>c=Client()>>>withopen('test.jpg')asfp" />

日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python Django框架單元測試之文件上傳測試示例

系統 1977 0

本文實例講述了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框架單元測試之文件上傳測試示例_第1張圖片

希望本文所述對大家基于Django框架的Python程序設計有所幫助。


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 宜州市| 绥宁县| 安顺市| 许昌市| 海城市| 抚松县| 河南省| 大安市| 西青区| 甘洛县| 汝城县| 老河口市| 浠水县| 长治县| 搜索| 乡城县| 鞍山市| 宜春市| 栾城县| 大田县| 澄迈县| 应用必备| 尚志市| 西昌市| 明星| 承德市| 栖霞市| 连平县| 安乡县| 玉环县| 清水河县| 永顺县| 湘阴县| 阜阳市| 蒙城县| 乌兰浩特市| 贡觉县| 武城县| 武宁县| 苗栗县| 綦江县|