使用flask-restful搭建API

蹲街弑〆低调 提交于 2019-11-28 19:20:52

最简单的例子


访问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):  #继承自flask_restful.Resource类
    def get(self):           #定义来自请求的方法, 例如get,post
        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)

实战类


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>')

用户访问http://localhost:5000/ebank/1时,会调用get_login_data()方法返回对应数据. 这里根据用户访问url的不同后缀,进入不同分支,调用不同方法,返回不同结果.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!