一、安装PyRestful库
 $ pip install pyrestful
 二、使用案例

(一)books_service.py

# -*- coding: utf-8 -*-

import tornado.ioloop
import pyrestful.rest from pyrestful import mediatypes
from pyrestful.rest import get, post, put, delete class Book(object):
isbn = int
title = str class BookResource(pyrestful.rest.RestHandler):
@get(_path="/books/json/{isbn}", _types=[int], _produces=mediatypes.APPLICATION_JSON)
def getBookJSON(self, isbn):
book = Book()
book.isbn = isbn
book.title = "My book for isbn "+str(isbn) return book @get(_path="/books/xml/{isbn}", _types=[int], _produces=mediatypes.APPLICATION_XML)
def getBookXML(self, isbn):
book = Book()
book.isbn = isbn
book.title = "My book for isbn "+str(isbn) return book @post(_path="/books/xml",_types=[Book],_consumes=mediatypes.APPLICATION_XML, _produces=mediatypes.APPLICATION_XML)
def postBookXML(self, book):
""" this is an echo...returns the same xml document """
return book @post(_path="/books/json",_types=[Book],_consumes=mediatypes.APPLICATION_JSON, _produces=mediatypes.APPLICATION_JSON)
def postBookJSON(self, book):
""" this is an echo...returns the same json document """
return book @post(_path="/books",_types=[Book])
def postBook(self, book):
""" this is an echo, returns json or xml depending of request content-type """
return book if __name__ == '__main__':
try:
print("Start the service")
app = pyrestful.rest.RestService([BookResource])
app.listen(8080)
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
print("\nStop the service")

(二)create_customer.py

# -*- coding: utf-8 -*-

import json
import sys if sys.version_info > (3,):
raw_input = input
import http.client as httplib
import urllib.parse as urllib
else:
import httplib
import urllib print('Create customer')
print('===============')
name_customer = raw_input('Customer Name : ')
address_customer = raw_input('Customer Address : ') if len(name_customer) == 0 and len(address_customer) == 0:
print('You must indicates name and address of customer')
else:
params = urllib.urlencode({'name_customer':name_customer,'address_customer':address_customer})
headers = {"Content-Type": "application/x-www-form-urlencoded"}
conn = httplib.HTTPConnection("localhost:8080") conn.request('POST','/customer',params,headers) resp = conn.getresponse()
data = resp.read()
if resp.status == 200:
json_data = json.loads(data.decode('utf-8'))
print(json_data)
else:
print(data)

(三)customer_service.py

# -*- coding: utf-8 -*-

import tornado.ioloop
import pyrestful.rest from pyrestful import mediatypes
from pyrestful.rest import get, post, put, delete class Customer(object):
id_customer = int
name_customer = str
address_customer = str
def __init__(self,id_customer=0, name_customer=None, address_customer=None):
self.id_customer = id_customer
self.name_customer = name_customer
self.address_customer = address_customer
# Setters
def setId_Customer(self,id_customer):
self.id_customer = id_customer
def setName_Customer(self,name_customer):
self.name_customer = name_customer
def setAddress_Customer(self,address_customer):
self.address_customer = address_customer
# Getters
def getId_Customer(self):
return self.id_customer
def getName_Customer(self):
return self.name_customer
def getAddress_Customer(self):
return self.address_customer class CustomerDataBase(object):
customerDB = dict()
id_seq = 1 def insert(self, name_customer, address_customer):
sequence = self.id_seq
customer = Customer(sequence, str(name_customer), str(address_customer))
self.customerDB[sequence] = customer
self.id_seq += 1 return sequence def update(self,id_customer, name_customer, address_customer):
if self.exists(id_customer):
customer = self.customerDB[id_customer]
customer.setName_Customer(str(name_customer))
customer.setAddress_Customer(str(address_customer))
self.customerDB[id_customer] = customer
return True
else:
return False def delete(self,id_customer):
if self.exists(id_customer):
del self.customerDB[id_customer]
return True
else:
return False def find(self,id_customer):
if self.exists(id_customer):
return self.customerDB[id_customer]
else:
return None def exists(self,id_customer):
if id_customer in self.customerDB:
return True
else:
return False def all(self):
return self.customerDB class CustomerResource(pyrestful.rest.RestHandler):
def initialize(self, database):
self.database = database @get(_path="/customer", _produces=mediatypes.APPLICATION_JSON)
def getListCustomer(self):
customers = self.database.all() response = dict()
for k in customers.keys():
cust = dict()
cust['id_customer'] = customers[k].getId_Customer()
cust['name_customer'] = customers[k].getName_Customer()
cust['address_customer'] = customers[k].getAddress_Customer()
response[k] = { k : cust } return response @get(_path="/customer/{id_customer}", _types=[int], _produces=mediatypes.APPLICATION_JSON)
def getCustomer(self, id_customer):
if not self.database.exists(id_customer):
self.gen_http_error(404,"Error 404 : do not exists the customer : %d"%id_customer)
return customer = self.database.find(id_customer) response = dict()
response['id_customer'] = customer.getId_Customer()
response['name_customer'] = customer.getName_Customer()
response['address_customer'] = customer.getAddress_Customer()
print(response)
return response @post(_path="/customer", _types=[str,str], _produces=mediatypes.APPLICATION_JSON)
def createCustomer(self, name_customer, address_customer):
id_customer = self.database.insert(name_customer, address_customer) return {"created_customer_id": id_customer} @put(_path="/customer/{id_customer}", _types=[int,str,str], _produces=mediatypes.APPLICATION_JSON)
def updateCustomer(self, id_customer, name_customer, address_customer):
if not self.database.exists(id_customer):
self.gen_http_error(404,"Error 404 : do not exists the customer : %d"%id_customer)
return updated = self.database.update(id_customer,name_customer,address_customer) return {"updated_customer_id": id_customer, "success":updated} @delete(_path="/customer/{id_customer}", _types=[int], _produces=mediatypes.APPLICATION_JSON)
def deleteCustomer(self,id_customer):
if not self.database.exists(id_customer):
self.gen_http_error(404,"Error 404 : do not exists the customer : %d"%id_customer)
return deleted = self.database.delete(id_customer) return {"delete_customer_id": id_customer, "success":deleted} if __name__ == '__main__':
try:
print("Start the service")
database = CustomerDataBase()
app = pyrestful.rest.RestService([CustomerResource], dict(database=database))
app.listen(8080)
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
print("\nStop the service")

(四)delete_customer.py

# -*- coding: utf-8 -*-

import json
import sys if sys.version_info > (3,):
raw_input = input
import http.client as httplib
import urllib.parse as urllib
else:
import httplib
import urllib print('Delete customer')
print('===============')
id_customer = raw_input('Id Customer : ') if len(id_customer) == 0:
print('You must indicates id of customer')
else:
conn = httplib.HTTPConnection("localhost:8080") conn.request('DELETE','/customer/%s'%id_customer) resp = conn.getresponse()
data = resp.read()
if resp.status == 200:
json_data = json.loads(data.decode('utf-8'))
print(json_data)
else:
print(data.decode('utf-8'))

(五)echo_service.py

import tornado.ioloop
import pyrestful.rest from pyrestful import mediatypes
from pyrestful.rest import get class EchoService(pyrestful.rest.RestHandler):
@get(_path="/echo/{name}", _produces=mediatypes.APPLICATION_JSON)
def sayHello(self, name):
return {"Hello":name} if __name__ == '__main__':
try:
print("Start the echo service")
app = pyrestful.rest.RestService([EchoService])
app.listen(8080)
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
print("\nStop the echo service")

(六)update_customer.py

# -*- coding: utf-8 -*-

import sys
import json if sys.version_info > (3,):
raw_input = input
import http.client as httplib
import urllib.parse as urllib
else:
import httplib
import urllib print('Update customer')
print('===============')
id_customer = raw_input('Id Customer : ')
name_customer = raw_input('Customer Name : ')
address_customer = raw_input('Customer Address : ') if len(id_customer) == 0 and len(name_customer) == 0 and len(address_customer) == 0:
print('You must indicates id, name and address of customer')
else:
params = urllib.urlencode({'name_customer':str(name_customer),'address_customer':str(address_customer)})
headers = {"Content-type": "application/x-www-form-urlencoded"}
conn = httplib.HTTPConnection("localhost:8080") conn.request('PUT','/customer/%s'%id_customer,params,headers) resp = conn.getresponse()
data = resp.read()
if resp.status == 200:
json_data = json.loads(data.decode('utf-8'))
print(json_data)
else:
print(data.decode('utf-8'))

用PyRestful快速构建Tornado下REST APIs 的支持的更多相关文章

  1. 使用 Vagrant + VirtualBox 快速构建 CentOS 下的 Docker 环境

    Vagrant - 基础概念: Vagrant 是什么? Vagrant是一款用于在单个工作流程中构建和管理虚拟机环境的工具.凭借易于使用的工作流程和专注于自动化,Vagrant降低了开发环境设置时间 ...

  2. Hexo快速构建个人小站-Fulid主题下添加Valine评论系统(三)

    Hexo目录: Hexo快速构建个人小站-Hexo初始化和将项目托管在Github(一) Hexo快速构建个人小站-自定义域名和自定义主题(二) 背景交代: 前面两章完成了Hexo的初始化和部分自定义 ...

  3. 快速构建springmvc+spring+swagger2环境

    快速构建springmvc+spring+swagger2环境 开发工具:Intellij idea               jdk: 1.8 开发步骤: 1.创建maven工程,如图建立工程结构 ...

  4. 玩转Windows服务系列——使用Boost.Application快速构建Windows服务

    玩转Windows服务系列——创建Windows服务一文中,介绍了如何快速使用VS构建一个Windows服务.Debug.Release版本的注册和卸载,及其原理和服务运行.停止流程浅析分别介绍了Wi ...

  5. 使用 Spring Boot 快速构建 Spring 框架应用--转

    原文地址:https://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/ Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2 ...

  6. Apache Commons CLI官方文档翻译 —— 快速构建命令行启动模式

    昨天通过几个小程序以及Hangout源码学习了CLI的基本使用,今天就来尝试翻译一下CLI的官方使用手册. 下面将会通过几个部分简单的介绍CLI在应用中的使用场景. 昨天已经联系过几个基本的命令行参数 ...

  7. C# Winform 通过FlowLayoutPanel及自定义的编辑控件,实现快速构建C/S版的编辑表单页面

    个人理解,开发应用程序的目的,不论是B/S或是C/S结构类型,无非就是实现可供用户进行查.增.改.删,其中查询用到最多,开发设计的场景也最为复杂,包括但不限于:表格记录查询.报表查询.导出文件查询等等 ...

  8. Java Swing快速构建窗体应用程序

    以前接触java感觉其在桌面开发上,总是不太方便,没有一个好的拖拽界面布局工具,可以快速构建窗体. 最近学习了一下NetBeans IDE 8.1,感觉其窗体设计工具还是很不错的 , 就尝试一下做了一 ...

  9. 【Android】如何快速构建Android Demo

    [Android]如何快速构建Android Demo 简介 在 Android 学习的过程中,经常需要针对某些项目来写一些测试的例子,或者在做一些 demo 的时候,都需要先写 Activity 然 ...

随机推荐

  1. The Suspects(并查集求节点数)

    The Suspects Time Limit: 1000MS   Memory Limit: 20000K Total Submissions: 28164   Accepted: 13718 De ...

  2. 魔兽世界---屠夫(Just a Hook)

    Just a Hook Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Tota ...

  3. 关于java同步包中ConcurrentLinkedQueue类的深入分析与理解

    一,官方描写叙述 一个基于连接节点的无界线程安全队列.这个队列的顺序是先进先出.队列头部的元素是留在队列中时间最长的,队列尾部的元素是留在队列中时间最短的.新元素被插入到元素的尾部,队列从队列的头部检 ...

  4. 机器学习Matlab打击垃圾邮件的分类————朴素贝叶斯模型

    该系列来自于我<人工智能>课程回顾总结,以及实验的一部分进行了总结学习机 垃圾分类是有监督的学习分类最经典的案例,本文首先回顾了概率论的基本知识.则以及朴素贝叶斯模型的思想.最后给出了垃圾 ...

  5. 跟我一起学写jQuery插件开发方法(转载)

    jQuery如此流行,各式各样的jQuery插件也是满天飞.你有没有想过把自己的一些常用的JS功能也写成jQuery插件呢?如果你的答案是肯定的,那么来吧!和我一起学写jQuery插件吧!     很 ...

  6. WCF编写时候的测试

    1右击WCF创建到使用到发布这篇文章中的类库项目中的接口类实现文件添加断点 2右击WCF创建到使用到发布这篇文章中的WCF服务网站设为启动项并允许 3右击WCF创建到使用到发布这篇文章中的WPF项目调 ...

  7. Mysql 如何做双机热备和负载均衡 (方法二)

    先简要介绍一下mysql双向热备:mysql从3.23.15版本以后提供数据库复制功能.利用该功能可以实现两个数据库同步,主从模式(A->B),互相备份模式(A<=>B)的功能. m ...

  8. 【Android】Handler的应用(一):从服务器端加载JSON数据

    最终目的 以JSON的形式,将数据存入服务器端. 在Android中,以Handler加载显示大批量文字. 在此以加载金庸小说<天龙八部(新修版)>为例(2580480 字节). 以tom ...

  9. Easyui + jQuery表单提交 给 Controller patr1

    2014-11-15  总结上周在公司开发所用到的技术,由于是刚找的工作(一个大三实习生)+自己的技术菜,有很多地方都是怎么想就怎么实现的, 如果你有什么更好的解决方法,在看见这篇博客的时候,希望你能 ...

  10. bzoj 3289: Mato的文件管理 莫队+线段树

    题目链接 给一些询问,每个询问给出区间[L, R] , 求这段区间的逆序数. 先分块排序, 然后对于每次更改, 如果是更改L, 那么应该查询区间内比他小的数的个数, 如果更改R, 查区间内比他大的数的 ...