【问题标题】:Testing a RESTful API with POSTs from Python使用 Python 的 POST 测试 RESTful API
【发布时间】:2011-09-17 14:22:10
【问题描述】:

我正在尝试测试我正在开发的 RESTful 接口(我正在使用这个接口:codeigniter-restserver),并且我想使用 Python。

GETs 似乎工作正常,但我遇到了POSTs 的问题。我不是在问这个图书馆的来龙去脉,而是我只是在尝试 弄清楚如何用 Python 测试POSTing。这就是我所拥有的:

import httplib, urllib

params = urllib.urlencode({
    'sentence':     'esta es una frase',
    'translation':  'this is a sentence'
})

headers = {
    "Content-type": "application/x-www-form-urlencoded", 
    "Accept":       "text/plain"
}

conn = httplib.HTTPConnection("localhost:80")
conn.request("POST", "/myapp/phrase", params, headers)

response = conn.getresponse()
print response.status, response.reason

data = response.read()
conn.close()

这个脚本是否足以作为测试POSTing 的一种方式?我在 SO 上看到了很多关于人们寻找 GUI 工具来执行此操作的请求(Firefox 插件,etc) 但对我来说,首先构建一个 RESTful 应用程序的重点是拥有一个 API,我可以编写脚本来快速修改数据库。 (用数据填充它 来自 JSON 文件,无论如何。)

使用这种基于 Python 的方法,我是否走在正确的轨道上?

谢谢

【问题讨论】:

    标签: python api http


    【解决方案1】:

    直接写信给httplib 没问题,但是级别比较低。

    查看Requests 模块。这是一种非常简单的 Pythonic 方法来制作和发送 http 请求。

    import requests
    
    requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None)
    

    【讨论】:

      【解决方案2】:

      POST 通常通过更高级别的函数 urllib2 完成。

      headers = {'User-Agent': user_agent}
      
      data = urllib.urlencode(values)
      req = urllib2.Request(url, data, headers)
      response = urllib2.urlopen(req)
      

      【讨论】:

        【解决方案3】:

        还有Nap,它只是请求的包装器,但便于调用,例如HTTP API。

        示例用法:

        from nap.url import Url
        api = Url('http://httpbin.org/')
        
        response = api.post('post', data={'test': 'Test POST'})
        print(response.json())
        

        更多示例:https://github.com/kimmobrunfeldt/nap#examples

        免责声明:我写了小睡。

        【讨论】:

          猜你喜欢
          • 2015-07-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-30
          • 2016-08-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多