前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >基于python3.5+的web框架s

基于python3.5+的web框架s

作者头像
py3study
发布2020-01-02 17:44:45
4140
发布2020-01-02 17:44:45
举报
文章被收录于专栏:python3python3python3

简介

sanic是一款用python3.5+写的web framework,用法和flask类似,sanic的特点是非常快 github官网:https://github.com/channelcat...

速度比较

框架

实现基础

每秒请求数

平均时间

Sanic

Python 3.5 + uvloop

30,601

3.23ms

Wheezy

gunicorn + meinheld

20,244

4.94ms

Falcon

gunicorn + meinheld

18,972

5.27ms

Bottle

gunicorn + meinheld

13,596

7.36ms

Flask

gunicorn + meinheld

4,988

20.08ms

Kyoukai

Python 3.5 + uvloop

3,889

27.44ms

Aiohttp

Python 3.5 + uvloop

2,979

33.42ms

安装

环境:python3.5+ python -m pip install sanic

Hello World

创建文件main.py,写入下面的内容

from sanic import Sanic
from sanic.response import json

app = Sanic(__name__)

@app.route("/")
async def test(request):
    return json({ "hello": "world" })

app.run(host="0.0.0.0", port=8000)

运行python3 main.py sanic是不是看起来和flask一样

 Request

属性 request.files (dictionary of File objects) - 上传文件列表 request.json (any) - json数据 request.args (dict) - get数据 request.form (dict) - post表单数据

例子

from sanic import Sanic
from sanic.response import json

@app.route("/json")
def post_json(request):
    return json({ "received": True, "message": request.json })

@app.route("/form")
def post_json(request):
    return json({ "received": True, "form_data": request.form, "test": request.form.get('test') })

@app.route("/files")
def post_json(request):
    test_file = request.files.get('test')

    file_parameters = {
        'body': test_file.body,
        'name': test_file.name,
        'type': test_file.type,
    }

    return json({ "received": True, "file_names": request.files.keys(), "test_file_parameters": file_parameters })

@app.route("/query_string")
def query_string(request):
    return json({ "parsed": True, "args": request.args, "url": request.url, "query_string": request.query_string })

 路由

和flask差不多,一看就懂

from sanic import Sanic
from sanic.response import text

@app.route('/tag/<tag>')
async def person_handler(request, tag):
    return text('Tag - {}'.format(tag))

@app.route('/number/<integer_arg:int>')
async def person_handler(request, integer_arg):
    return text('Integer - {}'.format(integer_arg))

@app.route('/number/<number_arg:number>')
async def person_handler(request, number_arg):
    return text('Number - {}'.format(number))

@app.route('/person/<name:[A-z]>')
async def person_handler(request, name):
    return text('Person - {}'.format(name))

@app.route('/folder/<folder_id:[A-z0-9]{0,4}>')
async def folder_handler(request, folder_id):
    return text('Folder - {}'.format(folder_id))

注册中间件

app = Sanic(__name__)

@app.middleware
async def halt_request(request):
    print("I am a spy")

@app.middleware('request')
async def halt_request(request):
    return text('I halted the request')

@app.middleware('response')
async def halt_response(request, response):
    return text('I halted the response')

@app.route('/')
async def handler(request):
    return text('I would like to speak now please')

app.run(host="0.0.0.0", port=8000)

异常处理

抛出异常

from sanic import Sanic
from sanic.exceptions import ServerError

@app.route('/killme')
def i_am_ready_to_die(request):
    raise ServerError("Something bad happened")

处理异常

from sanic import Sanic
from sanic.response import text
from sanic.exceptions import NotFound
@app.exception(NotFound)
def ignore_404s(request, exception):
    return text("Yep, I totally found the page: {}".format(request.url))

蓝图

和flask中的蓝图一样,用于组织项目结构 创建一个蓝图,相当于创建一个sanic app,上面的用法和上面相同,把app改成蓝图名称bp

from sanic.response import json
from sanic import Blueprint

bp = Blueprint('my_blueprint')

@bp.route('/')
async def bp_root():
    return json({'my': 'blueprint'})

蓝图注册到主app

from sanic import Sanic
from my_blueprint import bp

app = Sanic(__name__)
app.register_blueprint(bp)

app.run(host='0.0.0.0', port=8000, debug=True)

总结

sanic将是一个非常流行的框架.因为它基于python3.5+,使用了许多新的特性,这些特性让程序速度更快.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • 速度比较
  • 安装
  • Hello World
  •  Request
  •  路由
  • 注册中间件
  • 异常处理
  • 蓝图
  • 总结
相关产品与服务
消息队列 TDMQ
消息队列 TDMQ (Tencent Distributed Message Queue)是腾讯基于 Apache Pulsar 自研的一个云原生消息中间件系列,其中包含兼容Pulsar、RabbitMQ、RocketMQ 等协议的消息队列子产品,得益于其底层计算与存储分离的架构,TDMQ 具备良好的弹性伸缩以及故障恢复能力。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档