【Python】Flask-RESTful使用

来源:互联网 发布:学c4d 知乎 编辑:程序博客网 时间:2024/04/30 08:08

参考文章

  • 参考文章地址

项目结构

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 restfulclass Foo(restful.Resource):    def get(self):        pass    def post(self):        pass

app.py 中的配置就像这样:

from flask import Flaskfrom flask.ext import restfulfrom myapi.resources.foo import Foofrom myapi.resources.bar import Barapp = 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 Flaskfrom flask.ext import restfulapp = 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 Flaskfrom flask.ext.restful import reqparse, abort, Api, Resourceapp = 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 themclass 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 tasksclass 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"}
0 0
原创粉丝点击