Có urllib2
hỗ trợ phương thức DELETE hoặc PUT không? Nếu có, vui lòng cung cấp bất kỳ ví dụ nào. Tôi cần sử dụng API piston.
- python
- urllib2
45 hữu ích 0 bình luận 40k xem chia sẻ
answer
74
bạn có thể làm điều đó với httplib :
import httplib
conn = httplib.HTTPConnection['www.foo.com']
conn.request['PUT', '/myurl', body]
resp = conn.getresponse[]
content = resp.read[]
ngoài ra, hãy kiểm tra câu hỏi này . câu trả lời được chấp nhận cho thấy một cách để thêm các phương thức khác vào urllib2:
import urllib2
opener = urllib2.build_opener[urllib2.HTTPHandler]
request = urllib2.Request['//example.org', data='your_put_data']
request.add_header['Content-Type', 'your/contenttype']
request.get_method = lambda: 'PUT'
url = opener.open[request]
74 hữu ích 3 bình luận chia sẻ
answer
14
Chỉnh sửa cho câu trả lời của 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[]
14 hữu ích 2 bình luận chia sẻ
answer
8
Đã tìm thấy mã sau từ //gist.github.com/kehr/0c282b14bfa35155deff34d3d27f8307 và nó đã hoạt động đối với tôi [Python 2.7.5]:
import urllib2
request = urllib2.Request[uri, data=data]
request.get_method = lambda: 'DELETE'
response = urllib2.urlopen[request]
8 hữu ích 1 bình luận chia sẻ
answer
7
Bạn có thể phân lớp đối tượng urllib2.Request và ghi đè phương thức khi bạn khởi tạo lớp.
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
Được phép của Benjamin Smedberg
7 hữu ích 0 bình luận chia sẻ
answer
1
Bạn có thể xác định một lớp con của Request
đối tượng và gọi nó như sau:
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[]
def put_request[url, data]:
opener = urllib2.build_opener[urllib2.HTTPHandler]
request = RequestWithMethod[url, method='PUT', data=data]
return opener.open[request]
def delete_request[url]:
opener = urllib2.build_opener[urllib2.HTTPHandler]
request = RequestWithMethod[url, method='DELETE']
return opener.open[request]
[Điều này tương tự như các câu trả lời ở trên, nhưng hiển thị cách sử dụng.]
1 hữu ích 0 bình luận chia sẻ