如何使用urllib2制作HTTP DELETE方法?

Pol*_*Pol 45 python urllib2

是否urllib2支持DELETE或PUT方法?如果是,请提供任何示例.我需要使用活塞API.

Cor*_*erg 72

你可以用httplib做到这一点:

import httplib 
conn = httplib.HTTPConnection('www.foo.com')
conn.request('PUT', '/myurl', body) 
resp = conn.getresponse()
content = resp.read()
Run Code Online (Sandbox Code Playgroud)

另外,看看这个问题.接受的答案显示了向urllib2添加其他方法的方法:

import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)
Run Code Online (Sandbox Code Playgroud)


Dav*_*ave 13

更正Raj的答案:

import urllib2
class RequestWithMethod(urllib2.Request):
  def __init__(self, *args, **kwargs):
    self._method = kwargs.pop('method', None)
    urllib2.Request.__init__(self, *args, **kwargs)

  def get_method(self):
    return self._method if self._method else super(RequestWithMethod, self).get_method()
Run Code Online (Sandbox Code Playgroud)

  • 使用`self._method = kwargs.pop('method',None)`会更短 (2认同)
  • 使用super给我一个_TypeError_.相反,我使用了`urllib2.Request.get_method(self)` (2认同)

Ali*_*ali 8

https://gist.github.com/kehr/0c282b14bfa35155deff34d3d27f8307找到以下代码,它对我有用(Python 2.7.5):

import urllib2

request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'DELETE'
response = urllib2.urlopen(request)
Run Code Online (Sandbox Code Playgroud)


Raj*_*Raj 7

您可以对urllib2.Request对象进行子类化,并在实例化该类时覆盖该方法.

import urllib2

class RequestWithMethod(urllib2.Request):
  def __init__(self, method, *args, **kwargs):
    self._method = method
    urllib2.Request.__init__(*args, **kwargs)

  def get_method(self):
    return self._method
Run Code Online (Sandbox Code Playgroud)

Benjamin Smedberg友情提供