[英]http PUT method in python mechanize
我正在使用python機械化lib,並且嘗試在某些url上使用http PUT方法-但我找不到任何選擇。 我只看到GET和POST方法...
如果PUT方法不起作用,也許some1可以告訴我一個更好的庫來執行此操作?
一種可能的解決方案:
class PutRequest(mechanize.Request):
"Extend the mechanize Request class to allow a http PUT"
def get_method(self):
return "PUT"
然后,您可以在發出如下請求時使用此命令:
browser.open(PutRequest(url,data=your_encoded_params,headers=your_headers))
注意:我通過深入研究機械化代碼包來找出機械化設置HTTP方法的位置,從而得出了該解決方案。 我注意到,當我們調用mechanize.Request
,我們正在_request.py
中使用Request類,這反過來又擴展了_urllib2_fork.py
的Request類。 HTTP方法是在實際設置get_method
在Request類的_urllib2_fork.py
。 原來get_method
在_urllib2_fork.py
是只允許GET和POST方法。 為了克服這個限制,我最終編寫了自己的put和delete類來擴展機械化。 請求,但僅覆蓋get_method()
。
使用要求 :
>>> import requests
>>> result = requests.put("http://httpbin.org/put", data='hello')
>>> result.text
每個文檔 :
requests.put(url, data=None, **kwargs)
Sends a PUT request. Returns Response object.
Parameters:
url – URL for the new Request object.
data – (optional) Dictionary or bytes to send in the body of the Request.
**kwargs – Optional arguments that request takes.
通過機械化 :
import mechanize
import json
class PutRequest(mechanize.Request):
def get_method(self):
return 'PUT'
browser = mechanize.Browser()
browser.open(
PutRequest('http://example.com/',
data=json.dumps({'locale': 'en'}),
headers={'Content-Type': 'application/json'}))
另請參見http://qxf2.com/blog/python-mechanize-the-missing-manual/ (可能已過時)。
如朱 ( Key Zhu)所說, 請求以更好的方式做到了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.