您的位置:首页 > 编程语言 > Python开发

【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"}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: