[TOC]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 from flask import Blueprintfrom flask import make_response,render_template,jsonifyfrom flask_restful import Api,Resourceindex_blue=Blueprint('index' ,__name__) api=Api(index_blue) class Index (Resource) : def get (self) : return make_response(render_template('index.html' ,title="WeiyiGeek-Flask-RESTful之API接口编写实践记录" ,boby="这个是一个API专用URL什么都没有,想范返回数据请POST请求获取接口json数据" ),200 ) def post (self) : resp = make_response(render_template('index.json' ),200 ) resp.he return resp def put (self) : return make_response(jsonify({"code" :2022 , "status" : "err" ,"message" :"Not found!" }),200 ) class Robots (Resource) : def get (self) : resp = make_response(render_template('robots.txt' ),200 ) resp.headers={'context-type' :'text/plain' , 'Custom-Head' : 'True' } return resp def post (self) : return {"msg" : "robots.txt requires get request." }, 200 , {"Content-Type" :"application/json" } api.add_resource(Index,"/" ,endpoint='index' ) api.add_resource(Robots,"/robots.txt" ,endpoint='robots' )
执行结果如下图所示:
weiyigeek.top-flask_restful-简单示例
温馨提示: 如果指定资源类没有定义支持的请求方法, 则会在请求后显示”405 METHOD NOT ALLOWED”信息。