2017-06-17 44 views
3

編輯:我在this question嘗試了一切,並沒有解決問題。含義我想我嘗試手動添加FormParser和MultiPartParser到DEFAULT_PARSER_CLASSES的設置,我試圖改變django.test.TestCase到rest_framework.test.APITestCase。我仍然得到相同的錯誤代碼。獲得415碼django.test.Client的補丁方法

當我發送PATCH請求,通過在命令行上本地主機上運行,​​像這樣我的Django應用程序:

http -a <username>:<password> PATCH http://127.0.0.1:8000/post/1/ text="new text" 

它按預期工作,我得到一個200 OK代碼回來。

當我嘗試使用django.test.Client.patch方法這樣做同樣的事情在我的單元測試:

In [1]: from django.test import Client 
In [2]: client = Client() 
In [3]: client.login(username='<username>', password='<password>') 
Out[3]: True 
In [4]: client.patch('/post/1/', {'text': 'new text'}) 
Out[4]: <Response status_code=415, "application/json"> 

我得到一個415(不支持的媒體)響應代碼。該response.dataUnsupported media type "application/octet-stream" in request.'

如果我嘗試添加參數content-type='application/json'patch方法(我不應該這樣做,因爲我能夠發送GETPOSTDELETE請求使用Client類沒有提供參數)我得到一個400錯誤代碼。而response.data'JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)'

正如我所說的,當我使用類的getdelete,並post方法,該行爲是按預期。

現在用的方法正確嗎?這是一個錯誤?

+1

的可能的複製[Django的休息框架HTTP PUT Django上與415沒有1.5(https://stackoverflow.com/questions/15153048/django-rest-框架-HTTP-放不盡,與-415-上的Django-1-5) – Linch

+0

@Linch不解決這個問題。 –

+0

你試過編碼字典作爲JSON作爲相關的問題所暗示的,即'client.patch( '/後/ 1 /',json.dumps({ '文': '新文本'}),CONTENT_TYPE =「應用/ JSON「)'? – Alasdair

回答

6

據我所知,httpie發送與內容類型application/json的請求。

所以,試試這個:

import json 
data = json.dumps({'text': 'new text'}) 

client.patch('/post/1/', data, content_type='application/json')