参考:https://www.jianshu.com/p/6ac1cab17929

参考:https://www.cnblogs.com/alexyuyu/p/6243362.html

参考:http://docs.jinkan.org/docs/flask/quickstart.html.

安装基于REST的Web客户端

1、helloworld的运行

from flask import Flask
# Flask初始化参数尽量使用你的包名,这个初始化方式是官方推荐的,官方解释:http://flask.pocoo.org/docs/0.12/api/#flask.Flask
app = Flask(__name__)
@app.route('/HelloWorld')
def hello_world():
return "Hello World!"
app.run()

2、使用get 方法获取资源

# -*- coding: utf-8 -*-
from flask import Flask, jsonify, abort, make_response
app = Flask(__name__)
articles = [
{
'id': 1,
'title': 'the way to python',
'content': 'tuple, list, dict'
},
{
'id': 2,
'title': 'the way to REST',
'content': 'GET, POST, PUT'
}
]
@app.route('/blog/api/articles', methods=['GET'])
def get_articles():
return jsonify({'articles': articles})
@app.route('/blog/api/articles/<int:article_id>', methods=['GET'])
def get_article(article_id):
article = filter(lambda a: a['id'] == article_id, articles)
if len(article) == 0:
abort(404)
return jsonify({'article': article[0]})
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5632)

在终端输入如下得到结果:

$ curl -i http://localhost:5632/blog/api/articles
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 225
Server: Werkzeug/0.12.2 Python/3.6.3
Date: Thu, 22 Mar 2018 15:36:17 GMT {
"articles": [
{
"content": "tuple, list, dict",
"id": 1,
"title": "the way to python"
},
{
"content": "GET, POST, PUT",
"id": 2,
"title": "the way to REST"
}
]
}

3、使用flask的RESTful扩展库

from flask import Flask
from flask_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')
# Todo
# shows a single todo item and lets you delete a todo item
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()

查询列表结果:

查询单任务:

删除任务:

另一个例子:

from flask import Flask
from flask_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')
# Todo
# shows a single todo item and lets you delete a todo item
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)

通过终端进行如下相应任务:

获取列表:

$ curl http://localhost:5000/todos
{"todo1": {"task": "build an API"}, "todo2": {"task": "?????"}, "todo3": {"task": "profit!"}}

获取单个任务:

$ curl http://localhost:5000/todos/todo3
{"task": "profit!"}

删除一个任务:

curl http://localhost:5000/todos/todo2 -X DELETE -v

增加一个任务:

$ curl http://localhost:5000/todos -d "task=something new" -X POST -v

更新一个任务:

$ curl http://localhost:5000/todos/todo3 -d "task=something different" -X PUT -v

python实现Restful服务 (基于flask)(1)的更多相关文章

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

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

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

    https://www.jianshu.com/p/6ac1cab17929 http://www.pythondoc.com/flask/quickstart.html 在java中调用python ...

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

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

  4. python之restful api(flask)获取数据

    需要用到谷歌浏览器的扩展程序 Advanced Rest Client进行模拟请求 1.直接上代码 from flask import Flask from flask import request ...

  5. 实战SpringCloud响应式微服务系列教程(第九章)使用Spring WebFlux构建响应式RESTful服务

    本文为实战SpringCloud响应式微服务系列教程第九章,讲解使用Spring WebFlux构建响应式RESTful服务.建议没有之前基础的童鞋,先看之前的章节,章节目录放在文末. 从本节开始我们 ...

  6. Python flask 基于 Flask 提供 RESTful Web 服务

    转载自 http://python.jobbole.com/87118/ 什么是 REST REST 全称是 Representational State Transfer,翻译成中文是『表现层状态转 ...

  7. XData -–无需开发、基于配置的数据库RESTful服务,可作为移动App和ExtJS、WPF/Silverlight、Ajax等应用的服务端

    XData -–无需开发.基于配置的数据库RESTful服务,可作为移动App和ExtJS.WPF/Silverlight.Ajax等应用的服务端   源起一个App项目,Web服务器就一台,已经装了 ...

  8. 基于SpringBoot开发一个Restful服务,实现增删改查功能

    前言 在去年的时候,在各种渠道中略微的了解了SpringBoot,在开发web项目的时候是如何的方便.快捷.但是当时并没有认真的去学习下,毕竟感觉自己在Struts和SpringMVC都用得不太熟练. ...

  9. 基于TypeScript装饰器定义Express RESTful 服务

    前言 本文主要讲解如何使用TypeScript装饰器定义Express路由.文中出现的代码经过简化不能直接运行,完整代码的请戳:https://github.com/WinfredWang/expre ...

随机推荐

  1. (转)Jquery之ShowLoading遮罩组件

    本文转载自:http://www.cnblogs.com/eczhou/archive/2012/12/18/2822788.html 一.遮罩用途及效果 ShowLoading这个jQuery插件设 ...

  2. 基于modelforms组件实现注册功能

    数据库部分 使用的是auth_user表,添加r_pwd字段后表名变为UserInfo from django.db import models from django.contrib.auth.mo ...

  3. 阶段1 语言基础+高级_1-3-Java语言高级_04-集合_01 Collection集合_4_Iterator接口介绍

    collection集合中是没有索引的,不能使用普通的循环来便利它. 也是在util的包中 先判断集合中有没有元素 有元素就取出来,用next方法 使用接口来接受一个实现类,这就是多态

  4. C 语言跟 C++ 的差异比较

    C++ 完整的 CHM 版离线手册,可以 从这里下载. C++头文件不必是 .h 结尾 C语言中的标准库头文件,例如 math.h 和 stdio.h,在C++中被命名为 cmath 和 cstdio ...

  5. 练习2:python-把excel表格中某张表的内容导入sqlite

    前言:最新需要用到大批量的数据,在excel造好数据之后,存储在数据库库中,方便调用数据,于是就想着用python语言写一下这个过程 python有个openpyxl的模块,可以直接用来对于excel ...

  6. 【ABAP系列】SAP ABAP选择屏幕(SELECTION SCREEN)事件解析

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[ABAP系列]SAP ABAP选择屏幕(SEL ...

  7. 【MM系列】SAP MM-模块物料主数据简介

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP MM-模块物料主数据简介   ...

  8. AcWing 154. 滑动窗口(模板)

    (https://www.acwing.com/problem/content/156/) 给定一个大小为n≤106n≤106的数组. 有一个大小为k的滑动窗口,它从数组的最左边移动到最右边. 您只能 ...

  9. 实现类似add(1)(2)(3)结果为6的效果

    前两天看到一个问题说怎样实现add方法实现add(1)(2)(3)结果为6,于是开始引发了我的思考. 1.想要实现add()()这样调用方式,add()方法的返回值务必是一个函数 function a ...

  10. org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dx.service.ItemService] found for dependency

    在整合ssm框架,测试service层的时候报错 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: ...