SlideShare a Scribd company logo
SANIC
EXPERIENCE BLAZING FAST PYTHON WEB FRAMEWORK
PyCon ID Surabaya, Indonesia 2017
Fauzan Erich Emmerling
VP Integration @ prismapp.io
@femmerling (GitHub, twitter, IG)
pythonista since 2010
http://www.emfeld.com
currently active in Python-ID Jogja
PYTHON WEB
FRAMEWORKS ARE
SLOW
THEY SAY
WHY WAS PYTHON SLOW
▸ It’s interpreted
▸ It’s dynamically typed
▸ In python 2.x concurrency is a big mess
▸ Async is hard
▸ The notoriously famous GIL
THEN COMES
PYTHON 3.X
WHAT HAPPENS AT 3.X??
▸ Still interpreted
▸ Better performance
▸ Still dynamically typed but now comes with type hinting
▸ Since 3.5 async is a walk in the park
▸ GIL is still there but Asyncio saves us, BIG TIME
ENTER UVLOOP
“a full, drop-in replacement for the asyncio event
loop. uvloop is written in Cython and built on top
of libuv.
uvloop makes asyncio fast. In fact, it is at least 2x
faster than nodejs, gevent, as well as any other
Python asynchronous framework”
Yuri Selivanov
WHAT IS UVLOOP
HTTP Benchmark Test
DUDE, IT’S MY TURN NOW!!!
GOTTA GO FAST!!!
SANIC WEB
FRAMEWORK
WHAT IS IT?
▸ a python 3.5+ micro framework thats written to go fast
▸ small and contained
▸ inspired a lot by Flask, that’s why I ❤ it
▸ accepts async handlers so the we can use shiny async/
await syntax
WHY USE SANIC?
▸ super easy to learn
▸ can be a micro framework up to a full monolith, just like flask
▸ async capabilities, better concurrency
▸ performs like that of Go or NodeJS but with better syntax
▸ great docs
▸ extensions are growing
▸ however currently no wheel for uvloop on windows yet
▸ set your own workers
FEATURES
▸ async request handling
▸ http and websocket
▸ class based views
▸ blueprints
▸ configurations
▸ cookies
HOW TO START USING IT?
▸ make sure you have python 3.5+
▸ $ pip install sanic
▸ start coding
DOES THIS RING A BELL?
from sanic import Sanic
from sanic import response as sanic_response
from services import get_image_content, get_mimetype, set_expiry_headers
app = Sanic(__name__)
@app.route('/<image_url:path>')
async def index(request, image_url):
content_type = get_mimetype(image_url=image_url)
headers = set_expiry_headers()
async def get_image(response):
content = await get_image_content(image_url)
response.write(content)
return sanic_response.stream(
get_image,
content_type=content_type,
headers=headers)
if __name__ == '__main__':
app.run(host='0.0.0.0',
port=5000, debug=True, workers=4)
SOME BEST PRACTICES
use factory pattern for apps:
def create_app():
app = Sanic(__name__)
init_exception_handling(app=app)
app.add_route(
handle_transcript,
'/v2/conversations_transcript',
methods=['POST'])
app.add_route(
handle_ack,
'/v2/conversations_transcript',
methods=['OPTIONS'])
return app
SOME BEST PRACTICES
map exceptions
def init_handled_exceptions(app):
if app is None:
raise AppError('`app` is required')
@app.exception(AppError)
def handled_exceptions(request, exception):
error = create_response(
payload=exception.to_dict(),
status_code=exception.status_code)
logger.error(
exception.message,
error=error)
return response.json(
error.payload,
headers=error.headers,
status=exception.status_code)
SOME BEST PRACTICES
separate handlers from route for easier testing
from app.handlers.transcript import handle_transcript
app = Sanic(__name__)
init_exception_handling(app=app)
app.add_route(
handle_transcript,
'/v2/conversations_transcript',
methods=['POST'])
SANIC IN REAL LIFE
▸ Scarlett Project
▸ Translates image streams from http to https
▸ Handles around 200 req/s per worker
▸ Runs behind Gunicorn with 4 workers running
▸ Only need 1 docker container for now
▸ Average response time is 10ms
▸ Developed in 1.5 hours
SOMETIMES YOU GOTTA RUN
BEFORE YOU CAN WALK
Tony Stark
OUR MANTRA AT PRISM
QUESTIONS?
you can also ask on:
twitter: @femmerling
mail: erich@emfeld.com
THANK YOU
in case you’re wondering..
Yes, we’re hiring!!!
fauzan@prismapp.io

More Related Content

PDF
APIs That Make Things Happen
PDF
How WebHooks Will Make Us All Programmers
PDF
Webpack Encore Symfony Live 2017 San Francisco
PPTX
You are not_hiding_from_me_.net
PPTX
Cloud Native Batch Processing
PPT
Jenkins on Docker
PPTX
Deploying phalcon on heroku
PDF
Understanding meteor
APIs That Make Things Happen
How WebHooks Will Make Us All Programmers
Webpack Encore Symfony Live 2017 San Francisco
You are not_hiding_from_me_.net
Cloud Native Batch Processing
Jenkins on Docker
Deploying phalcon on heroku
Understanding meteor

What's hot (20)

PDF
Master the New Core of Drupal 8 Now: with Symfony and Silex
PDF
API for Beginners
PDF
node-webkit : Make a magic from your a desktop app to desktop app!
PPTX
Plone 6 / Volto Dexterity Content Types - Schema & Layout
PDF
WP-CLI: Unleash the power
PPTX
Writing java script for Csharp's Blazor
PPTX
Magento2 From Setup To Deployment. Automate Everything
PDF
BOSH / CF Deployment in modern ways #cf_tokyo
PPTX
Dockercon - Building a Chef cookbook testing pipeline with Drone.IO and Docker
PDF
Droidcon ES '16 - How to fail going offline
PPTX
Bringing Javascript to the Desktop with Electron
PDF
Web development with Lua and Sailor @ GeeCon 2015
PDF
Ionic2
PDF
Introducing Firebase by Google
PDF
Scala Vienna Website: reloaded
PDF
Symfony: Your Next Microframework (SymfonyCon 2015)
PDF
Using Composer with WordPress
PDF
Get your ass to 1.9
PPT
Auto Build
PPTX
Play with Alfresco ADF 2.0.0 Angular
Master the New Core of Drupal 8 Now: with Symfony and Silex
API for Beginners
node-webkit : Make a magic from your a desktop app to desktop app!
Plone 6 / Volto Dexterity Content Types - Schema & Layout
WP-CLI: Unleash the power
Writing java script for Csharp's Blazor
Magento2 From Setup To Deployment. Automate Everything
BOSH / CF Deployment in modern ways #cf_tokyo
Dockercon - Building a Chef cookbook testing pipeline with Drone.IO and Docker
Droidcon ES '16 - How to fail going offline
Bringing Javascript to the Desktop with Electron
Web development with Lua and Sailor @ GeeCon 2015
Ionic2
Introducing Firebase by Google
Scala Vienna Website: reloaded
Symfony: Your Next Microframework (SymfonyCon 2015)
Using Composer with WordPress
Get your ass to 1.9
Auto Build
Play with Alfresco ADF 2.0.0 Angular
Ad

Similar to Sanic: Experience Blazing Fast Python Web Framework (20)

PDF
Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면
PDF
Python performance engineering in 2017
PPTX
Asynchronous Frameworks.pptx
PDF
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
PPTX
Asynchronous Python with Twisted
PPTX
Async programming and python
PDF
Async Web Frameworks in Python
PDF
Scaling Uber
PDF
Building Web APIs that Scale
PDF
BIW15: Python in the Cloud: Django and Flaks
PPTX
python_development.pptx
KEY
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
PDF
Realtime Apps with Django
PDF
Scaling Django with gevent
PDF
Rapid Web Development with Python for Absolute Beginners
PDF
Understanding PyPy - PyConEs 14
PPTX
Using Coroutines to Create Efficient, High-Concurrency Web Applications
PPTX
The New York Times: Sustainable Systems, Powered by Python
PPTX
Flask and Introduction to web frameworks
PDF
Python, do you even async?
Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면
Python performance engineering in 2017
Asynchronous Frameworks.pptx
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Asynchronous Python with Twisted
Async programming and python
Async Web Frameworks in Python
Scaling Uber
Building Web APIs that Scale
BIW15: Python in the Cloud: Django and Flaks
python_development.pptx
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
Realtime Apps with Django
Scaling Django with gevent
Rapid Web Development with Python for Absolute Beginners
Understanding PyPy - PyConEs 14
Using Coroutines to Create Efficient, High-Concurrency Web Applications
The New York Times: Sustainable Systems, Powered by Python
Flask and Introduction to web frameworks
Python, do you even async?
Ad

Recently uploaded (20)

PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Spectroscopy.pptx food analysis technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Approach and Philosophy of On baking technology
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Cloud computing and distributed systems.
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
cuic standard and advanced reporting.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Empathic Computing: Creating Shared Understanding
Spectroscopy.pptx food analysis technology
Unlocking AI with Model Context Protocol (MCP)
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Approach and Philosophy of On baking technology
Chapter 3 Spatial Domain Image Processing.pdf
Machine learning based COVID-19 study performance prediction
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Reach Out and Touch Someone: Haptics and Empathic Computing
Dropbox Q2 2025 Financial Results & Investor Presentation
MIND Revenue Release Quarter 2 2025 Press Release
Big Data Technologies - Introduction.pptx
Cloud computing and distributed systems.
MYSQL Presentation for SQL database connectivity
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Network Security Unit 5.pdf for BCA BBA.
cuic standard and advanced reporting.pdf

Sanic: Experience Blazing Fast Python Web Framework

  • 1. SANIC EXPERIENCE BLAZING FAST PYTHON WEB FRAMEWORK PyCon ID Surabaya, Indonesia 2017
  • 2. Fauzan Erich Emmerling VP Integration @ prismapp.io @femmerling (GitHub, twitter, IG) pythonista since 2010 http://www.emfeld.com currently active in Python-ID Jogja
  • 4. WHY WAS PYTHON SLOW ▸ It’s interpreted ▸ It’s dynamically typed ▸ In python 2.x concurrency is a big mess ▸ Async is hard ▸ The notoriously famous GIL
  • 6. WHAT HAPPENS AT 3.X?? ▸ Still interpreted ▸ Better performance ▸ Still dynamically typed but now comes with type hinting ▸ Since 3.5 async is a walk in the park ▸ GIL is still there but Asyncio saves us, BIG TIME
  • 8. “a full, drop-in replacement for the asyncio event loop. uvloop is written in Cython and built on top of libuv. uvloop makes asyncio fast. In fact, it is at least 2x faster than nodejs, gevent, as well as any other Python asynchronous framework” Yuri Selivanov WHAT IS UVLOOP
  • 10. DUDE, IT’S MY TURN NOW!!! GOTTA GO FAST!!!
  • 12. WHAT IS IT? ▸ a python 3.5+ micro framework thats written to go fast ▸ small and contained ▸ inspired a lot by Flask, that’s why I ❤ it ▸ accepts async handlers so the we can use shiny async/ await syntax
  • 13. WHY USE SANIC? ▸ super easy to learn ▸ can be a micro framework up to a full monolith, just like flask ▸ async capabilities, better concurrency ▸ performs like that of Go or NodeJS but with better syntax ▸ great docs ▸ extensions are growing ▸ however currently no wheel for uvloop on windows yet ▸ set your own workers
  • 14. FEATURES ▸ async request handling ▸ http and websocket ▸ class based views ▸ blueprints ▸ configurations ▸ cookies
  • 15. HOW TO START USING IT? ▸ make sure you have python 3.5+ ▸ $ pip install sanic ▸ start coding
  • 16. DOES THIS RING A BELL? from sanic import Sanic from sanic import response as sanic_response from services import get_image_content, get_mimetype, set_expiry_headers app = Sanic(__name__) @app.route('/<image_url:path>') async def index(request, image_url): content_type = get_mimetype(image_url=image_url) headers = set_expiry_headers() async def get_image(response): content = await get_image_content(image_url) response.write(content) return sanic_response.stream( get_image, content_type=content_type, headers=headers) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True, workers=4)
  • 17. SOME BEST PRACTICES use factory pattern for apps: def create_app(): app = Sanic(__name__) init_exception_handling(app=app) app.add_route( handle_transcript, '/v2/conversations_transcript', methods=['POST']) app.add_route( handle_ack, '/v2/conversations_transcript', methods=['OPTIONS']) return app
  • 18. SOME BEST PRACTICES map exceptions def init_handled_exceptions(app): if app is None: raise AppError('`app` is required') @app.exception(AppError) def handled_exceptions(request, exception): error = create_response( payload=exception.to_dict(), status_code=exception.status_code) logger.error( exception.message, error=error) return response.json( error.payload, headers=error.headers, status=exception.status_code)
  • 19. SOME BEST PRACTICES separate handlers from route for easier testing from app.handlers.transcript import handle_transcript app = Sanic(__name__) init_exception_handling(app=app) app.add_route( handle_transcript, '/v2/conversations_transcript', methods=['POST'])
  • 20. SANIC IN REAL LIFE ▸ Scarlett Project ▸ Translates image streams from http to https ▸ Handles around 200 req/s per worker ▸ Runs behind Gunicorn with 4 workers running ▸ Only need 1 docker container for now ▸ Average response time is 10ms ▸ Developed in 1.5 hours
  • 21. SOMETIMES YOU GOTTA RUN BEFORE YOU CAN WALK Tony Stark OUR MANTRA AT PRISM
  • 22. QUESTIONS? you can also ask on: twitter: @femmerling mail: erich@emfeld.com
  • 23. THANK YOU in case you’re wondering.. Yes, we’re hiring!!! fauzan@prismapp.io