掌握聚合最新动态了解行业最新趋势
API接口,开发服务,免费咨询服务

最快的 Python Web 框架入门

速度比较

框架实现基础每秒请求数平均时间
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,写入下面的内容

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+,使用了许多新的特性,这些特性让程序速度更快.

                 ▄▄▄▄▄
        ▀▀▀██████▄▄▄       _______________
      ▄▄▄▄▄  █████████▄  /                 \
     ▀▀▀▀█████▌ ▀▐▄ ▀▐█ |   Gotta go fast!  |
   ▀▀█████▄▄ ▀██████▄██ | _________________/
   ▀▄▄▄▄▄  ▀▀█▄▀█════█▀ |/
        ▀▀▀▄  ▀▀███ ▀       ▄▄
     ▄███▀▀██▄████████▄ ▄▀▀▀▀▀▀█▌
   ██▀▄▄▄██▀▄███▀ ▀▀████      ▄██
▄▀▀▀▄██▄▀▀▌████▒▒▒▒▒▒███     ▌▄▄▀
▌    ▐▀████▐███▒▒▒▒▒▐██▌
▀▄▄▄▄▀   ▀▀████▒▒▒▒▄██▀
          ▀▀█████████▀
        ▄▄██▀██████▀█
      ▄██▀     ▀▀▀  █
     ▄█             ▐▌
 ▄▄▄▄█▌              ▀█▄▄▄▄▀▀▄
▌     ▐                ▀▀▄▄▄▀
 ▀▀▄▄▀

原文来自:Prasanta

声明:所有来源为“聚合数据”的内容信息,未经本网许可,不得转载!如对内容有异议或投诉,请与我们联系。邮箱:marketing@think-land.com

  • AI文生视频

    支持通过自然语言文本智能生成高质量短视频。用户只需输入一段描述性文字,即可自动合成画面连贯、风格鲜明、配乐匹配的定制化视频内容。适用于短视频创作、广告预演、社交内容生成、游戏素材制作等场景,为开发者与创作者提供高效、灵活、富有想象力的视频生产新范式。

    支持通过自然语言文本智能生成高质量短视频。用户只需输入一段描述性文字,即可自动合成画面连贯、风格鲜明、配乐匹配的定制化视频内容。适用于短视频创作、广告预演、社交内容生成、游戏素材制作等场景,为开发者与创作者提供高效、灵活、富有想象力的视频生产新范式。

  • AI图像理解

    先进的图像理解和分析能力,它能够快速准确地解析和理解图像内容。无论是自然风景、城市建筑还是复杂的场景与活动,都能提供详细的描述和深入的分析。

    先进的图像理解和分析能力,它能够快速准确地解析和理解图像内容。无论是自然风景、城市建筑还是复杂的场景与活动,都能提供详细的描述和深入的分析。

  • AI图像编辑

    根据文本提示(prompt)和图片公网访问链接,编辑原图按照特定风格、场景和氛围感的输出新的图像。广泛应用于电商营销、广告设计、创意灵感等领域,为用户带来高效且个性化的AI图像创作体验。

    根据文本提示(prompt)和图片公网访问链接,编辑原图按照特定风格、场景和氛围感的输出新的图像。广泛应用于电商营销、广告设计、创意灵感等领域,为用户带来高效且个性化的AI图像创作体验。

  • AI图像生成

    根据文本提示(prompt),生成生成具有特定风格、场景和氛围感的图像。广泛应用于电商营销、广告设计、创意灵感等领域,为用户带来高效且个性化的AI图像创作体验。

    根据文本提示(prompt),生成生成具有特定风格、场景和氛围感的图像。广泛应用于电商营销、广告设计、创意灵感等领域,为用户带来高效且个性化的AI图像创作体验。

  • 台风路径

    查询台风信息和台风路径

    查询台风信息和台风路径

0512-88869195
数 据 驱 动 未 来
Data Drives The Future