2012-06-22 108 views
1

我正在嘗試按照本指南在我的web應用程序中使用Youtube API https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2#OAuth2_Server_Side_Web_Applications_Flow我已經完成了第3步,並獲得了**授權代碼**。Python - 製作POST請求

現在我堅持做POST請求到這個網址https://accounts.google.com/o/oauth2/token

我要作出這樣的請求:(從我上面給出的鏈接所)

POST /o/oauth2/token HTTP/1.1 
Host: accounts.google.com 
Content-Type: application/x-www-form-urlencoded 

code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf& 
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com& 
client_secret=hDBmMRhz7eJRsM9Z2q1oFBSe& 
redirect_uri=http://localhost/oauth2callback& 
grant_type=authorization_code 

我想是這樣這樣的:

headers = {'Content-Type': 'application/x-www-form-urlencoded code=4/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&client_id=xxxxxxxxxxx.apps.googleusercontent.com&client_secret=xxxxxxxxxxxxxxxxx&redirect_uri=http://127.0.0.1:8000/information/youtube/&grant_type=authorization_code'} 

r = requests.post(url, headers) 

,我得到這個錯誤:

<Response [411]> 
u'<!DOCTYPE html>\n<html lang=en>\n <meta charset=utf-8>\n <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">\n <title>Error 411 (Length Required)!!1</title>\n <style>\n *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}\n </style>\n <a href=//www.google.com/><img src=//www.google.com/images/errors/logo_sm.gif alt=Google></a>\n <p><b>411.</b> <ins>That\u2019s an error.</ins>\n <p>POST requests require a <code>Content-length</code> header. <ins>That\u2019s all we know.</ins>\n' 

我知道我對發佈的請求有誤,我需要您的指導以瞭解如何使其工作。

謝謝!

回答

6

不要把數據的報頭。改爲使用data kwarg.post()。由於urlencoded POST主體是默認的,所以也不需要通過參數headers來指定它。

data = { 
    'code': '4/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 
    'client_id': 'xxxxxxxxxxx.apps.googleusercontent.com', 
    'client_secret': 'xxxxxxxxxxxxxxxxx', 
    'redirect_uri': 'http://127.0.0.1:8000/information/youtube/'. 
    'grant_type': 'authorization_code' 
} 
r = requests.post(url, data=data) 

可以使代碼更漂亮經由requests-oauth擴展讓請求成交與OAuth認證:https://github.com/maraujop/requests-oauth#readme

然後,你可以無需手動處理OAuth的參數執行您的要求。

+0

我在想...... django怎麼沒有內置的post請求模板標籤?有時,我們希望通過URL更改沒有表單的數據,實質​​上,它感覺就像一個post請求...一個例子是我想創建我自己的重置密碼,只是通過按鈕重置,但要做到這一點,我只是發送用戶到一個視圖,更改密碼,並重定向他們(我不想django的電子郵件鏈接令牌處理) – dtc

+0

嗯...什麼?我不知道你在做什麼。聽起來像是一個新的問題,但。 – ThiefMaster

+0

轉到這裏:http://docs.python-requests.org/en/master/這是貨物,有更多關於請求python庫的信息和例子 –