6、flask-restful基础

安装:pip install flask-restful -i https://pypi.tuna.tsinghua.edu.cn/simple/
文档:http://www.pythondoc.com/Flask-RESTful/quickstart.html

Script Demo:

# -*- coding:utf-8 -*-
from flask import Flask, request, jsonify
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)


class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

    def post(self):
        return {'hello': 'python3'}



class TodoSimple(Resource):
    todos = {}
    def get(self, todo_id):
        return {todo_id: self.todos[todo_id], 'request_type': 'GET'}

    def post(self, todo_id):
        return {todo_id: self.todos[todo_id], 'request_type': 'POST'}

    def put(self, todo_id):
        self.todos[todo_id] = request.form['data']
        return {todo_id: self.todos[todo_id], 'request_type': 'PUT'}


# 多个URL访问同一个地址
class Todo_1(Resource):
    def get(self):
        result = {
            'do_something': 'song'
        }

        return jsonify(result)


# 状态码
class Todo_2(Resource):
    def get(self):
        result = {
            'task': '赛里木湖自驾游'
        }

        return result, 200


api.add_resource(HelloWorld, '/')
api.add_resource(TodoSimple, '/')
api.add_resource(Todo_1, '/1', '/1/')
api.add_resource(Todo_2, '/2', '/2/')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001, debug=True)

你可能感兴趣的:(6、flask-restful基础)