SlideShare a Scribd company logo
1 of 28
Download to read offline
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!

More Related Content

What's hot

J2EE Security with Apache SHIRO
J2EE Security with Apache SHIROJ2EE Security with Apache SHIRO
J2EE Security with Apache SHIROCygnet Infotech
 
스프링 시큐리티로 시작하는 웹 어플리케이션 보안 _강사준비 스터디 버전
스프링 시큐리티로 시작하는 웹 어플리케이션 보안 _강사준비 스터디 버전스프링 시큐리티로 시작하는 웹 어플리케이션 보안 _강사준비 스터디 버전
스프링 시큐리티로 시작하는 웹 어플리케이션 보안 _강사준비 스터디 버전HyungTae Lim
 
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...Ioan Eugen Stan
 
How to customize Spring Boot?
How to customize Spring Boot?How to customize Spring Boot?
How to customize Spring Boot?GilWon Oh
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring SecurityDzmitry Naskou
 
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...CA API Management
 
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
 
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...Joris Kuipers
 
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 OAuth2Rodrigo Cândido da Silva
 
SIngle Sign On with Keycloak
SIngle Sign On with KeycloakSIngle Sign On with Keycloak
SIngle Sign On with KeycloakJulien Pivotto
 
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 EERudy De Busscher
 
Cloud Native Identity with SPIFFE
Cloud Native Identity with SPIFFECloud Native Identity with SPIFFE
Cloud Native Identity with SPIFFEPrabath Siriwardena
 
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 Will Tran
 
Api security-eic-prabath
Api security-eic-prabathApi security-eic-prabath
Api security-eic-prabathWSO2
 
Spring4 security
Spring4 securitySpring4 security
Spring4 securitySang Shin
 
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 ...Matt Raible
 
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.0Burt Beckwith
 
Enterprise Security mit Spring Security
Enterprise Security mit Spring SecurityEnterprise Security mit Spring Security
Enterprise Security mit Spring SecurityMike Wiesner
 

What's hot (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 to Pycon Korea 2018-Sanic을 활용하여 Microservice 구축하기-이재면

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 PickinGavin 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 2014Lou Sacco
 
Containerizing your Security Operations Center
Containerizing your Security Operations CenterContainerizing your Security Operations Center
Containerizing your Security Operations CenterJimmy Mesta
 
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 2016Issac Goldstand
 
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.0Krishna-Kumar
 
Servlet to Spring: Internal Understanding
Servlet to Spring: Internal UnderstandingServlet to Spring: Internal Understanding
Servlet to Spring: Internal UnderstandingKnoldus Inc.
 
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...Neil Mansilla
 
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 productsScaleway
 
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...Codemotion
 
Build12 factorappusingmp
Build12 factorappusingmpBuild12 factorappusingmp
Build12 factorappusingmpEmily Jiang
 
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 ContainerDiego Lewin
 
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...Christian Schneider
 
[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 AzureMichał Smereczyński
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsJim Jeffers
 
Spring boot microservice metrics monitoring
Spring boot   microservice metrics monitoringSpring boot   microservice metrics monitoring
Spring boot microservice metrics monitoringOracle Korea
 
Spring Boot - Microservice Metrics Monitoring
Spring Boot - Microservice Metrics MonitoringSpring Boot - Microservice Metrics Monitoring
Spring Boot - Microservice Metrics MonitoringDonghuKIM2
 
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 FrameworkInexture Solutions
 
Blazor, lo sapevi che...
Blazor, lo sapevi che...Blazor, lo sapevi che...
Blazor, lo sapevi che...Andrea Dottor
 
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...Shaun Murakami
 

Similar to 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...
 

Recently uploaded

RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATIONRACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATIONRachelAnnTenibroAmaz
 
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRRINDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRRsarwankumar4524
 
Quality by design.. ppt for RA (1ST SEM
Quality by design.. ppt for  RA (1ST SEMQuality by design.. ppt for  RA (1ST SEM
Quality by design.. ppt for RA (1ST SEMCharmi13
 
Engaging Eid Ul Fitr Presentation for Kindergartners.pptx
Engaging Eid Ul Fitr Presentation for Kindergartners.pptxEngaging Eid Ul Fitr Presentation for Kindergartners.pptx
Engaging Eid Ul Fitr Presentation for Kindergartners.pptxAsifArshad8
 
The 3rd Intl. Workshop on NL-based Software Engineering
The 3rd Intl. Workshop on NL-based Software EngineeringThe 3rd Intl. Workshop on NL-based Software Engineering
The 3rd Intl. Workshop on NL-based Software EngineeringSebastiano Panichella
 
Early Modern Spain. All about this period
Early Modern Spain. All about this periodEarly Modern Spain. All about this period
Early Modern Spain. All about this periodSaraIsabelJimenez
 
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...Henrik Hanke
 
Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170Escort Service
 
Simulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with AerialistSimulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with AerialistSebastiano Panichella
 
miladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptxmiladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptxCarrieButtitta
 
PHYSICS PROJECT BY MSC - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC  - NANOTECHNOLOGYPHYSICS PROJECT BY MSC  - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC - NANOTECHNOLOGYpruthirajnayak525
 
The Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism PresentationThe Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism PresentationNathan Young
 
Event 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptxEvent 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptxaryanv1753
 
Dutch Power - 26 maart 2024 - Henk Kras - Circular Plastics
Dutch Power - 26 maart 2024 - Henk Kras - Circular PlasticsDutch Power - 26 maart 2024 - Henk Kras - Circular Plastics
Dutch Power - 26 maart 2024 - Henk Kras - Circular PlasticsDutch Power
 
SBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation TrackSBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation TrackSebastiano Panichella
 
Genshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptxGenshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptxJohnree4
 
Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸mathanramanathan2005
 
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.KathleenAnnCordero2
 
Chizaram's Women Tech Makers Deck. .pptx
Chizaram's Women Tech Makers Deck.  .pptxChizaram's Women Tech Makers Deck.  .pptx
Chizaram's Women Tech Makers Deck. .pptxogubuikealex
 
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...漢銘 謝
 

Recently uploaded (20)

RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATIONRACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
 
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRRINDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRR
 
Quality by design.. ppt for RA (1ST SEM
Quality by design.. ppt for  RA (1ST SEMQuality by design.. ppt for  RA (1ST SEM
Quality by design.. ppt for RA (1ST SEM
 
Engaging Eid Ul Fitr Presentation for Kindergartners.pptx
Engaging Eid Ul Fitr Presentation for Kindergartners.pptxEngaging Eid Ul Fitr Presentation for Kindergartners.pptx
Engaging Eid Ul Fitr Presentation for Kindergartners.pptx
 
The 3rd Intl. Workshop on NL-based Software Engineering
The 3rd Intl. Workshop on NL-based Software EngineeringThe 3rd Intl. Workshop on NL-based Software Engineering
The 3rd Intl. Workshop on NL-based Software Engineering
 
Early Modern Spain. All about this period
Early Modern Spain. All about this periodEarly Modern Spain. All about this period
Early Modern Spain. All about this period
 
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...
 
Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170
 
Simulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with AerialistSimulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with Aerialist
 
miladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptxmiladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptx
 
PHYSICS PROJECT BY MSC - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC  - NANOTECHNOLOGYPHYSICS PROJECT BY MSC  - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC - NANOTECHNOLOGY
 
The Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism PresentationThe Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism Presentation
 
Event 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptxEvent 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptx
 
Dutch Power - 26 maart 2024 - Henk Kras - Circular Plastics
Dutch Power - 26 maart 2024 - Henk Kras - Circular PlasticsDutch Power - 26 maart 2024 - Henk Kras - Circular Plastics
Dutch Power - 26 maart 2024 - Henk Kras - Circular Plastics
 
SBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation TrackSBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation Track
 
Genshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptxGenshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptx
 
Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸
 
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.
 
Chizaram's Women Tech Makers Deck. .pptx
Chizaram's Women Tech Makers Deck.  .pptxChizaram's Women Tech Makers Deck.  .pptx
Chizaram's Women Tech Makers Deck. .pptx
 
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
 

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!