SlideShare a Scribd company logo
1 of 122
Download to read offline
A Crash Course on
Serverless Applications in Python
James Saryerwinnie
@jsaryer
Serverless Computing Overview
Serverless Architecture
Serverless Application in Python
Serverless Computing Overview
Serverless Architecture
Serverless Application in Python
Serverless Computing Overview
Build and run applications without thinking about servers
No servers to provision,
scale, or manage
Flexible scaling Built-in availability and fault tolerance
Serverless Computing
AWS Lambda
Run code without thinking about servers.
Pay for only the compute time you consume.
Lambda takes care of everything required to run and
scale your code with high availability.
AWS Lambda Function
def handler(event, context):
return 'hello world!'
def handler(event, context):
return 'hello world!'
AWS Lambda Function
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
2 event - data about what triggered invocation
context - runtime information about your function
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
app.py
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
app.py
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
app.py
$ python
>>> import app
>>> app.handler(event={}, context=None)
'hello world!'
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
app.py
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
app.py
$ pip install awscli
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
app.py
$ pip install awscli
$ aws configure
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
app.py
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
app.py
$ aws lambda create-function --function-name hello --handler app.handler --zip-file ...
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
app.py
$ aws lambda create-function --function-name hello --handler app.handler --zip-file ...
$ aws lambda invoke --function-name hello
def handler(event, context):
return 'hello world!'
AWS Lambda Function
1 Define python function
3 Return value sent back as response
2 event - data about what triggered invocation
context - runtime information about your function
app.py
$ aws lambda create-function --function-name hello --handler app.handler --zip-file ...
$ aws lambda invoke --function-name hello
hello world!
def handler(event, context):
return event['foo'].upper()
AWS Lambda Function Input
app.py
def handler(event, context):
return event['foo'].upper()
AWS Lambda Function Input
app.py
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
def handler(event, context):
return event['foo'].upper()
AWS Lambda Function Input
app.py
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
def handler(event, context):
return event['foo'].upper()
AWS Lambda Function Input
app.py
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
BAR
def handler(event, context):
return event['foo'].upper()
AWS Lambda Function Input
app.py
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
BAR
$ aws lambda invoke --function-name hello --payload '{"foo": "baz"}'
def handler(event, context):
return event['foo'].upper()
AWS Lambda Function Input
app.py
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
BAR
$ aws lambda invoke --function-name hello --payload '{"foo": "baz"}'
BAZ
AWS Lambda Function Invocation
https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html
https://youtu.be/oQFORsso2go?t=422
AWS Lambda Function Invocation
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html
https://youtu.be/oQFORsso2go?t=422
AWS Lambda Function Invocation
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
Download your code
https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html
https://youtu.be/oQFORsso2go?t=422
AWS Lambda Function Invocation
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
Download your code Start new container
https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html
https://youtu.be/oQFORsso2go?t=422
AWS Lambda Function Invocation
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
Download your code Start new container Bootstrap the runtime
https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html
https://youtu.be/oQFORsso2go?t=422
AWS Lambda Function Invocation
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
Start your codeDownload your code Start new container Bootstrap the runtime
https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html
https://youtu.be/oQFORsso2go?t=422
AWS Lambda Function Invocation
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
Start your codeDownload your code Start new container Bootstrap the runtime
Cold Start
https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html
https://youtu.be/oQFORsso2go?t=422
AWS Lambda Function Invocation
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
Start your codeDownload your code Start new container Bootstrap the runtime
Cold Start Warm Start
https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html
https://youtu.be/oQFORsso2go?t=422
AWS Lambda Function Invocation
$ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
Start your codeDownload your code Start new container Bootstrap the runtime
Cold Start Warm Start
$ aws lambda invoke --function-name hello --payload '{"foo": "baz"}'
https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html
https://youtu.be/oQFORsso2go?t=422
Focus on your core product instead of
worrying about managing and
operating servers or runtimes.
Serverless Computing Overview
Serverless Architecture
Serverless Application in Python
Serverless Architecture Patterns
Serverless Architecture
Event Trigger Lambda Services
Amazon API Gateway
request
Timer
SQS message
Amazon DynamoDB
Amazon S3
Serverless Architecture
Event Trigger Lambda Services
Amazon API Gateway
request
Timer
SQS message
Amazon DynamoDB
Amazon S3Think in terms of events
Serverless Architecture
Event Trigger Lambda Services
API Gateway request
Timer
SQS message
Amazon S3
Amazon DynamoDB
Serverless Architecture
Event Trigger Lambda Services
API Gateway request
Timer
SQS message
Amazon S3
Amazon DynamoDB
Decompose code into separate functions
Synchronous Invocation
Event Trigger Lambda
Manual invocation
$ aws lambda invoke
Synchronous Invocation
Event Trigger Lambda
GET /users
Rest API Request
{"http": "response"}
Async Invocation
Event Trigger Lambda Services
Async Invocation
Event Trigger Lambda Services
Amazon S3
object uploaded
1
Return immediately
2
Async Invocation
Event Trigger Lambda Services
Amazon S3
object uploaded
1
Return immediately
2
Async Invocation
Event Trigger Lambda Services
Amazon S3
object uploaded
1
Event trigger notification3
Return immediately
2
Async Invocation
Event Trigger Lambda Services
Amazon S3
object uploaded
1
Generates thumbnail4
Event trigger notification3
Return immediately
2
Async Invocation
Event Trigger Lambda Services
Amazon S3
object uploaded
1
Generates thumbnail4
Uploads to output bucket
Upload complete
5
Event trigger notification3
Stream/Poll Invocation
Stream Lambda Poller Lambda
Stream/Poll Invocation
Stream Lambda Poller Lambda
Return immediately2
Amazon SQS
message added
1
Stream/Poll Invocation
Stream Lambda Poller Lambda
Return immediately2
Amazon SQS
message added
1
3 Poll for messages
Stream/Poll Invocation
Stream Lambda Poller Lambda
Return immediately2
Amazon SQS
message added
1
3 Poll for messages
Message batch4
Lambda function invoked5
Stream/Poll Invocation
Stream Lambda Poller Lambda
Return immediately2
Amazon SQS
message added
1
3 Poll for messages
Message batch4
Lambda function invoked5
Stream/Poll Invocation
Stream Lambda Poller Lambda
Function execution finished
Return immediately2
Amazon SQS
message added
1
3 Poll for messages
Message batch4
Synchronous Asynchronous Stream
Blocks until response is returned
from Lambda function
Lambda function triggered in
response to an event, decoupled
from event trigger
Lambda service polls for
changes on a stream, invokes
Lambda function with batch of
messages
Synchronous Asynchronous Stream
Blocks until response is returned
from Lambda function
Lambda function triggered in
response to an event, decoupled
from event trigger
Lambda service polls for
changes on a stream, invokes
Lambda function with batch of
messages
$ aws lambda invoke
Amazon API Gateway
request
/users
Synchronous Asynchronous Stream
Blocks until response is returned
from Lambda function
Lambda function triggered in
response to an event, decoupled
from event trigger
Lambda service polls for
changes on a stream, invokes
Lambda function with batch of
messages
Timer
Amazon S3 Object
Amazon SNS Topic
$ aws lambda invoke
Amazon API Gateway
request
/users
Synchronous Asynchronous Stream
Blocks until response is returned
from Lambda function
Lambda function triggered in
response to an event, decoupled
from event trigger
Lambda service polls for
changes on a stream, invokes
Lambda function with batch of
messages
Timer
Amazon S3 Object
Amazon SNS Topic
Amazon SQS Message
Amazon DynamoDB Stream
Amazon Kinesis Stream
$ aws lambda invoke
Amazon API Gateway
request
/users
Serverless Computing Overview
Serverless Architecture
Serverless Application in Python
Serverless Applications in Python
AWS Lambda
def handler(event, context):
return 'hello world!'
Setting up from scratch
AWS Lambda
AWS IAM role
IAM.create_role()IAM.put_role_policy()
Lambda.create_function()
Zip of code and
dependencies
IAM policy
Setting up from scratch
AWS Lambda
AWS IAM role
IAM.create_role()IAM.put_role_policy()
Lambda.create_function()
Zip of code and
dependencies
IAM policy
1
Setting up from scratch
AWS Lambda
AWS IAM role
IAM.create_role()IAM.put_role_policy()
Lambda.create_function()
Zip of code and
dependencies
IAM policy
1
2
Setting up from scratch
AWS Lambda
AWS IAM role
IAM.create_role()IAM.put_role_policy()
Lambda.create_function()
Zip of code and
dependencies
IAM policy
1
2
3
Creating our first Lambda function
Creating our first Lambda function
$ zip -r app.zip app.py1
Creating our first Lambda function
$ zip -r app.zip app.py1
2 $ aws iam create-role 
--role-name MyApp 
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}]
}'
Creating our first Lambda function
$ zip -r app.zip app.py $ aws lambda create-function 
--function-name Hello 
--role-name MyApp 
--runtime python3.6 
--handler app.handler 
--zip-file fileb://app.zip
1
2
3
$ aws iam create-role 
--role-name MyApp 
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}]
}'
Creating our first Lambda function
$ zip -r app.zip app.py $ aws lambda create-function 
--function-name Hello 
--role-name MyApp 
--runtime python3.6 
--handler app.handler 
--zip-file fileb://app.zip
1
2
3
$ aws iam create-role 
--role-name MyApp 
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}]
}'
Creating our first Lambda function
$ zip -r app.zip app.py $ aws lambda create-function 
--function-name Hello 
--role-name MyApp 
--runtime python3.6 
--handler app.handler 
--zip-file fileb://app.zip
1
2
3
$ aws iam create-role 
--role-name MyApp 
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}]
}'
Return immediately
2
Image Resizer
Event Trigger Lambda Services
Amazon S3
object uploaded
1
λEvent trigger notification3
Generates thumbnail4
Uploads to output bucket
Upload complete
5
Amazon S3 AWS Lambda
AWS IAM role
IAM.create_role()IAM.put_role_policy()
Lambda.create_function()S3.put_bucket_notification_configuration()
Zip of code and
dependenciesNotification Config
IAM policy
Lambda.add_permsission(S3)
Image Resizer
Amazon S3 AWS Lambda
AWS IAM role
IAM.create_role()IAM.put_role_policy()
Lambda.create_function()S3.put_bucket_notification_configuration()
Zip of code and
dependenciesNotification Config
IAM policy
Lambda.add_permsission(S3)
Image Resizer
1. Third party packages
2. S3 notification configuration
3. IAM Permissions
Amazon S3 AWS Lambda
AWS IAM role
IAM.create_role()IAM.put_role_policy()
Lambda.create_function()S3.put_bucket_notification_configuration()
Zip of code and
dependenciesNotification Config
IAM policy
Lambda.add_permsission(S3)
Image Resizer
1. Third party packages
2. S3 notification configuration
3. IAM Permissions
Amazon S3 AWS Lambda
AWS IAM role
IAM.create_role()IAM.put_role_policy()
Lambda.create_function()S3.put_bucket_notification_configuration()
Zip of code and
dependenciesNotification Config
IAM policy
Lambda.add_permsission(S3)
Image Resizer
1. Third party packages
2. S3 notification configuration
3. IAM Permissions
Amazon S3 AWS Lambda
AWS IAM role
IAM.create_role()IAM.put_role_policy()
Lambda.create_function()S3.put_bucket_notification_configuration()
Zip of code and
dependenciesNotification Config
IAM policy
Lambda.add_permsission(S3)
Image Resizer
1. Third party packages
2. S3 notification configuration
3. IAM Permissions
AWS Chalice
Python serverless framework for AWS
Quickly create and deploy serverless applications
Integration with many AWS services
Lambda
handler.py
AWS Lambda
Chalice Integration
def hello_world(event, context):
return 'hello world!'
Lambda
chalice
app.py
AWS Lambda
from chalice import Chalice
app = Chalice('helloworld')
@app.lambda_function()
def hello_world(event, context):
return 'hello world!'
Chalice Integration
Lambda
chalice
app.py
AWS Lambda
from chalice import Chalice
app = Chalice('helloworld')
@app.lambda_function()
def hello_world(event, context):
return 'hello world!'
Chalice Integration
1 app defined at module level
Lambda
chalice
app.py
AWS Lambda
from chalice import Chalice
app = Chalice('helloworld')
@app.lambda_function()
def hello_world(event, context):
return 'hello world!'
Chalice Integration
1 app defined at module level
2 One or more decorators to defined resources
Deployment
$ chalice deploy
Creating deployment package.
Updating policy for IAM role: helloworld-dev
Creating lambda function: helloworld-dev-hello_world
Resources deployed:
- Lambda ARN: arn:aws:lambda:us-west-2:1:function:helloworld...
$ chalice invoke -n hello_world
"hello world!"
S3 Image Resizer app.py
import tempfile
import boto3
from PIL import Image
from chalice import Chalice
app = Chalice(app_name='s3resize', debug=True)
s3_client = boto3.client('s3')
@app.on_s3_event(bucket='mybucket',
prefix='images/', suffix='.jpg')
def resize_image(event):
app.log.debug("Resizing image for s3://%s/%s",
event.bucket, event.key)
with tempfile.NamedTemporaryFile('w') as f:
s3_client.download_file(event.bucket, event.key, f.name)
resized_file = f.name + '.thumbnail.jpg'
with open(Image.open(f.name)) as image:
image.thumbnail((256, 256))
image.save(resized_file)
s3_client.upload_file(
filename=resized_file,
bucket='mybucket',
key=f'thumbnails/{event.key.split("/", 1)[1]}'
)
S3 Image Resizer app.py
import tempfile
import boto3
from PIL import Image
from chalice import Chalice
app = Chalice(app_name='s3resize', debug=True)
s3_client = boto3.client('s3')
@app.on_s3_event(bucket='mybucket',
prefix='images/', suffix='.jpg')
def resize_image(event):
app.log.debug("Resizing image for s3://%s/%s",
event.bucket, event.key)
with tempfile.NamedTemporaryFile('w') as f:
s3_client.download_file(event.bucket, event.key, f.name)
resized_file = f.name + '.thumbnail.jpg'
with open(Image.open(f.name)) as image:
image.thumbnail((256, 256))
image.save(resized_file)
s3_client.upload_file(
filename=resized_file,
bucket='mybucket',
key=f'thumbnails/{event.key.split("/", 1)[1]}'
)
3rd party package
with C extension
automatically handled
from requirements.txt
S3 Image Resizer app.py
import tempfile
import boto3
from PIL import Image
from chalice import Chalice
app = Chalice(app_name='s3resize', debug=True)
s3_client = boto3.client('s3')
@app.on_s3_event(bucket='mybucket',
prefix='images/', suffix='.jpg')
def resize_image(event):
app.log.debug("Resizing image for s3://%s/%s",
event.bucket, event.key)
with tempfile.NamedTemporaryFile('w') as f:
s3_client.download_file(event.bucket, event.key, f.name)
resized_file = f.name + '.thumbnail.jpg'
with open(Image.open(f.name)) as image:
image.thumbnail((256, 256))
image.save(resized_file)
s3_client.upload_file(
filename=resized_file,
bucket='mybucket',
key=f'thumbnails/{event.key.split("/", 1)[1]}'
)
Client created in module scope
Only part of cold-start time
S3 Image Resizer app.py
import tempfile
import boto3
from PIL import Image
from chalice import Chalice
app = Chalice(app_name='s3resize', debug=True)
s3_client = boto3.client('s3')
@app.on_s3_event(bucket='mybucket',
prefix='images/', suffix='.jpg')
def resize_image(event):
app.log.debug("Resizing image for s3://%s/%s",
event.bucket, event.key)
with tempfile.NamedTemporaryFile('w') as f:
s3_client.download_file(event.bucket, event.key, f.name)
resized_file = f.name + '.thumbnail.jpg'
with open(Image.open(f.name)) as image:
image.thumbnail((256, 256))
image.save(resized_file)
s3_client.upload_file(
filename=resized_file,
bucket='mybucket',
key=f'thumbnails/{event.key.split("/", 1)[1]}'
)
Client created in module scope
Only part of cold-start time
Start your codeDownload your code Start new container Bootstrap the runtime
Cold Start Warm Start
Module Import
S3 Image Resizer app.py
import tempfile
import boto3
from PIL import Image
from chalice import Chalice
app = Chalice(app_name='s3resize', debug=True)
s3_client = boto3.client('s3')
@app.on_s3_event(bucket='mybucket',
prefix='images/', suffix='.jpg')
def resize_image(event):
app.log.debug("Resizing image for s3://%s/%s",
event.bucket, event.key)
with tempfile.NamedTemporaryFile('w') as f:
s3_client.download_file(event.bucket, event.key, f.name)
resized_file = f.name + '.thumbnail.jpg'
with open(Image.open(f.name)) as image:
image.thumbnail((256, 256))
image.save(resized_file)
s3_client.upload_file(
filename=resized_file,
bucket='mybucket',
key=f'thumbnails/{event.key.split("/", 1)[1]}'
)
Trigger function when
objects uploaded to
s3://mybucket/images/**/*.jpg
S3 Image Resizer app.py
import tempfile
import boto3
from PIL import Image
from chalice import Chalice
app = Chalice(app_name='s3resize', debug=True)
s3_client = boto3.client('s3')
@app.on_s3_event(bucket='mybucket',
prefix='images/', suffix='.jpg')
def resize_image(event):
app.log.debug("Resizing image for s3://%s/%s",
event.bucket, event.key)
with tempfile.NamedTemporaryFile('w') as f:
s3_client.download_file(event.bucket, event.key, f.name)
resized_file = f.name + '.thumbnail.jpg'
with open(Image.open(f.name)) as image:
image.thumbnail((256, 256))
image.save(resized_file)
s3_client.upload_file(
filename=resized_file,
bucket='mybucket',
key=f'thumbnails/{event.key.split("/", 1)[1]}'
)
S3 Image Resizer app.py
import tempfile
import boto3
from PIL import Image
from chalice import Chalice
app = Chalice(app_name='s3resize', debug=True)
s3_client = boto3.client('s3')
@app.on_s3_event(bucket='mybucket',
prefix='images/', suffix='.jpg')
def resize_image(event):
app.log.debug("Resizing image for s3://%s/%s",
event.bucket, event.key)
with tempfile.NamedTemporaryFile('w') as f:
s3_client.download_file(event.bucket, event.key, f.name)
resized_file = f.name + '.thumbnail.jpg'
with open(Image.open(f.name)) as image:
image.thumbnail((256, 256))
image.save(resized_file)
s3_client.upload_file(
filename=resized_file,
bucket='mybucket',
key=f'thumbnails/{event.key.split("/", 1)[1]}'
)
Event dictionary mapped to
python object
download_file method from boto3
will download file parts in parallel
S3 Image Resizer app.py
import tempfile
import boto3
from PIL import Image
from chalice import Chalice
app = Chalice(app_name='s3resize', debug=True)
s3_client = boto3.client('s3')
@app.on_s3_event(bucket='mybucket',
prefix='images/', suffix='.jpg')
def resize_image(event):
app.log.debug("Resizing image for s3://%s/%s",
event.bucket, event.key)
with tempfile.NamedTemporaryFile('w') as f:
s3_client.download_file(event.bucket, event.key, f.name)
resized_file = f.name + '.thumbnail.jpg'
with open(Image.open(f.name)) as image:
image.thumbnail((256, 256))
image.save(resized_file)
s3_client.upload_file(
filename=resized_file,
bucket='mybucket',
key=f'thumbnails/{event.key.split("/", 1)[1]}'
)
Generate 256x256 image and save
image to a temporary file.
S3 Image Resizer app.py
import tempfile
import boto3
from PIL import Image
from chalice import Chalice
app = Chalice(app_name='s3resize', debug=True)
s3_client = boto3.client('s3')
@app.on_s3_event(bucket='mybucket',
prefix='images/', suffix='.jpg')
def resize_image(event):
app.log.debug("Resizing image for s3://%s/%s",
event.bucket, event.key)
with tempfile.NamedTemporaryFile('w') as f:
s3_client.download_file(event.bucket, event.key, f.name)
resized_file = f.name + '.thumbnail.jpg'
with open(Image.open(f.name)) as image:
image.thumbnail((256, 256))
image.save(resized_file)
s3_client.upload_file(
filename=resized_file,
bucket='mybucket',
key=f'thumbnails/{event.key.split("/", 1)[1]}'
)
Upload thumbnail back to S3.
upload_file from boto3
will use parallelized multi part
uploaded if needed.
Chalice architecture
.
!"" app.py
#"" requirements.txt
Chalice architecture
$ chalice deploy
Chalice architecture
AWS IAM role
IAM.create_role()
$ chalice deploy
Chalice architecture
AWS IAM role
$ chalice deploy
IAM policy
Chalice architecture
AWS IAM role
IAM.put_role_policy()
$ chalice deploy
IAM policy
Chalice architecture
AWS IAM role
IAM.put_role_policy()
$ chalice deploy
Chalice architecture
AWS IAM role
$ chalice deploy
.
!"" app.py
#"" requirements.txt
Chalice architecture
AWS IAM role
$ chalice deploy
Chalice architecture
AWS IAM role
$ chalice deploy
deploy.zip
Chalice runtime
Chalice architecture
AWS IAM role
$ chalice deploy
deploy.zip
Chalice runtime
Lambda.create_function()
AWS Lambda
Chalice architecture
AWS IAM role
$ chalice deploy
deploy.zip
Chalice runtime
Lambda.create_function()
AWS Lambda
Chalice architecture
AWS IAM role
$ chalice deploy
AWS Lambda
Chalice architecture
$ chalice deploy
S3.put_bucket_notification_configuration()
AWS Lambda
Amazon S3
Lambda.add_permission(S3)
@app.on_s3_event('mybucket')
def resize_image(event):
pass
@app.schedule('rate(5 minutes)')
def rate_handler(event):
pass
@app.on_sns_message(topic='mytopic')
def handler(event):
pass
@app.on_sqs_message(queue='myqueue')
def handler(event):
pass
@app.lambda_function()
def handler(event, context):
pass
@app.route('/resource/{value}',
methods=['PUT'])
def resource(value):
pass
@app.authorizer(ttl_seconds=30)
def jwt_auth(auth_request):
pass
Additional Chalice Decorators
Serverless Computing Overview
Serverless Architecture
Serverless Application in Python
Continuous Delivery
Code changes are automatically built, tested, and
prepared for a release to production.
Every code change is built, tested, and then pushed to a
non-production testing or staging environment.
Deliver Updates Faster
Source Control Build Beta Production
Commit changes Run build and unit tests Deploy to test environment
Run integration tests
Deploy to production environment
Source Control Build Beta Production
Commit changes Run build and unit tests Deploy to test environment
Run integration tests
Deploy to production environment
Source Control Build Beta Production
Commit changes Run build and unit tests Deploy to test environment
Run integration tests
Deploy to production environment
Source Control Build Beta Production
Commit changes Run build and unit tests Deploy to test environment
Run integration tests
Deploy to production environment
Source Control Build Beta Production
Commit changes Run build and unit tests Deploy to test environment
Run integration tests
Deploy to production environment
Application Lifecycle
Application Lifecycle
Local Dev Laptop
chalice local
Application Lifecycle
Local Dev Laptop
chalice local
Dev Stack
AWS Lambda
chalice deploy
Amazon S3
Application Lifecycle
Local Dev Laptop
chalice local
Full CD Pipeline
Source
Build
Beta
Test
Prod
AWS CodePipeline
chalice generate-pipeline
Dev Stack
AWS Lambda
chalice deploy
Amazon S3
Next Steps
Todo App tutorial: https://chalice-workshop.readthedocs.io/en/latest/todo-app/index.html
Media query tutorial: https://chalice-workshop.readthedocs.io/en/latest/media-query/index.html
Chalice GitHub repository: https://github.com/aws/chalice
Chalice documentation: http://chalice.readthedocs.io/en/latest/
Serverless Black Belt (re:Invent 2017): https://www.youtube.com/watch?v=oQFORsso2go
Thanks!
James Saryerwinnie
@jsaryer

More Related Content

What's hot

Step into serverless into the box 2018
Step into serverless into the box 2018Step into serverless into the box 2018
Step into serverless into the box 2018Ortus Solutions, Corp
 
Heat and its resources
Heat and its resourcesHeat and its resources
Heat and its resourcesSangeeth Kumar
 
From System Engineer to Gopher
From System Engineer to GopherFrom System Engineer to Gopher
From System Engineer to GopherI-Fan Wang
 
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...Twilio Inc
 
Amazon Web Services for PHP Developers
Amazon Web Services for PHP DevelopersAmazon Web Services for PHP Developers
Amazon Web Services for PHP DevelopersJeremy Lindblom
 
AWS CLI: 2017 and Beyond - DEV307 - re:Invent 2017
AWS CLI: 2017 and Beyond - DEV307 - re:Invent 2017AWS CLI: 2017 and Beyond - DEV307 - re:Invent 2017
AWS CLI: 2017 and Beyond - DEV307 - re:Invent 2017Amazon Web Services
 
Advanced Container Management and Scheduling
Advanced Container Management and SchedulingAdvanced Container Management and Scheduling
Advanced Container Management and SchedulingAmazon Web Services
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...Yevgeniy Brikman
 
Heat up your stack
Heat up your stackHeat up your stack
Heat up your stackRico Lin
 
Akka persistence webinar
Akka persistence webinarAkka persistence webinar
Akka persistence webinarpatriknw
 
WordPress RESTful API & Amazon API Gateway (English version)
WordPress RESTful API & Amazon API Gateway (English version)WordPress RESTful API & Amazon API Gateway (English version)
WordPress RESTful API & Amazon API Gateway (English version)崇之 清水
 
Introduction to Container Management on AWS
Introduction to Container Management  on AWSIntroduction to Container Management  on AWS
Introduction to Container Management on AWSAmazon Web Services
 
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
 [AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵 [AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵Amazon Web Services Korea
 
Serverless Architectural Patterns
Serverless Architectural PatternsServerless Architectural Patterns
Serverless Architectural PatternsAmazon Web Services
 
AWS Lambda from the trenches
AWS Lambda from the trenchesAWS Lambda from the trenches
AWS Lambda from the trenchesYan Cui
 
Building Global Serverless Backends
Building Global Serverless BackendsBuilding Global Serverless Backends
Building Global Serverless BackendsAmazon Web Services
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreC4Media
 

What's hot (20)

Step into serverless into the box 2018
Step into serverless into the box 2018Step into serverless into the box 2018
Step into serverless into the box 2018
 
Heat and its resources
Heat and its resourcesHeat and its resources
Heat and its resources
 
From System Engineer to Gopher
From System Engineer to GopherFrom System Engineer to Gopher
From System Engineer to Gopher
 
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
 
Amazon Web Services for PHP Developers
Amazon Web Services for PHP DevelopersAmazon Web Services for PHP Developers
Amazon Web Services for PHP Developers
 
Deep Dive into AWS Fargate
Deep Dive into AWS FargateDeep Dive into AWS Fargate
Deep Dive into AWS Fargate
 
Building a chatbot – step by step
Building a chatbot – step by stepBuilding a chatbot – step by step
Building a chatbot – step by step
 
AWS CLI: 2017 and Beyond - DEV307 - re:Invent 2017
AWS CLI: 2017 and Beyond - DEV307 - re:Invent 2017AWS CLI: 2017 and Beyond - DEV307 - re:Invent 2017
AWS CLI: 2017 and Beyond - DEV307 - re:Invent 2017
 
Advanced Container Management and Scheduling
Advanced Container Management and SchedulingAdvanced Container Management and Scheduling
Advanced Container Management and Scheduling
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
 
Heat up your stack
Heat up your stackHeat up your stack
Heat up your stack
 
Amazon ECS Deep Dive
Amazon ECS Deep DiveAmazon ECS Deep Dive
Amazon ECS Deep Dive
 
Akka persistence webinar
Akka persistence webinarAkka persistence webinar
Akka persistence webinar
 
WordPress RESTful API & Amazon API Gateway (English version)
WordPress RESTful API & Amazon API Gateway (English version)WordPress RESTful API & Amazon API Gateway (English version)
WordPress RESTful API & Amazon API Gateway (English version)
 
Introduction to Container Management on AWS
Introduction to Container Management  on AWSIntroduction to Container Management  on AWS
Introduction to Container Management on AWS
 
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
 [AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵 [AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
 
Serverless Architectural Patterns
Serverless Architectural PatternsServerless Architectural Patterns
Serverless Architectural Patterns
 
AWS Lambda from the trenches
AWS Lambda from the trenchesAWS Lambda from the trenches
AWS Lambda from the trenches
 
Building Global Serverless Backends
Building Global Serverless BackendsBuilding Global Serverless Backends
Building Global Serverless Backends
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
 

Similar to A Crash Course on Serverless Applications in Python

AWS Serverless with Chalice
AWS Serverless with Chalice AWS Serverless with Chalice
AWS Serverless with Chalice Suman Debnath
 
Building Serverless Applications with AWS Chalice
Building Serverless Applications with AWS ChaliceBuilding Serverless Applications with AWS Chalice
Building Serverless Applications with AWS ChaliceAmazon Web Services
 
Track 4 Session 2_MAD03 容器技術和 AWS Lambda 讓您專注「應用優先」.pptx
Track 4 Session 2_MAD03 容器技術和 AWS Lambda 讓您專注「應用優先」.pptxTrack 4 Session 2_MAD03 容器技術和 AWS Lambda 讓您專注「應用優先」.pptx
Track 4 Session 2_MAD03 容器技術和 AWS Lambda 讓您專注「應用優先」.pptxAmazon Web Services
 
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbsAWS Chicago
 
Serverless archtiectures
Serverless archtiecturesServerless archtiectures
Serverless archtiecturesIegor Fadieiev
 
Serverless computing with AWS Lambda
Serverless computing with AWS Lambda Serverless computing with AWS Lambda
Serverless computing with AWS Lambda Apigee | Google Cloud
 
Schedule File Transfer from SFTP to S3 with AWS Lambda
Schedule File Transfer from SFTP to S3 with AWS LambdaSchedule File Transfer from SFTP to S3 with AWS Lambda
Schedule File Transfer from SFTP to S3 with AWS LambdaMaximilian Jackson
 
AWS Lambda and the Serverless Cloud
AWS Lambda and the Serverless CloudAWS Lambda and the Serverless Cloud
AWS Lambda and the Serverless CloudAmazon Web Services
 
Amazon API Gateway and AWS Lambda: Better Together
Amazon API Gateway and AWS Lambda: Better TogetherAmazon API Gateway and AWS Lambda: Better Together
Amazon API Gateway and AWS Lambda: Better TogetherDanilo Poccia
 
Serverless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best PracticesServerless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best PracticesDaniel Zivkovic
 
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...DevOps_Fest
 
Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Andrea Scuderi
 
Serverless architecture with AWS Lambda (June 2016)
Serverless architecture with AWS Lambda (June 2016)Serverless architecture with AWS Lambda (June 2016)
Serverless architecture with AWS Lambda (June 2016)Julien SIMON
 
AWS Summit Singapore - Lambda, Step Functions and Datadog: A Symphony
AWS Summit Singapore - Lambda, Step Functions and Datadog: A SymphonyAWS Summit Singapore - Lambda, Step Functions and Datadog: A Symphony
AWS Summit Singapore - Lambda, Step Functions and Datadog: A SymphonyAmazon Web Services
 
Deployment and Management on AWS:
 A Deep Dive on Options and Tools
Deployment and Management on AWS:
 A Deep Dive on Options and ToolsDeployment and Management on AWS:
 A Deep Dive on Options and Tools
Deployment and Management on AWS:
 A Deep Dive on Options and ToolsDanilo Poccia
 
Introduciendo Serverless en Proyectos Python
Introduciendo Serverless en Proyectos PythonIntroduciendo Serverless en Proyectos Python
Introduciendo Serverless en Proyectos PythonCarlos Hernando
 
AWS for Startups, London - Programming AWS
AWS for Startups, London - Programming AWSAWS for Startups, London - Programming AWS
AWS for Startups, London - Programming AWSAmazon Web Services
 
Aws meetup building_lambda
Aws meetup building_lambdaAws meetup building_lambda
Aws meetup building_lambdaAdam Book
 
Programming the Physical World with Device Shadows and Rules Engine
Programming the Physical World with Device Shadows and Rules EngineProgramming the Physical World with Device Shadows and Rules Engine
Programming the Physical World with Device Shadows and Rules EngineAmazon Web Services
 
Building Serverless APIs on AWS
Building Serverless APIs on AWSBuilding Serverless APIs on AWS
Building Serverless APIs on AWSJulien SIMON
 

Similar to A Crash Course on Serverless Applications in Python (20)

AWS Serverless with Chalice
AWS Serverless with Chalice AWS Serverless with Chalice
AWS Serverless with Chalice
 
Building Serverless Applications with AWS Chalice
Building Serverless Applications with AWS ChaliceBuilding Serverless Applications with AWS Chalice
Building Serverless Applications with AWS Chalice
 
Track 4 Session 2_MAD03 容器技術和 AWS Lambda 讓您專注「應用優先」.pptx
Track 4 Session 2_MAD03 容器技術和 AWS Lambda 讓您專注「應用優先」.pptxTrack 4 Session 2_MAD03 容器技術和 AWS Lambda 讓您專注「應用優先」.pptx
Track 4 Session 2_MAD03 容器技術和 AWS Lambda 讓您專注「應用優先」.pptx
 
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 
Serverless archtiectures
Serverless archtiecturesServerless archtiectures
Serverless archtiectures
 
Serverless computing with AWS Lambda
Serverless computing with AWS Lambda Serverless computing with AWS Lambda
Serverless computing with AWS Lambda
 
Schedule File Transfer from SFTP to S3 with AWS Lambda
Schedule File Transfer from SFTP to S3 with AWS LambdaSchedule File Transfer from SFTP to S3 with AWS Lambda
Schedule File Transfer from SFTP to S3 with AWS Lambda
 
AWS Lambda and the Serverless Cloud
AWS Lambda and the Serverless CloudAWS Lambda and the Serverless Cloud
AWS Lambda and the Serverless Cloud
 
Amazon API Gateway and AWS Lambda: Better Together
Amazon API Gateway and AWS Lambda: Better TogetherAmazon API Gateway and AWS Lambda: Better Together
Amazon API Gateway and AWS Lambda: Better Together
 
Serverless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best PracticesServerless Architectural Patterns & Best Practices
Serverless Architectural Patterns & Best Practices
 
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
 
Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020
 
Serverless architecture with AWS Lambda (June 2016)
Serverless architecture with AWS Lambda (June 2016)Serverless architecture with AWS Lambda (June 2016)
Serverless architecture with AWS Lambda (June 2016)
 
AWS Summit Singapore - Lambda, Step Functions and Datadog: A Symphony
AWS Summit Singapore - Lambda, Step Functions and Datadog: A SymphonyAWS Summit Singapore - Lambda, Step Functions and Datadog: A Symphony
AWS Summit Singapore - Lambda, Step Functions and Datadog: A Symphony
 
Deployment and Management on AWS:
 A Deep Dive on Options and Tools
Deployment and Management on AWS:
 A Deep Dive on Options and ToolsDeployment and Management on AWS:
 A Deep Dive on Options and Tools
Deployment and Management on AWS:
 A Deep Dive on Options and Tools
 
Introduciendo Serverless en Proyectos Python
Introduciendo Serverless en Proyectos PythonIntroduciendo Serverless en Proyectos Python
Introduciendo Serverless en Proyectos Python
 
AWS for Startups, London - Programming AWS
AWS for Startups, London - Programming AWSAWS for Startups, London - Programming AWS
AWS for Startups, London - Programming AWS
 
Aws meetup building_lambda
Aws meetup building_lambdaAws meetup building_lambda
Aws meetup building_lambda
 
Programming the Physical World with Device Shadows and Rules Engine
Programming the Physical World with Device Shadows and Rules EngineProgramming the Physical World with Device Shadows and Rules Engine
Programming the Physical World with Device Shadows and Rules Engine
 
Building Serverless APIs on AWS
Building Serverless APIs on AWSBuilding Serverless APIs on AWS
Building Serverless APIs on AWS
 

Recently uploaded

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 

A Crash Course on Serverless Applications in Python

  • 1. A Crash Course on Serverless Applications in Python James Saryerwinnie @jsaryer
  • 2. Serverless Computing Overview Serverless Architecture Serverless Application in Python
  • 3. Serverless Computing Overview Serverless Architecture Serverless Application in Python
  • 4. Serverless Computing Overview Build and run applications without thinking about servers
  • 5. No servers to provision, scale, or manage Flexible scaling Built-in availability and fault tolerance Serverless Computing
  • 6. AWS Lambda Run code without thinking about servers. Pay for only the compute time you consume. Lambda takes care of everything required to run and scale your code with high availability.
  • 7. AWS Lambda Function def handler(event, context): return 'hello world!'
  • 8. def handler(event, context): return 'hello world!' AWS Lambda Function
  • 9. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function
  • 10. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 2 event - data about what triggered invocation context - runtime information about your function
  • 11. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function
  • 12. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function app.py
  • 13. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function app.py
  • 14. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function app.py $ python >>> import app >>> app.handler(event={}, context=None) 'hello world!'
  • 15. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function app.py
  • 16. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function app.py $ pip install awscli
  • 17. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function app.py $ pip install awscli $ aws configure
  • 18. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function app.py
  • 19. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function app.py $ aws lambda create-function --function-name hello --handler app.handler --zip-file ...
  • 20. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function app.py $ aws lambda create-function --function-name hello --handler app.handler --zip-file ... $ aws lambda invoke --function-name hello
  • 21. def handler(event, context): return 'hello world!' AWS Lambda Function 1 Define python function 3 Return value sent back as response 2 event - data about what triggered invocation context - runtime information about your function app.py $ aws lambda create-function --function-name hello --handler app.handler --zip-file ... $ aws lambda invoke --function-name hello hello world!
  • 22. def handler(event, context): return event['foo'].upper() AWS Lambda Function Input app.py
  • 23. def handler(event, context): return event['foo'].upper() AWS Lambda Function Input app.py $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
  • 24. def handler(event, context): return event['foo'].upper() AWS Lambda Function Input app.py $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}'
  • 25. def handler(event, context): return event['foo'].upper() AWS Lambda Function Input app.py $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' BAR
  • 26. def handler(event, context): return event['foo'].upper() AWS Lambda Function Input app.py $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' BAR $ aws lambda invoke --function-name hello --payload '{"foo": "baz"}'
  • 27. def handler(event, context): return event['foo'].upper() AWS Lambda Function Input app.py $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' BAR $ aws lambda invoke --function-name hello --payload '{"foo": "baz"}' BAZ
  • 28. AWS Lambda Function Invocation https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html https://youtu.be/oQFORsso2go?t=422
  • 29. AWS Lambda Function Invocation $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html https://youtu.be/oQFORsso2go?t=422
  • 30. AWS Lambda Function Invocation $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' Download your code https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html https://youtu.be/oQFORsso2go?t=422
  • 31. AWS Lambda Function Invocation $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' Download your code Start new container https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html https://youtu.be/oQFORsso2go?t=422
  • 32. AWS Lambda Function Invocation $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' Download your code Start new container Bootstrap the runtime https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html https://youtu.be/oQFORsso2go?t=422
  • 33. AWS Lambda Function Invocation $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' Start your codeDownload your code Start new container Bootstrap the runtime https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html https://youtu.be/oQFORsso2go?t=422
  • 34. AWS Lambda Function Invocation $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' Start your codeDownload your code Start new container Bootstrap the runtime Cold Start https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html https://youtu.be/oQFORsso2go?t=422
  • 35. AWS Lambda Function Invocation $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' Start your codeDownload your code Start new container Bootstrap the runtime Cold Start Warm Start https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html https://youtu.be/oQFORsso2go?t=422
  • 36. AWS Lambda Function Invocation $ aws lambda invoke --function-name hello --payload '{"foo": "bar"}' Start your codeDownload your code Start new container Bootstrap the runtime Cold Start Warm Start $ aws lambda invoke --function-name hello --payload '{"foo": "baz"}' https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html https://youtu.be/oQFORsso2go?t=422
  • 37. Focus on your core product instead of worrying about managing and operating servers or runtimes.
  • 38. Serverless Computing Overview Serverless Architecture Serverless Application in Python
  • 40. Serverless Architecture Event Trigger Lambda Services Amazon API Gateway request Timer SQS message Amazon DynamoDB Amazon S3
  • 41. Serverless Architecture Event Trigger Lambda Services Amazon API Gateway request Timer SQS message Amazon DynamoDB Amazon S3Think in terms of events
  • 42. Serverless Architecture Event Trigger Lambda Services API Gateway request Timer SQS message Amazon S3 Amazon DynamoDB
  • 43. Serverless Architecture Event Trigger Lambda Services API Gateway request Timer SQS message Amazon S3 Amazon DynamoDB Decompose code into separate functions
  • 44. Synchronous Invocation Event Trigger Lambda Manual invocation $ aws lambda invoke
  • 45. Synchronous Invocation Event Trigger Lambda GET /users Rest API Request {"http": "response"}
  • 47. Async Invocation Event Trigger Lambda Services Amazon S3 object uploaded 1
  • 48. Return immediately 2 Async Invocation Event Trigger Lambda Services Amazon S3 object uploaded 1
  • 49. Return immediately 2 Async Invocation Event Trigger Lambda Services Amazon S3 object uploaded 1 Event trigger notification3
  • 50. Return immediately 2 Async Invocation Event Trigger Lambda Services Amazon S3 object uploaded 1 Generates thumbnail4 Event trigger notification3
  • 51. Return immediately 2 Async Invocation Event Trigger Lambda Services Amazon S3 object uploaded 1 Generates thumbnail4 Uploads to output bucket Upload complete 5 Event trigger notification3
  • 53. Stream/Poll Invocation Stream Lambda Poller Lambda Return immediately2 Amazon SQS message added 1
  • 54. Stream/Poll Invocation Stream Lambda Poller Lambda Return immediately2 Amazon SQS message added 1 3 Poll for messages
  • 55. Stream/Poll Invocation Stream Lambda Poller Lambda Return immediately2 Amazon SQS message added 1 3 Poll for messages Message batch4
  • 56. Lambda function invoked5 Stream/Poll Invocation Stream Lambda Poller Lambda Return immediately2 Amazon SQS message added 1 3 Poll for messages Message batch4
  • 57. Lambda function invoked5 Stream/Poll Invocation Stream Lambda Poller Lambda Function execution finished Return immediately2 Amazon SQS message added 1 3 Poll for messages Message batch4
  • 58. Synchronous Asynchronous Stream Blocks until response is returned from Lambda function Lambda function triggered in response to an event, decoupled from event trigger Lambda service polls for changes on a stream, invokes Lambda function with batch of messages
  • 59. Synchronous Asynchronous Stream Blocks until response is returned from Lambda function Lambda function triggered in response to an event, decoupled from event trigger Lambda service polls for changes on a stream, invokes Lambda function with batch of messages $ aws lambda invoke Amazon API Gateway request /users
  • 60. Synchronous Asynchronous Stream Blocks until response is returned from Lambda function Lambda function triggered in response to an event, decoupled from event trigger Lambda service polls for changes on a stream, invokes Lambda function with batch of messages Timer Amazon S3 Object Amazon SNS Topic $ aws lambda invoke Amazon API Gateway request /users
  • 61. Synchronous Asynchronous Stream Blocks until response is returned from Lambda function Lambda function triggered in response to an event, decoupled from event trigger Lambda service polls for changes on a stream, invokes Lambda function with batch of messages Timer Amazon S3 Object Amazon SNS Topic Amazon SQS Message Amazon DynamoDB Stream Amazon Kinesis Stream $ aws lambda invoke Amazon API Gateway request /users
  • 62. Serverless Computing Overview Serverless Architecture Serverless Application in Python
  • 64. AWS Lambda def handler(event, context): return 'hello world!'
  • 65. Setting up from scratch AWS Lambda AWS IAM role IAM.create_role()IAM.put_role_policy() Lambda.create_function() Zip of code and dependencies IAM policy
  • 66. Setting up from scratch AWS Lambda AWS IAM role IAM.create_role()IAM.put_role_policy() Lambda.create_function() Zip of code and dependencies IAM policy 1
  • 67. Setting up from scratch AWS Lambda AWS IAM role IAM.create_role()IAM.put_role_policy() Lambda.create_function() Zip of code and dependencies IAM policy 1 2
  • 68. Setting up from scratch AWS Lambda AWS IAM role IAM.create_role()IAM.put_role_policy() Lambda.create_function() Zip of code and dependencies IAM policy 1 2 3
  • 69. Creating our first Lambda function
  • 70. Creating our first Lambda function $ zip -r app.zip app.py1
  • 71. Creating our first Lambda function $ zip -r app.zip app.py1 2 $ aws iam create-role --role-name MyApp --assume-role-policy-document '{ "Version": "2012-10-17", "Statement": [{ "Sid": "", "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }] }'
  • 72. Creating our first Lambda function $ zip -r app.zip app.py $ aws lambda create-function --function-name Hello --role-name MyApp --runtime python3.6 --handler app.handler --zip-file fileb://app.zip 1 2 3 $ aws iam create-role --role-name MyApp --assume-role-policy-document '{ "Version": "2012-10-17", "Statement": [{ "Sid": "", "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }] }'
  • 73. Creating our first Lambda function $ zip -r app.zip app.py $ aws lambda create-function --function-name Hello --role-name MyApp --runtime python3.6 --handler app.handler --zip-file fileb://app.zip 1 2 3 $ aws iam create-role --role-name MyApp --assume-role-policy-document '{ "Version": "2012-10-17", "Statement": [{ "Sid": "", "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }] }'
  • 74. Creating our first Lambda function $ zip -r app.zip app.py $ aws lambda create-function --function-name Hello --role-name MyApp --runtime python3.6 --handler app.handler --zip-file fileb://app.zip 1 2 3 $ aws iam create-role --role-name MyApp --assume-role-policy-document '{ "Version": "2012-10-17", "Statement": [{ "Sid": "", "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }] }'
  • 75. Return immediately 2 Image Resizer Event Trigger Lambda Services Amazon S3 object uploaded 1 λEvent trigger notification3 Generates thumbnail4 Uploads to output bucket Upload complete 5
  • 76. Amazon S3 AWS Lambda AWS IAM role IAM.create_role()IAM.put_role_policy() Lambda.create_function()S3.put_bucket_notification_configuration() Zip of code and dependenciesNotification Config IAM policy Lambda.add_permsission(S3) Image Resizer
  • 77. Amazon S3 AWS Lambda AWS IAM role IAM.create_role()IAM.put_role_policy() Lambda.create_function()S3.put_bucket_notification_configuration() Zip of code and dependenciesNotification Config IAM policy Lambda.add_permsission(S3) Image Resizer 1. Third party packages 2. S3 notification configuration 3. IAM Permissions
  • 78. Amazon S3 AWS Lambda AWS IAM role IAM.create_role()IAM.put_role_policy() Lambda.create_function()S3.put_bucket_notification_configuration() Zip of code and dependenciesNotification Config IAM policy Lambda.add_permsission(S3) Image Resizer 1. Third party packages 2. S3 notification configuration 3. IAM Permissions
  • 79. Amazon S3 AWS Lambda AWS IAM role IAM.create_role()IAM.put_role_policy() Lambda.create_function()S3.put_bucket_notification_configuration() Zip of code and dependenciesNotification Config IAM policy Lambda.add_permsission(S3) Image Resizer 1. Third party packages 2. S3 notification configuration 3. IAM Permissions
  • 80. Amazon S3 AWS Lambda AWS IAM role IAM.create_role()IAM.put_role_policy() Lambda.create_function()S3.put_bucket_notification_configuration() Zip of code and dependenciesNotification Config IAM policy Lambda.add_permsission(S3) Image Resizer 1. Third party packages 2. S3 notification configuration 3. IAM Permissions
  • 81. AWS Chalice Python serverless framework for AWS Quickly create and deploy serverless applications Integration with many AWS services
  • 82. Lambda handler.py AWS Lambda Chalice Integration def hello_world(event, context): return 'hello world!'
  • 83. Lambda chalice app.py AWS Lambda from chalice import Chalice app = Chalice('helloworld') @app.lambda_function() def hello_world(event, context): return 'hello world!' Chalice Integration
  • 84. Lambda chalice app.py AWS Lambda from chalice import Chalice app = Chalice('helloworld') @app.lambda_function() def hello_world(event, context): return 'hello world!' Chalice Integration 1 app defined at module level
  • 85. Lambda chalice app.py AWS Lambda from chalice import Chalice app = Chalice('helloworld') @app.lambda_function() def hello_world(event, context): return 'hello world!' Chalice Integration 1 app defined at module level 2 One or more decorators to defined resources
  • 86. Deployment $ chalice deploy Creating deployment package. Updating policy for IAM role: helloworld-dev Creating lambda function: helloworld-dev-hello_world Resources deployed: - Lambda ARN: arn:aws:lambda:us-west-2:1:function:helloworld... $ chalice invoke -n hello_world "hello world!"
  • 87. S3 Image Resizer app.py import tempfile import boto3 from PIL import Image from chalice import Chalice app = Chalice(app_name='s3resize', debug=True) s3_client = boto3.client('s3') @app.on_s3_event(bucket='mybucket', prefix='images/', suffix='.jpg') def resize_image(event): app.log.debug("Resizing image for s3://%s/%s", event.bucket, event.key) with tempfile.NamedTemporaryFile('w') as f: s3_client.download_file(event.bucket, event.key, f.name) resized_file = f.name + '.thumbnail.jpg' with open(Image.open(f.name)) as image: image.thumbnail((256, 256)) image.save(resized_file) s3_client.upload_file( filename=resized_file, bucket='mybucket', key=f'thumbnails/{event.key.split("/", 1)[1]}' )
  • 88. S3 Image Resizer app.py import tempfile import boto3 from PIL import Image from chalice import Chalice app = Chalice(app_name='s3resize', debug=True) s3_client = boto3.client('s3') @app.on_s3_event(bucket='mybucket', prefix='images/', suffix='.jpg') def resize_image(event): app.log.debug("Resizing image for s3://%s/%s", event.bucket, event.key) with tempfile.NamedTemporaryFile('w') as f: s3_client.download_file(event.bucket, event.key, f.name) resized_file = f.name + '.thumbnail.jpg' with open(Image.open(f.name)) as image: image.thumbnail((256, 256)) image.save(resized_file) s3_client.upload_file( filename=resized_file, bucket='mybucket', key=f'thumbnails/{event.key.split("/", 1)[1]}' ) 3rd party package with C extension automatically handled from requirements.txt
  • 89. S3 Image Resizer app.py import tempfile import boto3 from PIL import Image from chalice import Chalice app = Chalice(app_name='s3resize', debug=True) s3_client = boto3.client('s3') @app.on_s3_event(bucket='mybucket', prefix='images/', suffix='.jpg') def resize_image(event): app.log.debug("Resizing image for s3://%s/%s", event.bucket, event.key) with tempfile.NamedTemporaryFile('w') as f: s3_client.download_file(event.bucket, event.key, f.name) resized_file = f.name + '.thumbnail.jpg' with open(Image.open(f.name)) as image: image.thumbnail((256, 256)) image.save(resized_file) s3_client.upload_file( filename=resized_file, bucket='mybucket', key=f'thumbnails/{event.key.split("/", 1)[1]}' ) Client created in module scope Only part of cold-start time
  • 90. S3 Image Resizer app.py import tempfile import boto3 from PIL import Image from chalice import Chalice app = Chalice(app_name='s3resize', debug=True) s3_client = boto3.client('s3') @app.on_s3_event(bucket='mybucket', prefix='images/', suffix='.jpg') def resize_image(event): app.log.debug("Resizing image for s3://%s/%s", event.bucket, event.key) with tempfile.NamedTemporaryFile('w') as f: s3_client.download_file(event.bucket, event.key, f.name) resized_file = f.name + '.thumbnail.jpg' with open(Image.open(f.name)) as image: image.thumbnail((256, 256)) image.save(resized_file) s3_client.upload_file( filename=resized_file, bucket='mybucket', key=f'thumbnails/{event.key.split("/", 1)[1]}' ) Client created in module scope Only part of cold-start time Start your codeDownload your code Start new container Bootstrap the runtime Cold Start Warm Start Module Import
  • 91. S3 Image Resizer app.py import tempfile import boto3 from PIL import Image from chalice import Chalice app = Chalice(app_name='s3resize', debug=True) s3_client = boto3.client('s3') @app.on_s3_event(bucket='mybucket', prefix='images/', suffix='.jpg') def resize_image(event): app.log.debug("Resizing image for s3://%s/%s", event.bucket, event.key) with tempfile.NamedTemporaryFile('w') as f: s3_client.download_file(event.bucket, event.key, f.name) resized_file = f.name + '.thumbnail.jpg' with open(Image.open(f.name)) as image: image.thumbnail((256, 256)) image.save(resized_file) s3_client.upload_file( filename=resized_file, bucket='mybucket', key=f'thumbnails/{event.key.split("/", 1)[1]}' ) Trigger function when objects uploaded to s3://mybucket/images/**/*.jpg
  • 92. S3 Image Resizer app.py import tempfile import boto3 from PIL import Image from chalice import Chalice app = Chalice(app_name='s3resize', debug=True) s3_client = boto3.client('s3') @app.on_s3_event(bucket='mybucket', prefix='images/', suffix='.jpg') def resize_image(event): app.log.debug("Resizing image for s3://%s/%s", event.bucket, event.key) with tempfile.NamedTemporaryFile('w') as f: s3_client.download_file(event.bucket, event.key, f.name) resized_file = f.name + '.thumbnail.jpg' with open(Image.open(f.name)) as image: image.thumbnail((256, 256)) image.save(resized_file) s3_client.upload_file( filename=resized_file, bucket='mybucket', key=f'thumbnails/{event.key.split("/", 1)[1]}' )
  • 93. S3 Image Resizer app.py import tempfile import boto3 from PIL import Image from chalice import Chalice app = Chalice(app_name='s3resize', debug=True) s3_client = boto3.client('s3') @app.on_s3_event(bucket='mybucket', prefix='images/', suffix='.jpg') def resize_image(event): app.log.debug("Resizing image for s3://%s/%s", event.bucket, event.key) with tempfile.NamedTemporaryFile('w') as f: s3_client.download_file(event.bucket, event.key, f.name) resized_file = f.name + '.thumbnail.jpg' with open(Image.open(f.name)) as image: image.thumbnail((256, 256)) image.save(resized_file) s3_client.upload_file( filename=resized_file, bucket='mybucket', key=f'thumbnails/{event.key.split("/", 1)[1]}' ) Event dictionary mapped to python object download_file method from boto3 will download file parts in parallel
  • 94. S3 Image Resizer app.py import tempfile import boto3 from PIL import Image from chalice import Chalice app = Chalice(app_name='s3resize', debug=True) s3_client = boto3.client('s3') @app.on_s3_event(bucket='mybucket', prefix='images/', suffix='.jpg') def resize_image(event): app.log.debug("Resizing image for s3://%s/%s", event.bucket, event.key) with tempfile.NamedTemporaryFile('w') as f: s3_client.download_file(event.bucket, event.key, f.name) resized_file = f.name + '.thumbnail.jpg' with open(Image.open(f.name)) as image: image.thumbnail((256, 256)) image.save(resized_file) s3_client.upload_file( filename=resized_file, bucket='mybucket', key=f'thumbnails/{event.key.split("/", 1)[1]}' ) Generate 256x256 image and save image to a temporary file.
  • 95. S3 Image Resizer app.py import tempfile import boto3 from PIL import Image from chalice import Chalice app = Chalice(app_name='s3resize', debug=True) s3_client = boto3.client('s3') @app.on_s3_event(bucket='mybucket', prefix='images/', suffix='.jpg') def resize_image(event): app.log.debug("Resizing image for s3://%s/%s", event.bucket, event.key) with tempfile.NamedTemporaryFile('w') as f: s3_client.download_file(event.bucket, event.key, f.name) resized_file = f.name + '.thumbnail.jpg' with open(Image.open(f.name)) as image: image.thumbnail((256, 256)) image.save(resized_file) s3_client.upload_file( filename=resized_file, bucket='mybucket', key=f'thumbnails/{event.key.split("/", 1)[1]}' ) Upload thumbnail back to S3. upload_file from boto3 will use parallelized multi part uploaded if needed.
  • 98. Chalice architecture AWS IAM role IAM.create_role() $ chalice deploy
  • 99. Chalice architecture AWS IAM role $ chalice deploy IAM policy
  • 100. Chalice architecture AWS IAM role IAM.put_role_policy() $ chalice deploy IAM policy
  • 101. Chalice architecture AWS IAM role IAM.put_role_policy() $ chalice deploy
  • 102. Chalice architecture AWS IAM role $ chalice deploy . !"" app.py #"" requirements.txt
  • 103. Chalice architecture AWS IAM role $ chalice deploy
  • 104. Chalice architecture AWS IAM role $ chalice deploy deploy.zip Chalice runtime
  • 105. Chalice architecture AWS IAM role $ chalice deploy deploy.zip Chalice runtime Lambda.create_function() AWS Lambda
  • 106. Chalice architecture AWS IAM role $ chalice deploy deploy.zip Chalice runtime Lambda.create_function() AWS Lambda
  • 107. Chalice architecture AWS IAM role $ chalice deploy AWS Lambda
  • 108. Chalice architecture $ chalice deploy S3.put_bucket_notification_configuration() AWS Lambda Amazon S3 Lambda.add_permission(S3)
  • 109. @app.on_s3_event('mybucket') def resize_image(event): pass @app.schedule('rate(5 minutes)') def rate_handler(event): pass @app.on_sns_message(topic='mytopic') def handler(event): pass @app.on_sqs_message(queue='myqueue') def handler(event): pass @app.lambda_function() def handler(event, context): pass @app.route('/resource/{value}', methods=['PUT']) def resource(value): pass @app.authorizer(ttl_seconds=30) def jwt_auth(auth_request): pass Additional Chalice Decorators
  • 110. Serverless Computing Overview Serverless Architecture Serverless Application in Python
  • 111. Continuous Delivery Code changes are automatically built, tested, and prepared for a release to production. Every code change is built, tested, and then pushed to a non-production testing or staging environment. Deliver Updates Faster
  • 112. Source Control Build Beta Production Commit changes Run build and unit tests Deploy to test environment Run integration tests Deploy to production environment
  • 113. Source Control Build Beta Production Commit changes Run build and unit tests Deploy to test environment Run integration tests Deploy to production environment
  • 114. Source Control Build Beta Production Commit changes Run build and unit tests Deploy to test environment Run integration tests Deploy to production environment
  • 115. Source Control Build Beta Production Commit changes Run build and unit tests Deploy to test environment Run integration tests Deploy to production environment
  • 116. Source Control Build Beta Production Commit changes Run build and unit tests Deploy to test environment Run integration tests Deploy to production environment
  • 118. Application Lifecycle Local Dev Laptop chalice local
  • 119. Application Lifecycle Local Dev Laptop chalice local Dev Stack AWS Lambda chalice deploy Amazon S3
  • 120. Application Lifecycle Local Dev Laptop chalice local Full CD Pipeline Source Build Beta Test Prod AWS CodePipeline chalice generate-pipeline Dev Stack AWS Lambda chalice deploy Amazon S3
  • 121. Next Steps Todo App tutorial: https://chalice-workshop.readthedocs.io/en/latest/todo-app/index.html Media query tutorial: https://chalice-workshop.readthedocs.io/en/latest/media-query/index.html Chalice GitHub repository: https://github.com/aws/chalice Chalice documentation: http://chalice.readthedocs.io/en/latest/ Serverless Black Belt (re:Invent 2017): https://www.youtube.com/watch?v=oQFORsso2go