【Python】Flask-RESTful使用
2016-01-20 14:47
766 查看
参考文章
参考文章地址项目结构
myapi/ __init__.py app.py # this file contains your app and routes resources/ __init__.py foo.py # contains logic for /Foo bar.py # contains logic for /Bar common/ __init__.py util.py # just some common infrastructure
common 文件夹可能只包含一组辅助函数以满足你的应用程序公共的需求。例如,它也可能包含任何自定义输入/输出类型。
在 resource 文件夹中,你只有资源对象。因此这里就是 foo.py 可能的样子:
from flask.ext import restful class Foo(restful.Resource): def get(self): pass def post(self): pass
app.py 中的配置就像这样:
from flask import Flask from flask.ext import restful from myapi.resources.foo import Foo from myapi.resources.bar import Bar app = Flask(__name__) api = restful.Api(app) api.add_resource(Foo, '/Foo', '/Foo/<str:id>') api.add_resource(Bar, '/Bar', '/Bar/<str:id>')
一个最小的Flask-RESTful API
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)
带参数解析例子
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)
用法示例
$ python api.py * Running on http://127.0.0.1:5000/ * Restarting with reloader
获取列表
$ curl http://localhost:5000/todos {"todo1": {"task": "build an API"}, "todo3": {"task": "profit!"}, "todo2": {"task": "?????"}}
获取一个单独的任务
$ curl http://localhost:5000/todos/todo3 {"task": "profit!"}
增加一个新的任务
$ curl http://localhost:5000/todos -d "task=something new" -X POST -v > POST /todos HTTP/1.1 > User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3 > Host: localhost:5000 > Accept: */* > Content-Length: 18 > Content-Type: application/x-www-form-urlencoded > * HTTP 1.0, assume close after body < HTTP/1.0 201 CREATED < Content-Type: application/json < Content-Length: 25 < Server: Werkzeug/0.8.3 Python/2.7.2 < Date: Mon, 01 Oct 2012 22:12:58 GMT < * Closing connection #0 {"task": "something new"}
相关文章推荐
- Python算法题----Palindrome Number
- Python中urllib+urllib2+cookielib模块编写爬虫实战
- Python Django
- python操作Elasticsearch (一、例子)
- 【LEETCODE】275-H-Index II [Python]
- Python之super函数
- Python算法题----Valid Palindrome
- python 类方法,和实例方法
- 《Python核心编程》第九章
- 统计拼音字母使用频率 python
- 转 Python中的正则表达式
- Python安装其它库的步骤和问题解决方案汇总
- windows系统下Python环境的搭建
- Python教你,谁把你的微信删除了!
- 【转】Python实现修改Windows CMD命令行输出颜色(完全解析)
- 深入剖析Python的爬虫框架Scrapy的结构与运作流程
- python--pack
- python--socket
- python--杂
- 实践Python的爬虫框架Scrapy来抓取豆瓣电影TOP250