簡體   English   中英

使用 Python urllib2 執行 PUT

[英]Doing PUT using Python urllib2

我正在嘗試按照我在 stackoverflow 上找到的示例使用 urllib2 執行 PUT 到 REST:

有沒有辦法在python中做HTTP PUT

我不明白為什么我會收到錯誤錯誤。

這是我的代碼的摘錄:

import urllib2
import json

content_header = {'Content-type':'application/json',
                 'Accept':'application/vnd.error+json,application/json',
                 'Accept-Version':'1.0'}

baseURL = "http://some/put/url/"


f = open("somefile","r")
data = json.loads(f.read())

request = urllib2.Request(url=baseURL, data=json.dumps(jsonObj), headers=content_header)
request.get_method = lambda: 'PUT' #if I remove this line then the POST works fine.

response = urllib2.urlopen(request)

print response.read()

如果我刪除了我嘗試設置的 PUT 選項,那么它會發布它 find 但當我嘗試將 get_method 設置為 PUT 時它會出錯。

為了確保 REST 服務不會導致問題,我嘗試使用 cURL 執行 PUT 並且它運行良好。

雖然 aaronfay 的回答很好並且有效,但我認為鑒於除了 GET 之外只有 3 個 HTTP 方法(並且您只擔心 PUT),只定義每個方法的 Request 子類更清晰、更簡單。

例如:

class PutRequest(urllib2.Request):
    '''class to handling putting with urllib2'''

    def get_method(self, *args, **kwargs):
        return 'PUT'

然后使用:

request = PutRequest(url, data=json.dumps(data), headers=content_header)

正如其他人所指出的, requests是一個很棒的庫。 但是,如果您處於無法使用requests的情況(例如 ansible 模塊開發或類似的情況),還有另一種方法,如本要點的作者所示

import urllib2

class MethodRequest(urllib2.Request):
    def __init__(self, *args, **kwargs):
        if 'method' in kwargs:
            self._method = kwargs['method']
            del kwargs['method']
        else:
            self._method = None
        return urllib2.Request.__init__(self, *args, **kwargs)

    def get_method(self, *args, **kwargs):
        if self._method is not None:
            return self._method
        return urllib2.Request.get_method(self, *args, **kwargs)

用法:

>>> req = MethodRequest(url, method='PUT')

嘗試使用:

import urllib

data=urllib.urlencode(jsonObj)

而不是json.dumps 這個對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM