2013-07-24 104 views
-2

爲什麼我不能將方法更改爲PUT。我可以在沒有太多代碼更改的情況下更改爲PUT嗎?使用urllib2無法將HTTP方法更改爲PUT

這裏是我的代碼:

cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
urllib2.install_opener(opener) 

#code to change method to PUT 
opener.get_method = lambda: 'PUT' 

print "now using method:", meth # prints now using PUT 

try: 
    r = opener.open("http://the_url") 
except urllib2.HTTPError as e: 
    if hasattr(e, 'code'): 
     report += "HTTP error status " + str(e.code) + " FAIL\n" 
     if hasattr(e, 'reason'): 
      print "HTTP Error reason " + e.reason 
    else: 
     report += "HTTP error occurred FAIL\n" 

,但我得到運行時錯誤 HTTP錯誤原因,請求方法 'POST' 不支持 PUT會話測試 HTTP錯誤狀態405失敗

+0

拜託,你的生活會更輕鬆:http://docs.python-requests.org/en/latest/ – Marcin

+1

請提供一個[簡短,自包含的正確示例](http://sscce.org)演示你的問題。你所包含的代碼不是一個:如果你嘗試運行它,它會崩潰,並使用未定義的變量(例如'meth')。 –

回答

0

似乎只的urllib2支持GET和POST。我決定改用Apache Requests lib。

opener.get_method = lambda:'PUT'是我在網上找到的一些代碼。它實際上並不會改變用於發送請求的動詞,即使您使用get_method,它也會以您更改的方式回覆。

例如,在我的情況下,因爲請求包含數據(實際上沒有在上面的例子中顯示),它發送一個POST。

+0

http://stackoverflow.com/questions/111945/is-there-any-way-to-do-http-put-in-python 你'request.get_method'不是'opener.get_method'。儘管繼承'urllib2.Request'並覆蓋'get_method()'可能更好 – RedBaron