速度比较

框架 实现基础 每秒请求数 平均时间
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)

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/')
async def person_handler(request, tag):
    return text('Tag - {}'.format(tag))
@app.route('/number/')
async def person_handler(request, integer_arg):
    return text('Integer - {}'.format(integer_arg))
@app.route('/number/')
async def person_handler(request, number_arg):
    return text('Number - {}'.format(number))
@app.route('/person/')
async def person_handler(request, name):
    return text('Person - {}'.format(name))
@app.route('/folder/')
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+,使用了许多新的特性,这些特性让程序速度更快。


看完以上的内容,相信你对于Linux运维的了解又加深了一层。作为一名Linux爱好者,如果你在学习中遇到了困惑需要交流,可以来我们的网站(http://www.magedu.com/)获取帮助,了解行业评价最高的Linux课程可以拨打电话:18519746220。

最快的 Python Web 框架入门的更多相关文章

  1. Python Flask Web 框架入门

    Python Flask 目录 本文主要借鉴 letiantian 的文章 http://www.letiantian.me/learn-flask/ 一.简介 二.安装 三.初始化Flask 四.获 ...

  2. 一步一步理解 python web 框架,才不会从入门到放弃

    要想清楚地理解 python web 框架,首先要清楚浏览器访问服务器的过程. 用户通过浏览器浏览网站的过程: 用户浏览器(socket客户端) 3. 客户端往服务端发消息 6. 客户端接收消息 7. ...

  3. python三大web框架Django,Flask,Flask,Python几种主流框架,13个Python web框架比较,2018年Python web五大主流框架

    Python几种主流框架 从GitHub中整理出的15个最受欢迎的Python开源框架.这些框架包括事件I/O,OLAP,Web开发,高性能网络通信,测试,爬虫等. Django: Python We ...

  4. Django,Flask,Tornado三大框架对比,Python几种主流框架,13个Python web框架比较,2018年Python web五大主流框架

    Django 与 Tornado 各自的优缺点Django优点: 大和全(重量级框架)自带orm,template,view 需要的功能也可以去找第三方的app注重高效开发全自动化的管理后台(只需要使 ...

  5. 教程:Visual Studio 中的 Django Web 框架入门

    教程:Visual Studio 中的 Django Web 框架入门 Django 是高级 Python 框架,用于快速.安全及可扩展的 Web 开发. 本教程将在 Visual Studio 提供 ...

  6. 浅谈Python web框架

    一.Python web框架 Web Framework,Ruby的世界Rails一统江湖,而Python则是一个百花齐放的世界,各种micro-framework.framework不可胜数,不完全 ...

  7. python web框架介绍对比

    Django Python框架虽然说是百花齐放,但仍然有那么一家是最大的,它就是Django.要说Django是Python框架里最好的,有人同意也有人 坚决反对,但说Django的文档最完善.市场占 ...

  8. “脚踢各大Python Web框架”,Sanic真有这能耐么?

    在Github上,Sanic第一句介绍语就是: "Sanic is a Flask-like Python 3.5+ web server that's written to go fast ...

  9. Python web框架——Tornado

    Tornado是一个Python Web框架和异步网络库,最初由FriendFeed开发.通过使用非阻塞网络I / O,Tornado可以扩展到数万个开放连接,使其成为需要长时间连接每个用户的长轮询, ...

随机推荐

  1. Android开发之ListView实现不同品种分类分隔栏的效果(非ExpandableListView实现)

    我们有时候会遇到这么一个情况.就是我在一个ListView里面须要显示的东西事实上是有种类之分的.比方我要分冬天,夏天.秋天.春天,然后在这每一个季节以下再去载入各自的条目数据. 还有,比方我们的通讯 ...

  2. hdu 4193 单调队列

    题意是给你n个数   组成的环   求以一个数开头 的数列全部前缀都为非负数的数列的个数: 思路:  先扩展成2*n的数列 然后求出sum[i]表示前i项的和     对每一个i>.=n结尾的数 ...

  3. Oracle移除表空间的数据文件 ora-00604 ora-01426

     项目背景:在之前开发环境数据库管理比較乱,在表空间不足时仅仅是加入数据文件,測试完后数据己删除,但数据库表空间所占的空间不能回收,导致数据库的存储文件夹使用率达到97%以上实际使用仅仅有10%, ...

  4. TGraphicControl和TCustomControl自绘过程的理论解释

    TGraphicControl = class(TControl) // 这个类实在是简单,因为所有事情都已经委托给它的父Win控件了,只要管自己即可 private FCanvas: TCanvas ...

  5. jquery操作删除元素

    通过 jQuery,可以很容易地删除已有的 HTML 元素. 删除元素/内容 如需删除元素和内容,一般可使用以下两个 jQuery 方法: remove() - 删除被选元素(及其子元素) empty ...

  6. 布局技巧4:使用ViewStub

    多亏了<include />标签,在Android里,很容易就能做到共享和重用UI组件.在Android开发中,很容易就能创建出复杂的UI结构,结果呢,用了很多的View,且其中的一些很少 ...

  7. /lib/dracut/hooks/shutdown/30-dm-shutdown.sh

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAABVQAAAMACAIAAABEqXuoAAAgAElEQVR4nOydPWjryOK3VaZM8RYpU2 ...

  8. tinymce 出现 Uncaught (in promise) TypeError: ae(...).createObjectURL is not a function

    需要引入两个JS文件:jQuery.tinymce.min.js 和 tinymce.min.js <script type="text/javascript" src=&q ...

  9. 【洛谷3467/BZOJ1113】[POI2008]海报PLA-Postering(单调栈)

    题目: 洛谷3467 分析: (ti jie shuo)这题是个单调栈经典题. 单调栈就是栈元素递增或递减的栈,这里只考虑递增.新元素入递增栈时,先将所有比它大的元素弹出,然后让新元素入栈,这样保证栈 ...

  10. Hadoop Hive概念学习系列之hive里的用户定义函数UDF(十七)

    Hive可以通过实现用户定义函数(User-Defined Functions,UDF)进行扩展(事实上,大多数Hive功能都是通过扩展UDF实现的).想要开发UDF程序,需要继承org.apache ...