【问题标题】:How to send DELETE request in Pycurl ?如何在 Pycurl 中发送 DELETE 请求?
【发布时间】:2013-06-09 04:13:32
【问题描述】:

我不知道如何使用 pycurl 或 requests 在 python 中编写以下 curl 命令。

curl -X DELETE -d '{"key": "value"}' http://url/json

【问题讨论】:

    标签: python urllib python-requests pycurl


    【解决方案1】:

    基于the example from requests quickstart:

    import json
    
    url = 'http://url/json'
    payload = {'key': 'value'}
    headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
    
    r = requests.delete(url, data=json.dumps(payload), headers=headers)
    print(r.json())
    

    curl 命令的更直译可能是:

    import os
    import sys
    import requests
    
    headers={"Content-Type": "application/x-www-form-urlencoded"}
    r = requests.delete("http://url/json", data=b'{"key": "value"}',
                        headers=headers)
    n = os.write(sys.stdout.fileno(), r.content) # support bytes in Python 2 & 3 
    

    【讨论】:

      【解决方案2】:
      • 你可以看看:

      CURLOPT_CUSTOMREQUEST from libcurl documentation

      我曾经将“DELE file.txt”发送到 FTP 服务器的示例。

      def delete_ftp_hash_file(self, ftp_hash_file_old):
          c = pycurl.Curl()
          delete_hash_file = 'DELE ' + ftp_hash_file_old
          sys.stderr.write("{0:.<20} : {1} \n".format('FTP command ', delete_hash_file))
          c.setopt(pycurl.URL, self.server)
          c.setopt(pycurl.USERNAME, self.username)
          c.setopt(pycurl.PASSWORD, self.password)
          c.setopt(pycurl.VERBOSE, True)
          c.setopt(pycurl.DEBUGFUNCTION, self.test)
          c.setopt(pycurl.CUSTOMREQUEST, delete_hash_file)
          try:
              c.perform()
          except Exception as e:
              print e
          c.close()
      
      def test(self, debug_type, debug_msg):
          if len(debug_msg) < 300:
              print "debug(%d): %s" % (debug_type, debug_msg.strip())
      

      【讨论】:

        猜你喜欢
        • 2011-01-10
        • 1970-01-01
        • 2010-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-04
        相关资源
        最近更新 更多