使用Sanic框架快速搭建测试接口

10 篇文章 0 订阅
6 篇文章 0 订阅

使用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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安心写bug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值