美文网首页
6、flask-restful基础

6、flask-restful基础

作者: 波罗的海de夏天 | 来源:发表于2020-05-04 00:27 被阅读0次

    安装: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, '/<string:todo_id>')
    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基础

          本文链接:https://www.haomeiwen.com/subject/zrvsghtx.html