博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Flask-RESTful构建小型REST服务
阅读量:7035 次
发布时间:2019-06-28

本文共 3193 字,大约阅读时间需要 10 分钟。

hot3.png

Flask-RESTful构建小型REST服务

by  ·

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这个应用来测试:

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

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 –

###参考:

转载于:https://my.oschina.net/u/2306127/blog/662294

你可能感兴趣的文章
Maven学习总结(三)——使用Maven构建项目
查看>>
Tomcat在Linux上的安装与配置
查看>>
CentOS 6和CentOS 7命令区别
查看>>
OUTLOOK2007 即时搜索失效解决经过
查看>>
SVN学习总结(2)——SVN冲突解决
查看>>
Maven学习总结(四)——Maven核心概念
查看>>
安装xtables-addons时报错
查看>>
.NET开发规范教程
查看>>
网络公开课《最后的升级-Oracle RAC数据库升级》
查看>>
配置FTP服务
查看>>
我的友情链接
查看>>
人类认识的层次模型
查看>>
WDS使用捕获映像制作企业自定义映像
查看>>
C++数组、指针与vector、iterator
查看>>
SSL及其开源实现OpenSSL+创建私有CA
查看>>
jquery实现表单form异步提交
查看>>
Citrix xendesktop中未注册(Not registered)的检查流程
查看>>
一张图让你看懂JAVA线程间的状态转换
查看>>
Performance comparison Raw device VS Ext2 VS Ext3 VS OCFS
查看>>
ISBN号码(CCF考题)
查看>>