Sanic实现了简洁的版本控制,通过传递关键词参数version
给路由装饰器或blueprint初始化方法就可以实现。这将会在url前面添加形似v{version}
的url前缀,其中{version}
就是版本号。
每个路由的版本控制
给路由装饰器传递版本号实现路由级的版本控制。
from sanic import Sanic
from sanic.response import text
app = Sanic()
@app.route("/text", version=1)
async def test(request):
return text('Hi, Version 1\n')
@app.route("/text", version=2)
async def test(request):
return text('Hi, Version 2\n')
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8888, debug=True)
使用curl
访问这个app:
curl localhost:8888/v1/text
curl localhost:8888/v2/text
blueprint的全局版本控制
初始化blueprint时传递版本号,可以应用到该blueprint下的所有路由。
from sanic import response
from sanic.blueprints import Blueprint
bp = Blueprint('test', version=1)
@bp.route('/html')
def handle_request(request):
return response.html('<p>Hello world!</p>')
这样,bp
下的所有路由都是v1
版本。

我的公众号:猿人学 Python 上会分享更多心得体会,敬请关注。
***版权申明:若没有特殊说明,文章皆是猿人学 yuanrenxue.con 原创,没有猿人学授权,请勿以任何形式转载。***
说点什么吧...