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

GET RESTful With Python的更多相关文章

  1. openstack命令行

    openstack的每一个子项目(project)都有自己对应的命令行API,所有的这些API都是基于RESTful的,python代码实现的API.也就是说,这些API都是基于HTTP实现的,所以A ...

  2. 使用Empire自动获取域管理员

    使用Empire自动获取域管理员  译:backlion 前言 自从Empire和BloodHound被应用来,对AD渗透已经可以获取到内网环境95%的信息量.作者发现自己一遍又一遍地在做同样重复的事 ...

  3. TDengine概述以及架构模型

    TDengine TDengine是一个高效的存储.查询.分析时序大数据的平台,专为物联网.车联网.工业互联网.运维监测等优化而设计. 您可以像使用关系型数据库MySQL一样来使用它. TDengin ...

  4. 使用python的Flask实现一个RESTful API服务器端[翻译]

    最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文将会使用python的Flask框架轻松实现一个RESTful的服务 ...

  5. Python flask 基于 Flask 提供 RESTful Web 服务

    转载自 http://python.jobbole.com/87118/ 什么是 REST REST 全称是 Representational State Transfer,翻译成中文是『表现层状态转 ...

  6. python Eve RESTFul 尝试笔记

    0.前言 最近重点研究了yeelink平台的原理和使用,yeelink平台和多数云平台设计一样应用了RESTFul框架.嵌入式侧(或者是客服端侧)的相关技术研究的比较充分(个人这么认为),是不是该弄弄 ...

  7. 使用python的Flask实现一个RESTful API服务器端

    使用python的Flask实现一个RESTful API服务器端 最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文 ...

  8. 让python bottle框架支持jquery ajax的RESTful风格的PUT和DELETE等请求

    这两天在用python的bottle框架开发后台管理系统,接口约定使用RESTful风格请求,前端使用jquery ajax与接口进行交互,使用POST与GET请求时都正常,而Request Meth ...

  9. 使用 Python & Flask 实现 RESTful Web API

    环境安装: sudo pip install flask Flask 是一个Python的微服务的框架,基于Werkzeug, 一个 WSGI 类库. Flask 优点: Written in Pyt ...

随机推荐

  1. POJ1733 Party game [带权并查集or扩展域并查集]

    题目传送 Parity game Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 10870   Accepted: 4182 ...

  2. 洛谷P1196 [NOI2002] 银河英雄传说

    #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #includ ...

  3. 洛谷——P1958 上学路线_NOI导刊2009普及(6)

    P1958 上学路线_NOI导刊2009普及(6) 题目描述 你所在城市的街道好像一个棋盘,有a条南北方向的街道和b条东西方向的街道.南北方向的a条街道从西到东依次编号为l到a,而东西方向的b条街道从 ...

  4. MYSQL注入天书之基础知识

    第一部分/page-1 Basic Challenges Background-1 基础知识 此处介绍一些mysql注入的一些基础知识. (1)注入的分类---仁者见仁,智者见智. 下面这个是阿德玛表 ...

  5. JSON APIs and Ajax

    1. 通过jQuery来绑定点击事件. 函数 $(document).ready()这个函数中的代码只会在我们的页面加载时候运行一次,确保执行js之前页面所有的dom已经准备就绪. 在$(docume ...

  6. Xamarin Android真机测试报错

    Xamarin Android真机测试报错   Xamarin Android真机测试报错,错误信息为INSTALL_CANCELLED_BY_USER.出现这个错误,通常都是真机上开发者选项设置错误 ...

  7. Spring和依赖注入的价值

    javaeye上看到有帖子,置疑spring和依赖注入的价值,回复内容整理如下: 依赖注入对设计有利,而spring则促进了依赖注入的使用. 如果业务处理类,它所使用的倚赖,都是依靠在这个类内部实现或 ...

  8. 【后缀自动机】CDOJ1551 Hesty Str1ng

    可以发现,对于原串的每个长度>1的子串而言,将其除了最后一个字符之外反向接在其结尾,都是一个合法解.该解的长度一定是奇数. 对于原串的每个长度>2,且结尾两个字符相同的子串而言,将其除了最 ...

  9. foreach循环时动态往数组里添加数据

    今天在用TP做项目的时候遇到一个问题,foreach的时候需要动态往数组里添加数据,示例代码如下: $arr = array( array('id'=>'字符串1','name'=>'字符 ...

  10. sql server的sql 语句中的列名包含[]时候,把]替换成]]就可以

    sql server的sql 语句中的列名包含[]时候,把]替换成]]就可以eg: create table p.e_LOG_WebServer ( [BSCFlg] int, ), ) ); sel ...