用Python中的POSTs测试RESTful API

2024-04-27 03:22:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

GET似乎工作正常,但我在使用POST时遇到了问题。我不是问这个库的输入和输出,而是在尝试 找出如何使用Python测试POST。这就是我得到的:

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()

这个脚本足以作为测试POST的方法吗?我已经看到了很多关于寻找GUI工具来实现这一点的请求(Firefox插件,etc) 但对我来说,首先构建RESTful应用程序的关键是要有一个API,我可以编写脚本来快速修改db。(用数据填充 从一个JSON文件,随便什么。)

我使用这种基于Python的方法是否正确?

谢谢


Tags: 方法import脚本restfulgetresponseparamsurllib
3条回答

直接向httplib写入是可以的,但级别很低。

查看Requests模块。这是一种非常简单的python方法,用于创建和发送http请求。

import requests

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

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

headers = {'User-Agent': user_agent}

data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)

还有一个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

免责声明:我写了午睡。

相关问题 更多 >