• Python Flask Restful


    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>')
  • 相关阅读:
    开源APM应用性能管理工具调研
    Inside ARC — to see the code inserted by the compiler
    报表应用系统中怎样正确使用图表功能
    创建cifs系统案例之“实现将Windows磁盘共享至Linux”
    Eclipse快捷键 10个最有用的快捷键
    如何生成KeyStore
    android中调用系统的发送短信、发送邮件、打电话功能
    android自带theme
    Android 报错:Conversion to Dalvik format failed: Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.
    Android oncreate onupgrade什么时候被调用
  • 原文地址:https://www.cnblogs.com/shadow-yin/p/10671149.html
Copyright © 2020-2023  润新知