Py学习  »  Python

最快的 Python Web 框架入门

编程派 • 7 年前 • 637 次点击  

sanic是一款用 python3.5+ 写的 web framework,用法和 flask 类似,特点是非常快 。


Github 官网:https://github.com/channelcat/sanic

速度比较

框架实现基础每秒请求数平均时间
SanicPython 3.5 + uvloop30,6013.23ms
Wheezygunicorn + meinheld20,2444.94ms
Falcongunicorn + meinheld18,9725.27ms
Bottlegunicorn + meinheld13,5967.36ms
Flaskgunicorn + meinheld4,98820.08ms
KyoukaiPython 3.5 + uvloop3,88927.44ms
AiohttpPython 3.5 + uvloop2,97933.42ms

安装

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

Hello World

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

  1. from sanic import Sanic

  2. from sanic.response import json

  3. app = Sanic(__name__)

  4. @app.route("/")

  5. async def test(request):

  6.    return json({ "hello": "world" })

  7. 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. @app.route("/json" )

  4. def post_json(request):

  5.    return json({ "received": True, "message": request.json })

  6. @app.route("/form")

  7. def post_json(request):

  8.    return json({ "received": True, "form_data": request.form, "test": request.form.get('test') })

  9. @app.route("/files")

  10. def post_json(request):

  11.    test_file = request.files.get('test' )

  12.    file_parameters = {

  13.        'body': test_file.body,

  14.        'name': test_file.name,

  15.        'type': test_file.type,

  16.    }

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

  18. @app.route("/query_string")

  19. def query_string(request):

  20.    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

  3. @app.route('/tag/')

  4. async def person_handler(request, tag):

  5.    return text('Tag - {}'.format(tag))

  6. @app.route('/number/')

  7. async def person_handler(request, integer_arg):

  8.    return text('Integer - {}'.format (integer_arg))

  9. @app.route('/number/')

  10. async def person_handler(request, number_arg):

  11.    return text('Number - {}'.format(number))

  12. @app.route('/person/')

  13. async def person_handler(request, name):

  14.    return text('Person - {}'.format(name))

  15. @app.route('/folder/')

  16. async def folder_handler(request, folder_id):

  17.    return text('Folder - {}'.format( folder_id))

注册中间件

  1. app = Sanic(__name__)

  2. @app.middleware

  3. async def halt_request(request):

  4.    print("I am a spy")

  5. @app.middleware('request')

  6. async def halt_request(request):

  7.    return text('I halted the request')

  8. @app.middleware('response')

  9. async def halt_response(request, response):

  10.    return text('I halted the response')

  11. @app.route('/')

  12. async def handler(request):

  13.    return text('I would like to speak now please')

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

异常处理

抛出异常

  1. from sanic import Sanic

  2. from sanic.exceptions import ServerError

  3. @app.route('/killme')

  4. def i_am_ready_to_die(request):

  5.    raise ServerError("Something bad happened")

处理异常

  1. from sanic import Sanic

  2. from sanic.response import text

  3. from sanic.exceptions import NotFound

  4. @app.exception(NotFound)

  5. def ignore_404s(request, exception):

  6.    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

  3. bp = Blueprint('my_blueprint')

  4. @bp.route('/')

  5. async def bp_root():

  6.    return json({'my': 'blueprint'})

蓝图注册到主app

  1. from sanic import Sanic

  2. from my_blueprint import bp

  3. app = Sanic(__name__)

  4. app.register_blueprint(bp)

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

总结

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

作者:Prasanta 

来源:https://segmentfault.com/a/1190000007193348


题图:pexels,CC0 授权。



今天看啥 - 高品质阅读平台
本文地址:http://www.jintiankansha.me/t/P1yZn5axIE
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/4643
 
637 次点击