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

 

posted @   念槐聚  阅读(895)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示