使用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的不同后綴,進入不同分支,調用不同方法,返回不同結果.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM