Use flask-restful API build

The simplest example


Visit http://127.0.0.1:5000/, return{"hello": "world"}

from flask import Flask
from flask_restful import Resource, Api

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

class HelloWorld(Resource):  #继承自flask_restful.Resource类
    def get(self):           #定义来自请求的方法, 例如get,post
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

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

By routing access


Command line execution curl http://localhost:5000/todo1 -d "data=Remember the milk" -X PUT, return {"todo1": "Remember the milk"}.
Execution curl http://localhost:5000/todo1, return{"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)

Real class


class EBank(Resource):

    def get(self,todo_id):
        if todo_id is '1' : #v0/login.do; 返回登录密文.
            return get_login_data()
        elif todo_id is '2':
            return gen_random_string(39) #返回39位随机数
        elif todo_id is '3':
            content = get_talk_ttkey()
            str1 = get_str1(content)
            str2 = get_str2(content)
            str3 = get_str3(content)
            x = {"a":str1,"b":str2,"c":str3}
            return x
        else:
            return 0

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

User access http://localhost:5000/ebank/1, the calls get_login_data () method returns the corresponding data. Here the user to access different suffixes url into different branches, call different methods to return a different result.

Guess you like

Origin www.cnblogs.com/nolang/p/11422148.html