如何使用urllib2生成HTTP DELETE方法?

2024-03-29 11:56:05 发布

您现在位置:Python中文网/ 问答频道 /正文

urllib2是否支持DELETE或PUT方法?如果是,请举例说明。我需要使用活塞API。


Tags: 方法apiputurllib2delete
3条回答

您可以对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

Benjamin Smedberg提供

更正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()

你可以用httplib来完成:

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

还有,看看这个question。接受的答案显示了向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)

相关问题 更多 >