2015-08-14 93 views
2

我需要在Google Drive中使用requests python庫創建一個新文件。Drive API - 解析錯誤插入文件

r = requests.post(
    'https://www.googleapis.com/drive/v2/files', 
    headers={ 
     'Content-type': 'application/json; charset=UTF-8', 
     'Authorization': 'Bearer %s' % access_token 
    } 
) 

此代碼可以成功創建一個文件,並將所有值設置爲默認值,但如果我嘗試例如設置文件的標題:

r = requests.post(
    'https://www.googleapis.com/drive/v2/files', 
    data={"title": "Foo"}, 
    headers={ 
     'Content-type': 'application/json; charset=UTF-8', 
     'Authorization': 'Bearer %s' % self.access_token 
    } 
) 

然後服務器400 Bad Request和JSON響應響應:

{ 
    "error": { 
    "code": 400, 
    "message": "Parse Error", 
    "errors": [ 
     { 
     "domain": "global", 
     "message": "Parse Error", 
     "reason": "parseError" 
     } 
    ] 
    } 
} 

什麼我做錯了,如何解決呢?

回答

1

事實證明,當發送json請求時,數據參數應該是序列化的json對象。

r = requests.post(
    'https://www.googleapis.com/drive/v2/files', 
    data=json.dumps({"title": "Foo"}), 
    headers={ 
     'Content-type': 'application/json; charset=UTF-8', 
     'Authorization': 'Bearer %s' % self.access_token 
    } 
)