Flask  Restful

1.flask restful

  在flask基础上进行一些封装,主要用于实现restful接口

2.restful的理解

1)URI(统一资源标识符):每一个URI代表一种资源,restful接口对资源进行增删改查

2) 客户端和服务器之间,传递这种资源的某种表现层

3)客户端通过四个HTTP动词(get、post、put、delete),对服务器资源进行操作,实现“表现层状态转化”

3.Flask Restful安装

1)先安装flask:

  pip install flask

  2)再安装flask restful:

    pip install flask-restful

4.HelloWorld

__author__ = 'zhizhi'
from flask import Flask
from flask_restful import Api,Resource#老版本flask中使用的是flask.ext中的Api,目前已经被flask_restful中的Api替代
app=Flask(__name__)
api=Api(app) class HelloWorld(Resource):
def get(self):
return {"hello":"world"} api.add_resource(HelloWorld,'/') if __name__=='__main__':
app.run(debug=True)

结果:

5.flask restful API官网示例

from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource app = Flask(__name__)
api = Api(app) TODOS = {
'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'},
} def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id)) parser = reqparse.RequestParser()
parser.add_argument('task', type=str) # Todo
# show a single todo item and lets you delete them
class Todo(Resource):
def get(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
return TODOS[todo_id] def delete(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
del TODOS[todo_id]
return '', 204 def put(self, todo_id):
args = parser.parse_args()
task = {'task': args['task']}
TODOS[todo_id] = task
return task, 201 # TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
def get(self):
return TODOS def post(self):
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201 ##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>') if __name__ == '__main__':
app.run(debug=True)

6.官网示例的代码解析

(1)引入需要的库名、函数、变量等,并做简单的Application初始化:

from flask import Flask
from flask_restful import reqparse, abort, Api, Resource app = Flask(__name__)
api = Api(app)

(2)定义我们需要操作的资源类型(都是json格式的):

TODOS = {
'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'},
}

(3)如果id不存在,则停止运行

def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id))

(4)Flask-RESTful提供了一个用于参数解析的RequestParser类,类似于Python中自带的argparse类,可以很方便的解析请求中的-d参数,并进行类型转换。

parser = reqparse.RequestParser()
parser.add_argument('task')

(5)API分为两类:带参数id的,和不带有参数id的。前者是操作单一资源,后者是操作资源列表或新建一个资源。

从操作单一资源开始,继承Resource类,并添加put / get / delete方法:

class Todo(Resource):
def get(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
return TODOS[todo_id] def delete(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
del TODOS[todo_id]
return '', 204 def put(self, todo_id):
args = parser.parse_args()
task = {'task': args['task']}
TODOS[todo_id] = task
return task, 201

(6)继续操作资源列表,继承Resource类,并添加get / post方法:

class TodoList(Resource):
def get(self):
return TODOS def post(self):
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201

(7)资源操作类定义完毕之后,需要设置路由,即告诉Python程序URL的对应关系。

api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')

Python Flask Restful的更多相关文章

  1. python Flask restful框架

    框架地址:https://github.com/flask-restful/flask-restful 文档:http://flask-restful.readthedocs.io/en/0.3.5/ ...

  2. [转]python实现RESTful服务(基于flask)

    python实现RESTful服务(基于flask) 原文: https://www.jianshu.com/p/6ac1cab17929  前言 上一篇文章讲到如何用java实现RESTful服务, ...

  3. Python Flask高级编程之RESTFul API前后端分离精讲 (网盘免费分享)

    Python Flask高级编程之RESTFul API前后端分离精讲 (免费分享)  点击链接或搜索QQ号直接加群获取其它资料: 链接:https://pan.baidu.com/s/12eKrJK ...

  4. Python flask 构建可扩展的restful apl☝☝☝

    Python flask 构建可扩展的restful apl☝☝☝ Flask-RESTful是flask的扩展,增加了对快速构建REST API的支持.Flask-RESTful通过最少的设置鼓励最 ...

  5. Python flask 构建可扩展的restful apl✍✍✍

    Python flask 构建可扩展的restful apl  整个课程都看完了,这个课程的分享可以往下看,下面有链接,之前做java开发也做了一些年头,也分享下自己看这个视频的感受,单论单个知识点课 ...

  6. python实现Restful服务(基于flask)(2)

    参考:https://blog.csdn.net/yelena_11/article/details/53404892 最简单的post例子: from flask import Flask, req ...

  7. python 部署 Restful web

    使用python web做Restful 风格,很简单,采用Flask框架轻松实现一个RESTful的服务. Restful相关介绍请查看:https://www.ibm.com/developerw ...

  8. Flask RESTful API搭建笔记

    之前半年时间,来到项目的时候,已经有一些东西,大致就是IIS+MYSQL+PHP. 所以接着做,修修补补,Android/iOS与服务器数据库交换用PHP, Web那边则是JS+PHP,也没有前后端之 ...

  9. Python Flask Web 框架入门

    Python Flask 目录 本文主要借鉴 letiantian 的文章 http://www.letiantian.me/learn-flask/ 一.简介 二.安装 三.初始化Flask 四.获 ...

随机推荐

  1. 25)django-form使用

    目录 1)django form作用 2)django form使用 一:django form 作用 django form有两个作用:一是用户输入数据验证:二是生成html 1)用户输入数据验证, ...

  2. Java的家庭记账本程序(I)

    日期:2019.2.26 博客期:037 星期二 Part 1: 今天使用新的"radio"标签,将搜索方式的选则内容更改了,如下图,不过,研究了很久的数据库连接也还是没有成功!嗯 ...

  3. linux SWAP

    1.内存和SWAP之间合理的分配方案 M = Amount of RAM in GB, and S = Amount of swap in GB, then If M < 2, S = M *2 ...

  4. NIagara Workbench ( 温度控制)

    1.在原来BoilerControl的基础上建立一个 2.检查通过标签构造的报告的时候,在键盘上按下Control键并一直保持的同时按下L键 将会弹窗一个ORD窗口代表定义的参数.同时按下Contro ...

  5. ubuntu的磁盘扩容

    前言:以前项目的人给ubuntu虚拟机分配磁盘空间走的默认,导致后期/根和swap空间跟不上需求,需要扩容 流程如下: 1.先添加块硬盘,命令行输入fdisk -l,会发现多了个/dev/sdb(vd ...

  6. String hashcode的兴趣试玩

    今天突然看到Hashcode和equals,==比较时,一时兴起,想了解一下hashcode生成规则,为什么hashcode相同,无法说明对象相等,但用equals说明相同,却可以推出对象的hashc ...

  7. Spring中RequestContextHolder以及HandlerInterceptorAdapter的使用

    1 . RequestContextHolder 的使用 想要使用RequestContextHolder,要在web.xml中配置RequestContextListener的监听才能使用. //全 ...

  8. eclipse怎么对项目重命名,eclipse怎么重命名类

    eclipse怎么对项目重命名,eclipse怎么重命名类

  9. 译:Dataiku 白皮书之《在银行和保险行业应用数据科学》

    原文链接:Data Science For Banking & Insurance 如果不能正常访问,请点击备份获取. 在银行和保险行业应用数据科学 互联网巨头和金融技术创业时代的求生和发展 ...

  10. ISP PIPLINE (三) BPC

    what is the Bad Pixel? 坏点为死点,也就是基本不随照度变化呈现光电线性转换的关系.表现为暗态常亮,亮态常暗. 坏点分类:静态坏点:亮坏点,暗坏点.                 ...