Flask-RESTful构建小型REST服务

Flask-RESTful构建小型REST服务

2015年6月18日 by debugo  · Leave a comment

REST是web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了。诸如docker daemon等服务都是提供了RESTful API,docker的CLI可以通过该API的URL地址与之通信。
Flask是一个超级流行的Python 编写的轻量级 Web 应用框架。而Flask有一个REST插件——Flask-RESTful是为了快速构建REST API的Flask插件,它能和现有的ORM配合实现轻量级数据抽象。Flask-RESTful鼓励小型化实践,非常简单易学。本文将会使用 python的Flask框架轻松实现一个RESTful的服务。
REST的六个特性:

  • Client-Server:服务器端与客户端分离。

  • Stateless:每次客户端请求必需包含完整的信息,换句话说,每一次请求都是独立的。

  • Cacheable(可缓存):服务器端必需指定哪些请求是可以缓存的。

  • Layered System(分层结构):服务器端与客户端通讯必需标准化,服务器的变更并不会影响客户端。

  • Uniform Interface(统一接口):客户端与服务器端的通讯方法必需是统一的。

  • Code on demand(按需执行代码):服务器端可以在上下文中执行代码

万事从Hello world起,
安装Flask-RESTful:

pip install FLASK-RESTful
#-*- coding: utf-8 -*- from flask 
import Flask from flask.ext 
import restful 
app = Flask(__name__) 
api = restful.Api(app) 

class HelloWorld(restful.Resource):
 def get(self): 
     return {'hello': 'world'} 

     api.add_resource(HelloWorld, '/') 

if __name__ == '__main__': 
    app.run(debug=True)

相比普通的http服务,区别在于:
1. import了RESTful的模块,并使用了restful Api。
2. REST资源类Hello world必须继承自restful.Resource,并实现/重写父类的一些方法(比如get)
3. 将Hello world添加到Restful api资源里,并没有使用装饰器。
下面是一个更复杂的实现,实现一个item列表的更新。HTTP中有相应的请求方法可以用于描述操作资源的动作:

HTTP方法 动作 例子 功能
GET 获取资源信息 http://example.com/api/orders 检索订单清单
GET 获取资源信息 http://example.com/api/orders/123 检索订单123
POST 创建一个次的资源 http://example.com/api/orders 使用带数据的请求,创建一个新的订单
PUT 更新一个资源 http://example.com/api/orders/123 (使用带数据的请求,更新123订单)
DELETE 删除一个资源 http://example.com/api/orders/123 删除订单123

下面我们设计一个复杂的REST API:

#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask from flask.ext.restful import reqparse, Api, Resource, fields, marshal_with from pymongo import MongoClient mongo_url = 'your-ip' db_name = 'your-db' col_name = 'your-col' client = MongoClient(mongo_url) col = client[db_name][col_name] col.remove({}) col.insert({'_id': 1, "name": "debugo", "values": [70, 65]}) col.insert({'_id': 2, "name": "leo", "values": [65]}) app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() parser.add_argument('name', type=str, required=True) parser.add_argument('values', type=int, help='rate is a number', action='append') class UserInfo(Resource):    def get(self):        return [str(i) for i in col.find({})]    def post(self):        args = parser.parse_args()        user_id = col.count() + 1        col.insert({'_id': user_id, "name": args["name"], "values": args["values"]})        return [str(i) for i in col.find({'_id': user_id})], 201 api.add_resource(UserInfo, '/') if __name__ == '__main__':    app.run(debug=True)

其中我们定义了一个参数

新建一个请求解析器RequestParser,规定类型为type,否则会拒绝并提示help的信息:

param type: The type to which the request argument should be
     converted. If a type raises an exception, the message in the
     error will be returned in the response. Defaults to :class:unicode
     in python2 and :class:str in python3.
 param help: A brief description of the argument, returned in the
     response when the argument is invalid with the name of the argument and
     the message passed to any exception raised by a type converter.

在Chrome中使用Advanced REST Client这个应用来测试:

Flask-RESTful构建小型REST服务_第1张图片
Flask-RESTful构建小型REST服务_第2张图片

程序中成功输出下面请求结果:

127.0.0.1 – – [18/Jun/2015 18:09:23] “POST / HTTP/1.1″ 201 –
    127.0.0.1 – – [18/Jun/2015 18:09:29] “GET / HTTP/1.1″ 200 –

###参考:
Flask-RESTful Document
使用python的Flask实现一个RESTful API服务器端
极客学院 Flask-RESTful 插件介绍及应用


你可能感兴趣的:(python,REST,flask)