使用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): #继承自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的不同后缀,进入不同分支,调用不同方法,返回不同结果.