How do I make a PATCH request in Python?

假如想象 提交于 2019-12-01 15:44:42
Kenneth Reitz

With Requests, making PATCH requests is very simple:

import requests

r = requests.patch('http://httpbin.org/patch')
Travis Jensen

Seems to work in 2.7.1 as well.

>>> import urllib2
>>> request = urllib2.Request('http://google.com')
>>> request.get_method = lambda: 'PATCH'
>>> resp = urllib2.urlopen(request)
Traceback (most recent call last):
 ...
urllib2.HTTPError: HTTP Error 405: Method Not Allowed

I tried this in Python 3, and it seemed to work (but I don't have a server handy that supports the PATCH request type):

>>> import http.client
>>> c = http.client.HTTPConnection("www.google.com")
>>> r = c.request("PATCH", "/index.html")
>>> print(r.status, r.reason)
405 Method Not Allowed

I'm assuming that the HTTP 405 is coming from the server and that it is "not allowed".

By the way, thanks for showing me the cool PATCH method in HTTP.

It is incredibly simple with httplib2:

import httplib2

http = httplib2.Http()
http.request("http://www.google.com", "PATCH", <patch content>)

I've used the httplib2 library myself in a professional REST framework that includes PATCH support. It supports Python 2.3 or later (including 3.x) and works beautifully!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!