zoukankan      html  css  js  c++  java
  • Python 和 Flask 设计 RESTful API

    #!flask/bin/python
    from flask import Flask, jsonify
    from flask import make_response
    app = Flask(__name__)
    
    tasks = [
        {
            'id': 1,
            'title': u'Buy groceries',
            'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
            'done': False
        },
        {
            'id': 2,
            'title': u'Learn Python',
            'description': u'Need to find a good Python tutorial on the web',
            'done': False
        }
    ]
    
    @app.route('/todo/api/v1.0/tasks', methods=['GET'])
    def get_tasks():
        return jsonify({'tasks': tasks})
    
    @app.errorhandler(404)
    def not_found(error):
        return make_response(jsonify({'error': 'Not found'}), 404)

    if __name__ == '__main__': app.run(debug=True)

    请求

    bogon:~ macname$ curl -i http://localhost:5000/todo/api/v1.0/tasks
    HTTP/1.0 200 OK
    Content-Type: application/json
    Content-Length: 317
    Server: Werkzeug/0.16.0 Python/3.7.4
    Date: Tue, 08 Oct 2019 08:57:10 GMT
    
    {
      "tasks": [
        {
          "description": "Milk, Cheese, Pizza, Fruit, Tylenol", 
          "done": false, 
          "id": 1, 
          "title": "Buy groceries"
        }, 
        {
          "description": "Need to find a good Python tutorial on the web", 
          "done": false, 
          "id": 2, 
          "title": "Learn Python"
        }
      ]
    }


    bogon:
    ~ macname$ curl -i http://localhost:5000/todo/api/v1.0/tasks/aq HTTP/1.0 404 NOT FOUND Content-Type: application/json Content-Length: 27 Server: Werkzeug/0.16.0 Python/3.7.4 Date: Tue, 08 Oct 2019 08:57:15 GMT { "error": "Not found" }

     参考:

    https://www.cnblogs.com/momoyan/p/11027572.html

  • 相关阅读:
    9.过滤器的使用
    8.公共组件
    7.Props向子组件传递数据
    6.组件
    5.指令系统-事件
    4.指令系统
    SpringCloud入门
    springcloud注解
    was unable to refresh its cache! status = Cannot execute request on any known server
    集成第三方框架,报错NoSuchFieldError:logger
  • 原文地址:https://www.cnblogs.com/sea-stream/p/11636560.html
Copyright © 2011-2022 走看看