Getting started with the fastest Python WEB framework

Source: Internet
Author: User
Tags throw exception

Speed comparison
Frame Implement the Basics number of requests per second Average Time
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
Installation

Environment: python3.5+
python -m pip install sanic

Hello World

Create a file main.py, write the following content

From sanic import sanicfrom sanic.response Import Jsonapp = Sanic (__name__) @app. Route ("/") Async def Test (request): Retu RN json ({"Hello": "World"}) App.run (host= "0.0.0.0", port=8000)

Does sanic look like flask?

Request

Properties
Request.Files (Dictionary of File objects)-List of uploaded files
Request.json (any)-JSON data
Request.args (dict)-Get data
Request.Form (dict)-Post form data

Example

From sanic import sanicfrom 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 ') &nbsp @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 })
Routing

And flask Almost, a look at it

From sanic import sanicfrom 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 (' Intege  R-{} '. 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 (NA Me) @app. Route ('/folder/') async def folder_handler (Request, folder_id): Return text (' folder-{} '. Format (folder_id))
Register middleware
App = Sanic (__name__) @app. Middlewareasync def halt_request (request): print ("I am a Spy") @app. Middleware (' request ') Asyn C def halt_request (Request): Return text (' I halted the request ') @app. Middleware (' response ') Async def halt_response (requ EST, response): Return text (' I halted the response ') @app. Route ('/') Async def handler (Request): Return text (' I would Like to speak Now ') App.run (host= "0.0.0.0", port=8000)
Exception handling

Throw exception

From sanic import sanicfrom sanic.exceptions import servererror@app.route ('/killme ') def i_am_ready_to_die (request): RA Ise servererror ("Something bad Happened")

Handling Exceptions

From sanic import sanicfrom sanic.response import textfrom sanic.exceptions import notfound@app.exception (NotFound) def ignore_404s (Request, Exception): Return text ("Yep, I totally found the page: {}". Format (Request.url))
Blueprint

Like the blueprints in flask, for organizing project structures
Create a blueprint that is equivalent to creating a Sanic app with the same usage as above and changing the app to a blueprint name BP

From sanic.response import jsonfrom sanic Import BLUEPRINTBP = Blueprint (' my_blueprint ') @bp. Route ('/') Async def bp_root ( ): Return json ({' My ': ' Blueprint '})

Blueprint registration to the main app

From sanic import sanicfrom my_blueprint Import Bpapp = Sanic (__name__) app.register_blueprint (BP) app.run (host= ' 0.0.0.0 ', port=8000, Debug=true)
Summarize

Sanic will be a very popular framework. Because it's based on python3.5+, it uses many new features that make the program faster.

After reading the above, I believe you have deepened the understanding of Linux operations. As a Linux enthusiast, if you encounter confusion in your studies and need to communicate, you can come to our website (http://www.magedu.com/) to get help, learn about the industry's highest rated Linux courses can call: 18519746220.

Getting started with the fastest Python WEB framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.