繁体   English   中英

python机械化中的http PUT方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM