Getting started with the fastest Python WEB framework

Source: Internet
Author: User
Tags throw exception

Speed comparison

Framework implementation base 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
1.from sanic Import Sanic
2.from sanic.response Import JSON
3.
4.app = Sanic ( name) br/>5.
[email protected]("/")
  1. ?? return json ({"Hello": "World"})
  2. 10.app.run (host= "0.0.0.0", port=8000)
    Run? Python3 main.py?
    Does sanic look like flask?
    Request
    Property?
    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
    1.from sanic Import Sanic
    2.from sanic.response Import JSON

  3. [email protected] ("/json")
    5.def Post_json (Request):

  4. ?? return JSON ({"Received": True, "message": Request.json})
  5. [email protected] ("/form")
    9.def Post_json (Request):

  6. ?. return json ({"Received": True, "Form_data": Request.Form, "Test": request.form.get (' Test ')})
  7. [email protected] ("/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. [email protected] ("/query_string")
    25.def query_string (Request):

  16. ?. return json ({"Parsed": True, "args": Request.args, "url": Request.url, "query_string": request.query_string})
    Routing
    And flask Almost, a look at it
    1.from sanic Import Sanic
    2.from sanic.response Import Text
  17. [email protected] ('/tag/')
    5.async def person_handler (request, TAG):

  18. ?? return text (' tag-{} '. Format (TAG))
  19. [email protected] ('/number/')
    9.async def person_handler (Request, Integer_arg):

  20. ?? return text (' Integer-{} '. Format (INTEGER_ARG))
  21. [email protected] ('/number/')
    13.async def person_handler (Request, Number_arg):

  22. ?? return text (' number-{} '. Format (number))
  23. [email protected] ('/person/')
    17.async def person_handler (Request, name):

  24. ?? return text (' Person-{} '. Format (name))
  25. [email protected] ('/folder/')
    21.async def folder_handler (Request, folder_id):

  26. ?? return text (' Folder-{} '. Format (folder_id))
    Register middleware
    1.app = sanic (name)
  27. [Email protected]
    4.async def halt_request (Request):

  28. ?? print ("I am a Spy")
  29. [email protected] (' request ')
    8.async def halt_request (Request):

  30. ?? return text (' I halted the request ')
  31. [email protected] (' response ')
    12.async def halt_response (Request, Response):

  32. ?? return text (' I halted the response ')
  33. [email protected] (‘/‘)
    16.async def handler (request):

  34. ?? return text (' I would like to speak now ')
  35. 19.app.run (host= "0.0.0.0", port=8000)
    Exception handling
    Throw exception
    1.from sanic Import Sanic
    2.from sanic.exceptions Import Servererror

  36. [email protected] ('/killme ')
    5.def I_am_ready_to_die (Request):

  37. ?? Raise Servererror ("Something bad Happened")
    Handling Exceptions
    1.from sanic Import Sanic
    2.from sanic.response Import Text
    3.from sanic.exceptions Import notfoundbr/>[email protected](NotFound)
    < li="">
  38. ?? return text ("Yep, I totally found the page: {}". Format (Request.url))
    Blueprint
    Like the blueprints in flask, to organize the project structure?
    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
    1.from sanic.response Import JSON
    2.from sanic Import Blueprint
  39. 4.BP = Blueprint (' My_blueprint ')

  40. [email protected] (‘/‘)
    7.async def bp_root ():

  41. ?? return json ({' My ': ' Blueprint '})
    Blueprint registration to the main 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)
    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.
    * Disclaimer: Push content and images from the Internet, some of the content will be changed, the copyright is owned by the original author, such as the source of incorrect information or infringement of interests, please contact us for removal or authorization matters.

Getting started with the fastest Python WEB framework

Related Article

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.