使用 Python 的 XML POST REST 请求
有人有一个使用 Python 向 RESTful API 发送 XML POST 请求的简单示例吗?我试图使用 urllib2 Python 库在 Harvest API 中“创建一个新项目”,但没有成功。 Payload 变量是一个有效的 XML 文档,它是其文档(在“创建新项目”标题下)的近乎复制/粘贴,如下所示:
http://www.getharvest.com/api/projects
这是我尝试执行的代码。
def postRequest():
""" Makes POST request to url, and returns a response. """
url = 'http://subdomain.harvestapp.com/projects'
opener = urllib2.build_opener()
opener.addheaders = [('Accept', 'application/xml'),
('Content-Type', 'application/xml'),
('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password))[:-1]),
('User-Agent', 'Python-urllib/2.6')]
req = urllib2.Request(url=url, data=payload)
assert req.get_method() == 'POST'
response = self.opener.open(req)
print response.code
return response
我收到响应代码 200(状态正常)而不是响应代码 201(已创建)...这是 Harvest 支持人员的问题吗?
任何人的任何提示将不胜感激。
谢谢, 杰夫.
Does anyone have a simple example of sending an XML POST request to a RESTful API with Python? I am trying to use the urllib2 Python library to "create a new project" in the Harvest API, with no luck. The payload variable is a valid XML document that is a near copy/paste of their documentation (under the Create New Project heading) shown here:
http://www.getharvest.com/api/projects
Here is the code I am trying to execute.
def postRequest():
""" Makes POST request to url, and returns a response. """
url = 'http://subdomain.harvestapp.com/projects'
opener = urllib2.build_opener()
opener.addheaders = [('Accept', 'application/xml'),
('Content-Type', 'application/xml'),
('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password))[:-1]),
('User-Agent', 'Python-urllib/2.6')]
req = urllib2.Request(url=url, data=payload)
assert req.get_method() == 'POST'
response = self.opener.open(req)
print response.code
return response
I receive a response code 200 (Status OK) instead of a response code 201 (Created)...is this a question for the Harvest Support guys?
Any hints anyone has would be greatly appreciated.
Thanks,
Jeff.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
即使 201 响应严格来说更合适,但返回 200 响应也是很常见的。即使您收到“正确”响应,您是否确定请求未得到正确处理?
It's common to return a 200 response even when a 201 response would strictly be more appropriate. Are you sure that the request isn't correctly processed even if you are getting a 'correct' response?
除了创建响应的行(使用 self.opener )之外,您在任何地方都使用本地开启器,这看起来像是问题所在。
You're using a local opener everywhere except on the line where you create the response, where you use
self.opener
, which looks like the problem.