最快的 Python Web 框架入门

本文介绍了Sanic,一个基于Python 3.5+的高性能Web框架。它利用了Python的新特性来提高运行效率,并提供了诸如请求处理、路由、中间件等功能。文章还展示了如何创建并运行一个简单的Sanic应用。

速度比较
最快的 Python Web 框架入门
框架 实现基础 每秒请求数 平均时间
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,写入下面的内容
1.from sanic import Sanic
2.from sanic.response import json
3.
4.app = Sanic(name)br/>5.
6.@app.route("/")
7.async def test(request):

  1.    return json({ "hello": "world" })
  2. 10.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表单数据
    例子
    1.from sanic import Sanic
    2.from sanic.response import json

  3. 4.@app.route("/json")
    5.def post_json(request):

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

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

  8.    test_file = request.files.get('test')
  9.    file_parameters = {
  10.        'body': test_file.body,
  11.        'name': test_file.name,
  12.        'type': test_file.type,
  13.    }
  14.    return json({ "received": True, "file_names": request.files.keys(), "test_file_parameters": file_parameters })
  15. 24.@app.route("/query_string")
    25.def query_string(request):

  16.    return json({ "parsed": True, "args": request.args, "url": request.url, "query_string": request.query_string })
    路由
    和flask差不多,一看就懂
    1.from sanic import Sanic
    2.from sanic.response import text
  17. 4.@app.route('/tag/')
    5.async def person_handler(request, tag):

  18.    return text('Tag - {}'.format(tag))
  19. 8.@app.route('/number/')
    9.async def person_handler(request, integer_arg):

  20.    return text('Integer - {}'.format(integer_arg))
  21. 12.@app.route('/number/')
    13.async def person_handler(request, number_arg):

  22.    return text('Number - {}'.format(number))
  23. 16.@app.route('/person/')
    17.async def person_handler(request, name):

  24.    return text('Person - {}'.format(name))
  25. 20.@app.route('/folder/')
    21.async def folder_handler(request, folder_id):

  26.    return text('Folder - {}'.format(folder_id))
    注册中间件
    1.app = Sanic(name)
  27. 3.@app.middleware
    4.async def halt_request(request):

  28.    print("I am a spy")
  29. 7.@app.middleware('request')
    8.async def halt_request(request):

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

  32.    return text('I halted the response')
  33. 15.@app.route('/')
    16.async def handler(request):

  34.    return text('I would like to speak now please')
  35. 19.app.run(host="0.0.0.0", port=8000)
    异常处理
    抛出异常
    1.from sanic import Sanic
    2.from sanic.exceptions import ServerError

  36. 4.@app.route('/killme')
    5.def i_am_ready_to_die(request):

  37.    raise ServerError("Something bad happened")
    处理异常
    1.from sanic import Sanic
    2.from sanic.response import text
    3.from sanic.exceptions import NotFoundbr/>4.@app.exception(NotFound)
    5.def ignore_404s(request, exception):
  38.    return text("Yep, I totally found the page: {}".format(request.url))
    蓝图
    和flask中的蓝图一样,用于组织项目结构 
    创建一个蓝图,相当于创建一个sanic app,上面的用法和上面相同,把app改成蓝图名称bp
    1.from sanic.response import json
    2.from sanic import Blueprint
  39. 4.bp = Blueprint('my_blueprint')

  40. 6.@bp.route('/')
    7.async def bp_root():

  41.    return json({'my': 'blueprint'})
    蓝图注册到主app
    1.from sanic import Sanic
    2.from my_blueprint import bp
  42. 4.app = Sanic(name)
    5.app.register_blueprint(bp)

  43. 7.app.run(host='0.0.0.0', port=8000, debug=True)
    总结
    sanic将是一个非常流行的框架.因为它基于python3.5+,使用了许多新的特性,这些特性让程序速度更快。
    *声明:推送内容及图片来源于网络,部分内容会有所改动,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜。
    最快的 Python Web 框架入门

转载于:https://blog.51cto.com/13878985/2147841

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值