使用Sanic框架快速搭建測試接口

使用Sanic框架快速搭建測試接口

Sanic框架簡介

  • 引用官方文檔
    Sanic is a Flask-like Python 3.5+ web server that’s written to go fast. It’s based on the work done by the amazing folks at magicstack, and was inspired by this article.
    On top of being Flask-like, Sanic supports async request handlers. This means you can use the new shiny async/await syntax from Python 3.5, making your code non-blocking and speedy.
  • Sanic是一個和Flask很相似的異步web框架,可以使用async/await語法編寫非阻塞的異步函數。
  • 根據官方的說法,這玩意很快,快到接近select的速度

代碼示例

  • 簡單的使用教程參考註釋。
from sanic import Sanic
from sanic import response
from sanic.response import text, json

# appname在小項目中不寫也是可以的
app = Sanic('給你的項目起個名')

# 路由裝飾器,和Flask很相似。
@app.route('/')
async def test(request):
    return text('Hello World!')

	# 可以使用這種語法返回文件
    # return await response.file('./test.html')

# Sanic默認是使用GET的,想使用POST的話,需要在路由裝飾器中修改methods選項
@app.route('/test-json', methods=['POST'])
async def test_json(request):
	# 使用request.json來接收json對象
    print(request.json)
    # Sanic內置json,直接使用這種形式就能返回json對象
    return json({'data': 'True'})

if __name__ == '__main__':
	# 和Flask很相似的啓動方法,綁定IP,端口號,可以選擇消息等級。
    app.run(host='0.0.0.0', port=8800, debug=True)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章