SlideShare una empresa de Scribd logo
1 de 28
Descargar para leer sin conexión
Sanic Microservice
Microservices architecture
Who am I?
mymusictaste.com
Person who wants to be crazy 

about something, like a geek
DevOps
Catlover
Instagram @our_durian
The Takeaway

 





AsyncIO Sanic
01 Monolithic vs Microservices
02 AsyncIO & Sanic
03 Transformation to Insanic
04 Challenges & Plan
Contents
01 Monolithic vs Microservices
. MMT .
Microservices



 



- 

- 

- 

-
A collection of loosely coupled services
Parallelizes development by small autonomous

teams to development
scale their respective services independently
polyglot
developed by Python
developed by Go
more resilient to

architecture erosion
easier to understand,

develop, test
Microservices
Container & orchestration
Continous deployment
=> => &
Microservices
Don’t even consider
microservices
unless you have a
system that’s too
complex to manage
as monolithic
: https://www.martinfowler.com/bliki/MicroservicePremium.html
Why did we move to microservices architecture?
Django
Microservices
Acrchitecture
02 AsyncIO vs Sanic
python 3.4 standard library AsyncIO . 

AsyncIO Web framework Sanic .
This module provides infrastructure
for writing single-threaded
concurrent code using coroutines,
multiplexing I/O access over socket
and other resources, running
network clients and servers, and
other related primitives.
import asyncio
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
return x + y
async def print_sum(x, y):
result = await compute(x, y)
print("%s + %s = %s" % (x, y, result))
loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()
AsyncIO
import asyncio
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
return x + y
async def print_sum(x, y):
result = await compute(x, y)
print("%s + %s = %s" % (x, y,
result))
loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()
AsyncIO
- results = await asyncio.gather(*tasks)
- await asyncio.wait(futures, return_when=FIRST_COMPLETED)
- asyncio.ensure_future(task)
- future.add_done_callback(callback)
AsyncIO
AsyncIO
I/O bound
CPU bound
A B A
single-threaded concurrent code
B
cooperative multitasking
A B
A
what if B is not cooperative?
“So microservices use a distributed system to improve modularity. But distributed
software has a major disadvantage, the fact that it's distributed.

The second mitigation is to use asynchrony. If make six asynchronous calls in parallel
you're now only as slow as the slowest call instead of the sum of their latencies. This can
be a big performance gain, but comes at another cognitive cost. Asynchronous
programming is hard: hard to get right, and much harder to debug. But most microservice
stories I've heard need asynchrony in order to get acceptable performance.”
Martin Fowler
SANIC
- Sanic is a Flask-like Python 3.5+ web server
https://github.com/channelcat/sanic
from sanic import Sanic
from sanic.response import json
app = Sanic()
@app.route('/')
async def test(request):
return json({'hello': 'world'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)
SANIC
sanic/server.py
class HttpProtocol(asyncio.Protocol)
def connection_made(self, transport):

def connection_lost(self, exc):

def data_received(self, data):

server_coroutine = loop.create_server(

server,

host,

port,

ssl=ssl,

reuse_port=reuse_port,

sock=sock,

backlog=backlog

)

http_server = loop.run_until_complete(server_coroutine)

loop.run_forever()

Create TCP server
self.transport.write(

response.output(

self.request.version, keep_alive,

self.keep_alive_timeout))
03 Transformation to Insanic
MMT Sanic web framework . MMT
web framework , .
Sanic Insanic
INSANIC
Settings
Settings for Insanic differ a lot from sanic's config pattern. While implementing, I found the need to access the settings
from modules where the sanic application was not accessable. Thus the settings object in insanic takes a lot from django's
settings configuration where the settings object is a single instantiated config object that can be imported anywhere.

In addition to sanic's config object, where it is usually instantiated and attached to sanic's application instance, the
settings object in insanic is a lazy loaded with dependencies on the service name.
Settings Loading
There are several steps/places the settings object loads settings from.

1. Loads the global_settings.py from within insanic. These are the default settings that insanic needs to run.

2. Then with the SERVICE_VARIABLE, tries to load config.py from within the project.

3. common settings are loaded from VAULT

4. service settings are loaded from VAULT

5. Any environment variables are loaded. Must be prefixed with set prefix. (default its INSANIC)

INSANICINSANIC
View Authentication and Permission Handling
Insanic takes the original views from sanic and modifies them to handle authentication and permission handling. A lot of
patterns were taken from Django Rest Framework. The bulk of the updates is through the dispatch_request method. To
register authentication and permissions, we must first create or use the general authentication and permission provided
by insanic
Views
# views.py
from sanic.response import json
from insanic import permissions, authentication
from insanic.views import InsanicView
class GottaGoFastView(InsanicView):
permission_classes = (permissions.AllowAny,)
authentication_classes = (authentication.JSONWebTokenAuthentication, )
async def get(self, request, *args, **kwargs):
return json({"how fast?": "insanely fast"})
Permissions
- AllowAny

- IsAuthenticated

- IsAdminUser

- IsAuthenticatedOrReadOnly

- IsOwnerOrAdmin

- IsServiceOnly
INSANIC
Request Object
Apart from the request attributes provided by the sanic request object, insanic creates additional attributes with a lot of
inspiration from Django-REST-Framework but with async compatibilities.
Request Parsing Authentication
.data
.query_params
.user
user = await request.user
.service
service = await request.service
INSANIC
Inter Service Communications
One of the core additional features of insanic, that differentiates it from other frameworks, is the Service object.
Service Features
• Resolve address and endpoint construction

• Header preparation and injections for https requests

• Error handling

• Circuit Breaker patching

• Response handling

from insanic.loading import get_service
ArtistService = get_service('artist')
response, status_code = await ArtistService.http_dispatch('GET', '/api/v1/artists/',
query_params={"query": "insanic"},
include_status_code=True)
INSANIC
Pytest helpers
Public Facing API Gateway Registration
Tracing with AWS X-Ray service
Addition of these features are ongoing

- Contract test

- OpenAPI 3.0 specification document generation

- inter service communication with RPC option
INSANIC
04 Challenges & Plan
AsyncIO Sanic Microservices architecture
. , .
In… series / wrapper for asyncio
aiohttp
Asynchronous HTTP client/server for asyncio
aioelasticsearch
elasticsearch-py wrapper for asyncio
asyncpg
A fast PostgreSQL database client library
aioredis
Asyncio Redis support
InPynamoDB
This transforms PynamoDB’s basic methods working
asynchronously used  aiobotocore.
Infuse
This is heavily based on pybreaker. For full
documentation refer to pybreaker. What is different from
pybreaker is that it includes asynchronous storage
options.
async-python-mailchimp-api
A straighforward python asynchronous client for v3 of
MailChimp API using aiohttp >= 3.0.0. This Project
forked from python-mailchimp
CHALLENGES
CHALLENGES
Where you are
PLAN
1. Insanic
(2018. 8. 6. Release)
2. Insanic Open source
Main developer for Insanic

Kwang Jin Kim
https://github.com/MyMusicTaste/recruit
We are hiring!

Más contenido relacionado

La actualidad más candente

Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Hermann Burgmeier
 

La actualidad más candente (20)

J2EE Security with Apache SHIRO
J2EE Security with Apache SHIROJ2EE Security with Apache SHIRO
J2EE Security with Apache SHIRO
 
스프링 시큐리티로 시작하는 웹 어플리케이션 보안 _강사준비 스터디 버전
스프링 시큐리티로 시작하는 웹 어플리케이션 보안 _강사준비 스터디 버전스프링 시큐리티로 시작하는 웹 어플리케이션 보안 _강사준비 스터디 버전
스프링 시큐리티로 시작하는 웹 어플리케이션 보안 _강사준비 스터디 버전
 
Modern authentication in Sling with Openid Connect and Keycloak - Adapt.to 20...
Modern authentication in Sling with Openid Connect and Keycloak - Adapt.to 20...Modern authentication in Sling with Openid Connect and Keycloak - Adapt.to 20...
Modern authentication in Sling with Openid Connect and Keycloak - Adapt.to 20...
 
How to customize Spring Boot?
How to customize Spring Boot?How to customize Spring Boot?
How to customize Spring Boot?
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
API Security & Federation Patterns - Francois Lascelles, Chief Architect, Lay...
API Security & Federation Patterns - Francois Lascelles, Chief Architect, Lay...API Security & Federation Patterns - Francois Lascelles, Chief Architect, Lay...
API Security & Federation Patterns - Francois Lascelles, Chief Architect, Lay...
 
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
 
I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...
 
ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2
 
Java Security Framework's
Java Security Framework'sJava Security Framework's
Java Security Framework's
 
SIngle Sign On with Keycloak
SIngle Sign On with KeycloakSIngle Sign On with Keycloak
SIngle Sign On with Keycloak
 
Octopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EEOctopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EE
 
Cloud Native Identity with SPIFFE
Cloud Native Identity with SPIFFECloud Native Identity with SPIFFE
Cloud Native Identity with SPIFFE
 
Enabling Cloud Native Security with OAuth2 and Multi-Tenant UAA
Enabling Cloud Native Security with OAuth2 and Multi-Tenant UAA Enabling Cloud Native Security with OAuth2 and Multi-Tenant UAA
Enabling Cloud Native Security with OAuth2 and Multi-Tenant UAA
 
It and ej
It and ejIt and ej
It and ej
 
Api security-eic-prabath
Api security-eic-prabathApi security-eic-prabath
Api security-eic-prabath
 
Spring4 security
Spring4 securitySpring4 security
Spring4 security
 
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
 
What's New in spring-security-core 2.0
What's New in spring-security-core 2.0What's New in spring-security-core 2.0
What's New in spring-security-core 2.0
 
Enterprise Security mit Spring Security
Enterprise Security mit Spring SecurityEnterprise Security mit Spring Security
Enterprise Security mit Spring Security
 

Similar a Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면

Behind the scenes of Scaleway Functions : when Kubernetes meets our products
Behind the scenes of Scaleway Functions : when Kubernetes meets our productsBehind the scenes of Scaleway Functions : when Kubernetes meets our products
Behind the scenes of Scaleway Functions : when Kubernetes meets our products
Scaleway
 

Similar a Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면 (20)

Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014
 
Containerizing your Security Operations Center
Containerizing your Security Operations CenterContainerizing your Security Operations Center
Containerizing your Security Operations Center
 
Private Apps in the Public Cloud - DevConTLV March 2016
Private Apps in the Public Cloud - DevConTLV March 2016Private Apps in the Public Cloud - DevConTLV March 2016
Private Apps in the Public Cloud - DevConTLV March 2016
 
CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0
CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0
CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0
 
Servlet to Spring: Internal Understanding
Servlet to Spring: Internal UnderstandingServlet to Spring: Internal Understanding
Servlet to Spring: Internal Understanding
 
Smart Services & Smart Clients - How Microservices Change the Way You Build a...
Smart Services & Smart Clients - How Microservices Change the Way You Build a...Smart Services & Smart Clients - How Microservices Change the Way You Build a...
Smart Services & Smart Clients - How Microservices Change the Way You Build a...
 
Behind the scenes of Scaleway Functions : when Kubernetes meets our products
Behind the scenes of Scaleway Functions : when Kubernetes meets our productsBehind the scenes of Scaleway Functions : when Kubernetes meets our products
Behind the scenes of Scaleway Functions : when Kubernetes meets our products
 
Maxim Salnikov - Service Worker: taking the best from the past experience for...
Maxim Salnikov - Service Worker: taking the best from the past experience for...Maxim Salnikov - Service Worker: taking the best from the past experience for...
Maxim Salnikov - Service Worker: taking the best from the past experience for...
 
Build12 factorappusingmp
Build12 factorappusingmpBuild12 factorappusingmp
Build12 factorappusingmp
 
Api Gateway
Api GatewayApi Gateway
Api Gateway
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
 
[PL] Code Europe 2016 - Python and Microsoft Azure
[PL] Code Europe 2016 - Python and Microsoft Azure[PL] Code Europe 2016 - Python and Microsoft Azure
[PL] Code Europe 2016 - Python and Microsoft Azure
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
Spring boot microservice metrics monitoring
Spring boot   microservice metrics monitoringSpring boot   microservice metrics monitoring
Spring boot microservice metrics monitoring
 
Spring Boot - Microservice Metrics Monitoring
Spring Boot - Microservice Metrics MonitoringSpring Boot - Microservice Metrics Monitoring
Spring Boot - Microservice Metrics Monitoring
 
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkEasy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
 
Blazor, lo sapevi che...
Blazor, lo sapevi che...Blazor, lo sapevi che...
Blazor, lo sapevi che...
 
Open stack ocata summit enabling aws lambda-like functionality with openstac...
Open stack ocata summit  enabling aws lambda-like functionality with openstac...Open stack ocata summit  enabling aws lambda-like functionality with openstac...
Open stack ocata summit enabling aws lambda-like functionality with openstac...
 

Último

Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
Kayode Fayemi
 
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
amilabibi1
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
raffaeleoman
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New Nigeria
Kayode Fayemi
 

Último (18)

AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdfAWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
 
Dreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video TreatmentDreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video Treatment
 
Dreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio IIIDreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio III
 
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verifiedSector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
 
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdfThe workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
 
Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
 
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar Training
 
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
 
My Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle BaileyMy Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle Bailey
 
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510
 
Causes of poverty in France presentation.pptx
Causes of poverty in France presentation.pptxCauses of poverty in France presentation.pptx
Causes of poverty in France presentation.pptx
 
ICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdfICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdf
 
Digital collaboration with Microsoft 365 as extension of Drupal
Digital collaboration with Microsoft 365 as extension of DrupalDigital collaboration with Microsoft 365 as extension of Drupal
Digital collaboration with Microsoft 365 as extension of Drupal
 
lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New Nigeria
 

Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면

  • 2. Who am I? mymusictaste.com Person who wants to be crazy about something, like a geek DevOps Catlover Instagram @our_durian
  • 4. 01 Monolithic vs Microservices 02 AsyncIO & Sanic 03 Transformation to Insanic 04 Challenges & Plan Contents
  • 5. 01 Monolithic vs Microservices . MMT .
  • 6. Microservices - - - - A collection of loosely coupled services Parallelizes development by small autonomous teams to development scale their respective services independently polyglot developed by Python developed by Go more resilient to architecture erosion easier to understand, develop, test
  • 8. Microservices Don’t even consider microservices unless you have a system that’s too complex to manage as monolithic : https://www.martinfowler.com/bliki/MicroservicePremium.html
  • 9. Why did we move to microservices architecture? Django Microservices Acrchitecture
  • 10. 02 AsyncIO vs Sanic python 3.4 standard library AsyncIO . AsyncIO Web framework Sanic .
  • 11. This module provides infrastructure for writing single-threaded concurrent code using coroutines, multiplexing I/O access over socket and other resources, running network clients and servers, and other related primitives. import asyncio async def compute(x, y): print("Compute %s + %s ..." % (x, y)) await asyncio.sleep(1.0) return x + y async def print_sum(x, y): result = await compute(x, y) print("%s + %s = %s" % (x, y, result)) loop = asyncio.get_event_loop() loop.run_until_complete(print_sum(1, 2)) loop.close() AsyncIO
  • 12. import asyncio async def compute(x, y): print("Compute %s + %s ..." % (x, y)) await asyncio.sleep(1.0) return x + y async def print_sum(x, y): result = await compute(x, y) print("%s + %s = %s" % (x, y, result)) loop = asyncio.get_event_loop() loop.run_until_complete(print_sum(1, 2)) loop.close() AsyncIO
  • 13. - results = await asyncio.gather(*tasks) - await asyncio.wait(futures, return_when=FIRST_COMPLETED) - asyncio.ensure_future(task) - future.add_done_callback(callback) AsyncIO
  • 14. AsyncIO I/O bound CPU bound A B A single-threaded concurrent code B cooperative multitasking A B A what if B is not cooperative?
  • 15. “So microservices use a distributed system to improve modularity. But distributed software has a major disadvantage, the fact that it's distributed. The second mitigation is to use asynchrony. If make six asynchronous calls in parallel you're now only as slow as the slowest call instead of the sum of their latencies. This can be a big performance gain, but comes at another cognitive cost. Asynchronous programming is hard: hard to get right, and much harder to debug. But most microservice stories I've heard need asynchrony in order to get acceptable performance.” Martin Fowler
  • 16. SANIC - Sanic is a Flask-like Python 3.5+ web server https://github.com/channelcat/sanic from sanic import Sanic from sanic.response import json app = Sanic() @app.route('/') async def test(request): return json({'hello': 'world'}) if __name__ == '__main__': app.run(host='0.0.0.0', port=8000)
  • 17. SANIC sanic/server.py class HttpProtocol(asyncio.Protocol) def connection_made(self, transport): def connection_lost(self, exc): def data_received(self, data): server_coroutine = loop.create_server( server, host, port, ssl=ssl, reuse_port=reuse_port, sock=sock, backlog=backlog ) http_server = loop.run_until_complete(server_coroutine) loop.run_forever() Create TCP server self.transport.write( response.output( self.request.version, keep_alive, self.keep_alive_timeout))
  • 18. 03 Transformation to Insanic MMT Sanic web framework . MMT web framework , .
  • 20. Settings Settings for Insanic differ a lot from sanic's config pattern. While implementing, I found the need to access the settings from modules where the sanic application was not accessable. Thus the settings object in insanic takes a lot from django's settings configuration where the settings object is a single instantiated config object that can be imported anywhere. In addition to sanic's config object, where it is usually instantiated and attached to sanic's application instance, the settings object in insanic is a lazy loaded with dependencies on the service name. Settings Loading There are several steps/places the settings object loads settings from. 1. Loads the global_settings.py from within insanic. These are the default settings that insanic needs to run. 2. Then with the SERVICE_VARIABLE, tries to load config.py from within the project. 3. common settings are loaded from VAULT 4. service settings are loaded from VAULT 5. Any environment variables are loaded. Must be prefixed with set prefix. (default its INSANIC) INSANICINSANIC
  • 21. View Authentication and Permission Handling Insanic takes the original views from sanic and modifies them to handle authentication and permission handling. A lot of patterns were taken from Django Rest Framework. The bulk of the updates is through the dispatch_request method. To register authentication and permissions, we must first create or use the general authentication and permission provided by insanic Views # views.py from sanic.response import json from insanic import permissions, authentication from insanic.views import InsanicView class GottaGoFastView(InsanicView): permission_classes = (permissions.AllowAny,) authentication_classes = (authentication.JSONWebTokenAuthentication, ) async def get(self, request, *args, **kwargs): return json({"how fast?": "insanely fast"}) Permissions - AllowAny - IsAuthenticated - IsAdminUser - IsAuthenticatedOrReadOnly - IsOwnerOrAdmin - IsServiceOnly INSANIC
  • 22. Request Object Apart from the request attributes provided by the sanic request object, insanic creates additional attributes with a lot of inspiration from Django-REST-Framework but with async compatibilities. Request Parsing Authentication .data .query_params .user user = await request.user .service service = await request.service INSANIC
  • 23. Inter Service Communications One of the core additional features of insanic, that differentiates it from other frameworks, is the Service object. Service Features • Resolve address and endpoint construction • Header preparation and injections for https requests • Error handling • Circuit Breaker patching • Response handling from insanic.loading import get_service ArtistService = get_service('artist') response, status_code = await ArtistService.http_dispatch('GET', '/api/v1/artists/', query_params={"query": "insanic"}, include_status_code=True) INSANIC
  • 24. Pytest helpers Public Facing API Gateway Registration Tracing with AWS X-Ray service Addition of these features are ongoing - Contract test - OpenAPI 3.0 specification document generation - inter service communication with RPC option INSANIC
  • 25. 04 Challenges & Plan AsyncIO Sanic Microservices architecture . , .
  • 26. In… series / wrapper for asyncio aiohttp Asynchronous HTTP client/server for asyncio aioelasticsearch elasticsearch-py wrapper for asyncio asyncpg A fast PostgreSQL database client library aioredis Asyncio Redis support InPynamoDB This transforms PynamoDB’s basic methods working asynchronously used  aiobotocore. Infuse This is heavily based on pybreaker. For full documentation refer to pybreaker. What is different from pybreaker is that it includes asynchronous storage options. async-python-mailchimp-api A straighforward python asynchronous client for v3 of MailChimp API using aiohttp >= 3.0.0. This Project forked from python-mailchimp CHALLENGES
  • 28. PLAN 1. Insanic (2018. 8. 6. Release) 2. Insanic Open source Main developer for Insanic Kwang Jin Kim https://github.com/MyMusicTaste/recruit We are hiring!