Python 异步Web框架Sanic


注: 本文参考 Sanic官方文档 编写:

安装Sanic

pip install sanic # 注意: sanic框架仅支持python3.5+版本

Hello World

  1. 新建一个文件hello.py
    from sanic import Sanic
    from sanic.response import json
    
    app = Sanic()
    
    @app.route("/")
    async def test(request):
       return json({"hello": "world"})
    
    if __name__ == "__main__":
       app.run(host="0.0.0.0", port=8000)
    
  2. 运行这个文件:
     python3 hello.py
    
  3. 打开游览器: http://0.0.0.0:8000

搭建一个后端Web服务器

  1. 新建一个项目文件夹 如: NewSanic
  2. 新建一个配置文件, settings.py
    # 访问配置
    HOST = ['*']
    PORT = 8000
    DEBUG = True
    
  3. 新建项目管理文件 manage.py
    from NewSanic import settings
    from NewSanic.urls import app
    
    if __name__ == '__main__':
        app.run(
            host="0.0.0.0" if settings.HOST[0] == '*' else settings.HOST[0],
            port=settings.PORT or 8000,
            debug=settings.DEBUG
        )
    
  4. 新建一个apis文件夹, 用来存放不同类型的视图API
    • 创建一个简单的view.py 文件
    from sanic.response import json, text, html, redirect
    
    async def test(request):
        """返回json"""
        print(type(request), request)
        context = {"hello": "world"}
        return json(context)
    
    async def tag_test(request, arg):
        """get 传参"""
        print(request.url)
        print(request.host)
        print(request.ip)
        print(request.path)
        print(request.app.name)
        return text('arg is {}'.format(arg))
    
    async def html_test(request):
        """html对象"""
        return html('<h1>this is html h1 tag')
    
    async def redirect_test(request):
        """重定向"""
        return redirect(to='/test/html/', content_type='text/html; charset=utf-8')
    
  5. 在项目根目录创建一个公用的urls.py文件, 用来存放所有的路由
    from sanic import Sanic
    from NewSanic.apis.view import test, tag_test, html_test, redirect_test
    
    app = Sanic(name='first_app')
    app.add_route(test, '/')
    app.add_route(html_test, "/test/html/")
    app.add_route(redirect_test, "/test/redirect/")
    app.add_route(tag_test, "/test/<arg>/")
    
  6. 至此, 一个由Sanic搭建的Web服务器已经完成, 执行以下命令启动项目:
    python manage.py
    

完整代码地址: https://pan.baidu.com/s/1RypF0Bppv8MY309Oy9HR5A

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值