nolang

使用flask-restful搭建API

最简单的例子

---~~~~

访问http://127.0.0.1:5000/ , 返回{"hello": "world"}

from flask import Flask
from flask_restful import Resource, 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)

通过路由访问


命令行执行curl http://localhost:5000/todo1 -d "data=Remember the milk" -X PUT , 返回{"todo1": "Remember the milk"}.
执行curl http://localhost:5000/todo1,返回{"todo1": "Remember the milk"}

from flask import Flask, request
from flask_restful import Resource, Api

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

todos = {}

class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

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

api.add_resource(TodoSimple, '/<string:todo_id>')

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

分类:

技术点:

相关文章:

  • 2021-10-24
  • 2021-12-02
  • 2021-12-29
  • 2021-08-22
  • 2021-11-22
  • 2017-12-21
  • 2021-05-24
  • 2021-08-21
猜你喜欢
  • 2021-12-13
  • 2021-09-14
  • 2021-12-02
  • 2020-04-07
  • 2021-07-12
  • 2021-04-09
  • 2019-11-10
相关资源
相似解决方案