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://files.cnblogs.com/files/haochuang/alipay-RedEnvelopes.bmp)
赠人玫瑰
手留余香
我们曾如此渴望命运的波澜,到最后才发现:人生最曼妙的风景,竟是内心的淡定与从容……我们曾如此期盼外界的认可,到最后才知道:世界是自己的,与他人毫无关系!-杨绛先生
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的