GET RESTful With Python

Python调用RESTful:http://blog.akiban.com/get-restful-with-python/

本文就是参考该英文做了一下试验,后续补充一下翻译。

This post will take a look at our REST API by creating a Python script to interact with the entity endpoint.

One of the key benefits of using standard technologies, formats, and protocols is the incredible amount of existing tooling that you get for free. Since we’ve been busy building our new service, backed by our ever changing database, we haven’t gotten around to client libraries yet.

However, we do speak JSON through REST over HTTPS. Every language already has battle hardened libraries for working with those. For Python, it doesn’t get much better than the requests library. Their motto is HTTP for Humans and it makes working with RESTful services a breeze.

 
需求:

As in Schemaless SQL, we’ll be using a DataSpace with a single entity named hopes.

On the service side, just copy and deploy the hopes DataSpace and make note of the credentials.

On the client side, we just need to install the requests library.
$ pip install requests

 
Hello, World

We’ll be using an external JSON configuration file, named config.json, for simplicity. Create the JSON files as below with real values from the Deployments page.

{
  "host": "host",
  "port": "port",
  "user": "user",
  "pass": "pass"
}



The simplest endpoint exposed by the Akiban Server is version. It has no dependencies and will always work if valid credentials are supplied.

We’ll start our script, named akiban_rest.py, with the code below to load our configuration and execute a version request.

复制代码
import json
import requests
 
config = {}
with open('config.json') as cfg:
  config = json.load(cfg)
 
resp = requests.get(
  'https://%s:%s/v1/version' % (config['host'], config['port']),
  auth = (config['user'], config['pass'])
)
 
print resp.text
复制代码


Running that will give output like below, though the specific server_version may vary.
$ python akiban_rest.py

[{"server_name":"Akiban Server","server_version":"1.6.1-SNAPSHOT.2606"}]
Congrats! You're now talking to the Akiban REST API. We'll be wrapping the rest of the Entity Resources to provide convenient access from the command line.

 
Helpers

A few helpers are in order. One for building the URI string, one for pretty-printing our JSON response, and a variable for holding the configured credentials.

复制代码
def url(endpoint):
  return 'https://%s:%s/v1%s' % (config['host'], config['port'], endpoint)
 
def dump(response):
  print json.dumps(json.loads(response.text), indent=2)
 
AUTH = (config['user'], config['pass'])
复制代码

 
Commands and Arguments

The overall script architecture will be quite simple. A single function per endpoint we're exposing, a map to name it, and very simple command line argument handling.

Note that a real library would want a number of things that have been omitted for brevity, such as argument checking and specific error messages.

复制代码
def version():
  return requests.get(url('/version'), auth=AUTH)
 
commands = {
  'version': version
}
 
cmd_name = sys.argv[1]
cmd_args = sys.argv[2:]
cmd = commands.get(cmd_name)
resp = cmd(*cmd_args)
dump(resp)

We can now run the version command.
$ python akiban_rest.py version
[
  {
    "server_version": "1.6.1-SNAPSHOT.2606",
    "server_name": "Akiban Server"
  }
]
复制代码

 
GET and POST

Now we can begin interacting with our hopes entity. New methods for retrieving all, or specific, instances with GET and creating a new instance with POST.

复制代码
def entity_get_all(entity):
  return requests.get(url('/entity/%s' % entity), auth=AUTH)
 
def entity_get(entity, ids):
  return requests.get(url('/entity/%s/%s' % (entity, ids)), auth=AUTH)
 
def entity_post(entity, json):
  return requests.post(url('/entity/%s' % entity), data=json, auth=AUTH)
 
commands = {
  'version': version,
  'all': entity_get_all,
  'get': entity_get,
  'create': entity_post
}
复制代码


The create, get, and get_all commands now function.

复制代码
$ python akiban_rest.py create hopes '{"desc": "Part IV: A New Hope", "date": "2013-04-04 16:58:30", "bumpcount": 0}'
{
  "id": 1
}
$ python akiban_rest.py create hopes '{"desc": "Another", "date": "2013-04-04 16:58:35", "bumpcount": 0}'
{
  "id": 2
}
$ python akiban_rest.py get hopes 1
[
  {
    "date": "2013-04-04 16:58:30",
    "bumpcount": 0,
    "id": 1,
    "desc": "Part IV: A New Hope"
  }
]
$ python akiban_rest.py all hopes
[
  {
    "date": "2013-04-04 16:58:30",
    "bumpcount": 0,
    "id": 1,
    "desc": "Part IV: A New Hope"
  },
  {
    "date": "2013-04-04 16:58:35",
    "bumpcount": 0,
    "id": 2,
    "desc": "Another"
  }
]
复制代码


 
PUT and DELETE

We can now finish out the entity endpoint by adding commands for replacing and deleting. Note that the dump has been tweaked to handle no_content responses, like delete.

复制代码
def dump(response):
  if response.status_code != requests.codes.no_content:
    print json.dumps(json.loads(response.text), indent=2)
 
def entity_put(entity, ids, json):
  return requests.put(url('/entity/%s/%s' % (entity, ids)), data=json, auth=AUTH)
 
def entity_delete(entity, ids):
  return requests.delete(url('/entity/%s/%s' % (entity, ids)), auth=AUTH)
 
commands = {
  'version': version,
  'all': entity_get_all,
  'get': entity_get,
  'create': entity_post,
  'replace': entity_put,
  'delete': entity_delete
}
复制代码

 



And to demonstrate.

复制代码
$ python akiban_rest.py replace hopes 2 '{"id": 2, "desc": "A better name", "date": "2013-04-04 16:58:35", "bumpcount": 100}'
{
  "id": 2
}
$ python akiban_rest.py delete hopes 1
$ python akiban_rest.py all hopes
[
  {
    "date": "2013-04-04 16:58:35",
    "bumpcount": 100,
    "id": 2,
    "desc": "A better name"
  }
]
复制代码


 
Summary

We started out with an empty DataSpace and a blank akiban_rest.py file. After loading our example hope and deploying it, we could start to interact with it through a simple REST call. Fifty lines of Python later and we now have a respectable command line script for viewing, creating, updating, and deleting our entities.

All of the code from this post is available in this Gist. Who knows, this might just grow into our Python client library!

android调用RESTful:http://bbs.it-home.org/thread-10447-1-1.html

 

转载请注明出处:http://www.cnblogs.com/haochuang/ 8年IT工作经验,5年测试技术与管理,2年产品与项目管理,曾参与过云计算\云存储\车联网产品研发工作; 业余自媒体人,有技术类垂直微信公众号;如有招聘或求职方面需求,请Mail to uetest@qq.com ;或通过 QQ:363573922 微博:@念槐聚 联系;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值