2013-08-18 46 views
3

,我想送一個HTTP POST多部分包含2個參數:Django的測試 - 如何在我的Django的測試中發送一個HTTP後多部分用JSON

  • JSON字符串
  • 文件
def test_upload_request(self): 
    temp_file = tempfile.NamedTemporaryFile(delete=False).name 
    with open(temp_file) as f: 
     file_form = { 
      "file": f 
     } 
     my_json = json.dumps({ 
      "list": { 
       "name": "test name", 
       "description": "test description" 
      } 
     }) 
     response = self.client.post(reverse('api:upload'), 
            my_json, 
            content=file_form, 
            content_type="application/json") 
    os.remove(temp_file) 


def upload(request):  
    print request.FILES['file'] 
    print json.loads(request.body) 

我的代碼不起作用。任何幫助? 如果有必要,我可以使用外部Python LIB(我想用請求) 謝謝

回答

3

隨着application/json內容類型,你不能上傳文件。

嘗試以下操作:

觀點:

def upload(request): 
    print request.FILES['file'] 
    print json.loads(request.POST['json']) 
    return HttpResponse('OK') 

測試:

def test_upload_request(self): 
    with tempfile.NamedTemporaryFile() as f: 
     my_json = json.dumps({ 
      "list": { 
       "name": "test name", 
       "description": "test description" 
      } 
     }) 
     form = { 
      "file": f, 
      "json": my_json, 
     } 
     response = self.client.post(reverse('api:upload'), 
            data=form) 
     self.assertEqual(response.status_code, 200) 
+0

謝謝@falsetru這麼簡單,你讓我一天 –

+0

@guillaumevincent,歡迎您。祝你今天愉快。 – falsetru