This class represents a chalice application. It provides:
- The ability to register routes using the :meth:`route` method.
- Within a view function, the ability to introspect the current
request using the
current_requestattribute which is an instance of the :class:`Request` class.
.. attribute:: app_name The name of the Chalice app. This corresponds to the value provided when instantiating a ``Chalice`` object.
.. attribute:: current_request An object of type :class:`Request`. This value is only set when a view function is being called. This attribute can be used to introspect the current HTTP request.
.. attribute:: api An object of type :class:`APIGateway`. This attribute can be used to control how apigateway interprets ``Content-Type`` headers in both requests and responses.
.. attribute:: lambda_context
A Lambda context object that is passed to the invoked view by AWS
Lambda. You can find out more about this object by reading the
`lambda context object documentation <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_.
.. note::
This is only set on ``@app.route`` handlers. For other handlers it
will be ``None``. Instead the event parameter will have a ``context``
property. For example :attr:`S3Event.context`.
.. attribute:: debug
A boolean value that enables debugging. By default, this value is
``False``. If debugging is true, then internal errors are returned back
to the client. Additionally, debug log messages generated by the
framework will show up in the cloudwatch logs. Example usage:
.. code-block:: python
from chalice import Chalice
app = Chalice(app_name="appname")
app.debug = True
.. attribute:: websocket_api An object of type :class:`WebsocketAPI`. This attribute can be used to send messages to websocket clients connected through API Gateway.
.. method:: route(path, \*\*options)
Register a view function for a particular URI path. This method
is intended to be used as a decorator for a view function. For example:
.. code-block:: python
from chalice import Chalice
app = Chalice(app_name="appname")
@app.route('/resource/{value}', methods=['PUT'])
def viewfunction(value):
pass
:param str path: The path to associate with the view function. The
``path`` should only contain ``[a-zA-Z0-9._-]`` chars and curly
braces for parts of the URL you would like to capture. The path
should not end in a trailing slash, otherwise a validation error
will be raised during deployment.
:param list methods: Optional parameter that indicates which HTTP methods
this view function should accept. By default, only ``GET`` requests
are supported. If you only wanted to support ``POST`` requests, you
would specify ``methods=['POST']``. If you support multiple HTTP
methods in a single view function (``methods=['GET', 'POST']``), you
can check the :attr:`app.current_request.method <Request.method>`
attribute to see which HTTP method was used when making the request.
You can provide any HTTP method supported by API Gateway, which
includes: ``GET``, ``POST``, ``PUT``, ``PATCH``, ``HEAD``,
``OPTIONS``, and ``DELETE``.
:param str name: Optional parameter to specify the name of the view
function. You generally do not need to set this value. The name
of the view function is used as the default value for the view name.
:param Authorizer authorizer: Specify an authorizer to use for this
view. Can be an instance of :class:`CognitoUserPoolAuthorizer`,
:class:`CustomAuthorizer` or :class:`IAMAuthorizer`.
:param str content_types: A list of content types to accept for
this view. By default ``application/json`` is accepted. If
this value is specified, then chalice will reject any incoming request
that does not match the provided list of content types with a
415 Unsupported Media Type response.
:param boolean api_key_required: Optional parameter to specify whether
the method required a valid API key.
:param cors: Specify if CORS is supported for this view. This can either
by a boolean value, ``None``, or an instance of :class:`CORSConfig`.
Setting this value is set to ``True`` gives similar behavior to enabling
CORS in the AWS Console. This includes injecting the
``Access-Control-Allow-Origin`` header to have a value of ``*`` as well
as adding an ``OPTIONS`` method to support preflighting requests. If
you would like more control over how CORS is configured, you can provide
an instance of :class:`CORSConfig`.
.. method:: authorizer(name, \*\*options)
Register a built-in authorizer.
.. code-block:: python
from chalice import Chalice, AuthResponse
app = Chalice(app_name="appname")
@app.authorizer(ttl_seconds=30)
def my_auth(auth_request):
# Validate auth_request.token, and then:
return AuthResponse(routes=['/'], principal_id='username')
@app.route('/', authorizer=my_auth)
def viewfunction(value):
pass
:param ttl_seconds: The number of seconds to cache this response.
Subsequent requests that require this authorizer will use a
cached response if available. The default is 300 seconds.
:param execution_role: An optional IAM role to specify when invoking
the Lambda function associated with the built-in authorizer.
:param header: The header where the auth token will be specified.
The default is ``Authorization``
.. method:: schedule(expression, name=None)
Register a scheduled event that's invoked on a regular schedule.
This will create a lambda function associated with the decorated
function. It will also schedule the lambda function to be invoked
with a scheduled CloudWatch Event.
See :ref:`scheduled-events` for more information.
.. code-block:: python
@app.schedule('cron(15 10 ? * 6L 2002-2005)')
def cron_handler(event):
pass
@app.schedule('rate(5 minutes)')
def rate_handler(event):
pass
@app.schedule(Rate(5, unit=Rate.MINUTES))
def rate_obj_handler(event):
pass
@app.schedule(Cron(15, 10, '?', '*', '6L', '2002-2005'))
def cron_obj_handler(event):
pass
:param expression: The schedule expression to use for the CloudWatch
event rule. This value can either be a string value or an
instance of type ``ScheduleExpression``, which is either a
:class:`Cron` or :class:`Rate` object. If a string value is
provided, it will be provided directly as the ``ScheduleExpression``
value in the `PutRule <https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/API_PutRule.html#API_PutRule_RequestSyntax>`__ API
call.
:param name: The name of the function to use. This name is combined
with the chalice app name as well as the stage name to create the
entire lambda function name. This parameter is optional. If it is
not provided, the name of the python function will be used.
.. method:: on_cw_event(pattern, name=None)
Create a lambda function and configure it to be invoked whenever
an event that matches the given pattern flows through CloudWatch Events
or Event Bridge.
:param pattern: The event pattern to use to filter subscribed events.
See the CloudWatch Events docs for examples https://amzn.to/2OlqZso
:param name: The name of the function to create. This name is combined
with the chalice app name as well as the stage name to create the
entire lambda function name. This parameter is optional. If it is
not provided, the name of the python function will be used.
.. method:: on_s3_event(bucket, events=None, prefix=None, suffix=None, name=None)
Create a lambda function and configure it to be automatically invoked
whenever an event happens on an S3 bucket.
.. warning::
You can't use the ``chalice package`` command when using the
``on_s3_event`` decorator. This is because CFN does not support
configuring an existing S3 bucket.
See :ref:`s3-events` for more information.
This example shows how you could implement an image resizer that's
triggered whenever an object is uploaded to the ``images/`` prefix
of an S3 bucket (e.g ``s3://mybucket/images/house.jpg``).
.. code-block:: python
@app.on_s3_event('mybucket', events=['s3:ObjectCreated:Put'],
prefix='images/', suffix='.jpg')
def resize_image(event):
with tempfile.NamedTemporaryFile('w') as f:
s3.download_file(event.bucket, event.key, f.name)
resize_image(f.name)
s3.upload_file(event.bucket, 'resized/%s' % event.key, f.name)
:param bucket: The name of the S3 bucket. This bucket must already exist.
:param events: A list of strings indicating the events that should trigger
the lambda function. See `Supported Event Types <https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html#supported-notification-event-types>`__
for the full list of strings you can provide. If this option is not
provided, a default of ``['s3:ObjectCreated:*']`` is used, which will
configure the lambda function to be invoked whenever a new object
is created in the S3 bucket.
:param prefix: An optional key prefix. This specifies that
the lambda function should only be invoked if the key starts with
this prefix (e.g. ``prefix='images/'``). Note that this value
is not a glob (e.g. ``images/*``), it is a literal string match
for the start of the key.
:param suffix: An optional key suffix. This specifies that the
lambda function should only be invoked if the key name ends with
this suffix (e.g. ``suffix='.jpg'``). Note that this value is
not a glob (e.g. ``*.txt``), it is a literal string match for
the end of the key.
:param name: The name of the function to use. This name is combined
with the chalice app name as well as the stage name to create the
entire lambda function name. This parameter is optional. If it is
not provided, the name of the python function will be used.
.. method:: on_sns_message(topic, name=None)
Create a lambda function and configure it to be automatically invoked
whenever an SNS message is published to the specified topic.
See :ref:`sns-events` for more information.
This example prints the subject and the contents of the message whenever
something publishes to the sns topic of ``mytopic``. In this example,
the input parameter is of type :class:`SNSEvent`.
.. code-block:: python
app.debug = True
@app.on_sns_message(topic='mytopic')
def handler(event):
app.log.info("SNS subject: %s", event.subject)
app.log.info("SNS message: %s", event.message)
:param topic: The name or ARN of the SNS topic you want to subscribe to.
:param name: The name of the function to use. This name is combined
with the chalice app name as well as the stage name to create the
entire lambda function name. This parameter is optional. If it is
not provided, the name of the python function will be used.
.. method:: on_sqs_message(queue, batch_size=1, name=None, queue_arn=None, maximum_batching_window_in_seconds=0, maximum_concurrency=None)
Create a lambda function and configure it to be automatically invoked
whenever a message is published to the specified SQS queue.
The lambda function must accept a single parameter which
is of type :class:`SQSEvent`.
If the decorated function returns without raising any exceptions
then Lambda will automatically delete the SQS messages associated
with the :class:`SQSEvent`. You don't need to manually delete
messages. If any exception is raised, Lambda won't delete any messages,
and the messages will become available once the visibility timeout
has been reached. Note that for batch sizes of more than one, either
the entire batch succeeds and all the messages in the batch are
deleted by Lambda, or the entire batch fails. The default batch size
is 1. See the
`Using AWS Lambda with Amazon SQS <https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html>`__
for more information on how Lambda integrates with SQS.
See the :ref:`sqs-events` topic guide for more information on using SQS
in Chalice.
.. code-block:: python
app.debug = True
@app.on_sqs_message(queue='myqueue')
def handler(event):
app.log.info("Event: %s", event.to_dict())
for record in event:
app.log.info("Message body: %s", record.body)
:param queue: The name of the SQS queue you want to subscribe to.
This is the name of the queue, not the ARN or Queue URL.
:param batch_size: The maximum number of messages to retrieve
when polling for SQS messages. The event parameter can have
multiple SQS messages associated with it. This is why the
event parameter passed to the lambda function is iterable. The
batch size controls how many messages can be in a single event.
:param name: The name of the function to use. This name is combined
with the chalice app name as well as the stage name to create the
entire lambda function name. This parameter is optional. If it is
not provided, the name of the python function will be used.
:param queue_arn: The ARN of the SQS queue you want to subscribe to.
This argument is mutually exclusive with the ``queue`` parameter.
This is useful if you already know the exact ARN or when integrating
with the AWS CDK to create your SQS queue.
:param maximum_batching_window_in_seconds: The maximum amount of time,
in seconds, to gather records before invoking the function.
:param maximum_concurrency: The maximum number of concurrent functions
that the event source can invoke.
.. method:: on_kinesis_record(stream, batch_size=100, starting_position='LATEST', name=None, maximum_batching_window_in_seconds=0)
Create a lambda function and configure it to be automatically invoked
whenever data is published to the specified Kinesis stream.
The lambda function must accept a single parameter which
is of type :class:`KinesisEvent`.
If the decorated function raises an exception, Lambda retries the
batch until processing succeeds or the data expires.
See
`Using AWS Lambda with Amazon Kinesis <https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html>`__
for more information on how Lambda integrates with Kinesis.
.. code-block:: python
app.debug = True
@app.on_kinesis_record(stream='mystream')
def handler(event):
app.log.info("Event: %s", event.to_dict())
for record in event:
app.log.info("Message body: %s", record.data)
:param stream: The name of the Kinesis stream you want to subscribe to.
This is the name of the data stream, not the ARN.
:param batch_size: The maximum number of messages to retrieve
when polling for Kinesis messages. The event parameter can have
multiple Kinesis records associated with it. This is why the
event parameter passed to the lambda function is iterable. The
batch size controls how many messages can be in a single event.
:param starting_position: Specifies where to start processing records.
This can have the following values:
* ``LATEST`` - Process new records that are added to the stream.
* ``TRIM_HORIZON`` - Process all records in the stream.
:param name: The name of the function to use. This name is combined
with the chalice app name as well as the stage name to create the
entire lambda function name. This parameter is optional. If it is
not provided, the name of the python function will be used.
:param maximum_batching_window_in_seconds: The maximum amount of time,
in seconds, to gather records before invoking the function.
.. method:: on_dynamodb_record(stream_arn, batch_size=100, starting_position='LATEST', name=None, maximum_batching_window_in_seconds=0)
Create a lambda function and configure it to be automatically invoked
whenever data is written to a DynamoDB stream.
The lambda function must accept a single parameter which
is of type :class:`DynamoDBEvent`.
If the decorated function raises an exception, Lambda retries the
batch until processing succeeds or the data expires.
See
`Using AWS Lambda with Amazon DynamoDB <https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html>`__
for more information on how Lambda integrates with DynamoDB Streams.
.. code-block:: python
app.debug = True
@app.on_dynamodb_record(stream_arn='arn:aws:dynamodb:...:stream')
def handler(event):
app.log.info("Event: %s", event.to_dict())
for record in event:
app.log.info("New: %s", record.new_image)
:param stream_arn: The name of the DynamoDB stream ARN you want to
subscribe to. Note that, unlike other event handlers that accept
the resource name, you must provide the stream ARN when subscribing
to the DynamoDB stream ARN.
:param batch_size: The maximum number of messages to retrieve
when polling for DynamoDB messages. The event parameter can have
multiple DynamoDB records associated with it. This is why the
event parameter passed to the lambda function is iterable. The
batch size controls how many messages can be in a single event.
:param starting_position: Specifies where to start processing records.
This can have the following values:
* ``LATEST`` - Process new records that are added to the stream.
* ``TRIM_HORIZON`` - Process all records in the stream.
:param name: The name of the function to use. This name is combined
with the chalice app name as well as the stage name to create the
entire lambda function name. This parameter is optional. If it is
not provided, the name of the python function will be used.
:param maximum_batching_window_in_seconds: The maximum amount of time,
in seconds, to gather records before invoking the function.
.. method:: lambda_function(name=None)
Create a pure lambda function that's not connected to anything.
See :doc:`topics/purelambda` for more information.
:param name: The name of the function to use. This name is combined
with the chalice app name as well as the stage name to create the
entire lambda function name. This parameter is optional. If it is
not provided, the name of the python function will be used.
.. method:: register_blueprint(blueprint, name_prefix=None, url_prefix=None)
Register a :class:`Blueprint` to a Chalice app.
See :doc:`topics/blueprints` for more information.
:param blueprint: The :class:`Blueprint` to register to the app.
:param name_prefix: An optional name prefix that's added to all the
resources specified in the blueprint.
:param url_prefix: An optional url prefix that's added to all the
routes defined the Blueprint. This allows you to set the root mount
point for all URLs in a Blueprint.
.. method:: on_ws_connect(event)
Create a Websocket API connect event handler.
:param event: The :class:`WebsocketEvent` received to indicate a new
connection has been registered with API Gateway. The identifier of this
connection is under the :attr:`WebsocketEvent.connection_id` attribute.
see :doc:`topics/websockets` for more information.
.. method:: on_ws_message(event)
Create a Websocket API message event handler.
:param event: The :class:`WebsocketEvent` received to indicate API Gateway
received a message from a connected client. The identifier of the
client that sent the message is under the
:attr:`WebsocketEvent.connection_id` attribute. The content of the
message is available in the :attr:`WebsocketEvent.body` attribute.
see :doc:`topics/websockets` for more information.
.. method:: on_ws_disconnect(event)
Create a Websocket API disconnect event handler.
:param event: The :class:`WebsocketEvent` received to indicate an existing
connection has been disconnected from API Gateway. The identifier of this
connection is under the :attr:`WebsocketEvent.connection_id` attribute.
see :doc:`topics/websockets` for more information.
.. method:: middleware(event_type='all')
Register a middleware with a Chalice application.
This decorator will register a function as Chalice middleware, which
will be automatically invoked as part of the request/response cycle for
a Lambda invocation. You can provide the ``event_type`` argument to
indicate what type of lambda events you want to register with. The
default value, ``all``, indicates that the middleware will be called
for all Lambda functions defined in your Chalice app. Supported
values are:
* ``all`` - ``Any``
* ``s3`` - :class:`S3Event`
* ``sns`` - :class:`SNSEvent`
* ``sqs`` - :class:`SQSEvent`
* ``cloudwatch`` - :class:`CloudWatchEvent`
* ``scheduled`` - :class:`CloudWatchEvent`
* ``websocket`` - :class:`WebsocketEvent`
* ``http`` - :class:`Request`
* ``pure_lambda`` - :class:`LambdaFunctionEvent`
The decorated function must accept two arguments, ``event`` and
``get_response``. The ``event`` is the input event associated with
the Lambda invocation, and ``get_response`` is a callable that takes
an input event and will invoke the next middleware in the chain,
and eventually the original Lambda handler. Below is a noop middleware
that shows the minimum needed to write middleware:
.. code-block:: python
@app.middleware('all')
def mymiddleware(event, get_response):
return get_response(event)
See :doc:`topics/middleware` for more information on writing middleware.
.. method:: register_middleware(func, event_type='all')
Register a middleware with a Chalice application. This is the same
behavior as the :meth:`Chalice.middleware` decorator and is useful
if you want to register middleware for pre-existing functions:
.. code-block:: python
import thirdparty
app.register_middleware(thirdparty.func, 'all')
This class is used to convert a function that wraps/proxies a Lambda function into middleware. This allows this wrapper to automatically be applied to every function in your app. For example, if you had the following logging decorator:
def log_invocation(func):
def wrapper(event, context):
logger.debug("Before lambda function.")
response = func(event, context)
logger.debug("After lambda function.")
return wrapper
@app.lambda_function()
@log_invocation
def myfunction(event, context):
logger.debug("In myfunction().")Rather than decorate every Lambda function with the @log_invocation
decorator, you can instead use ConvertToMiddleware to automatically
apply this wrapper to every Lambda function in your app.
app.register_middleware(ConvertToMiddleware(log_invoation))A class that represents the current request. This is mapped to
the app.current_request object.
@app.route('/objects/{key}', methods=['GET', 'PUT'])
def myobject(key):
request = app.current_request # type: Request
if request.method == 'PUT':
# handle PUT request
pass
elif request.method == 'GET':
# handle GET request
pass.. attribute:: path The path of the HTTP request.
.. attribute:: query_params
A MultiDict of the query params for the request. This value is ``None``
if no query params were provided in the request. The MultiDict acts like a
normal dictionary except that you can call the method ``getlist()`` to get
multiple keys from the same query string parameter
.. code-block:: python
request = app.current_request
# Raises an exception if key doesn't exist, usual Python behavior.
single_param = request.query_params['single']
# None if key doesn't exist, usual Python behavior
another_param = request.query_params.get('another_param')
# A List of all parameters named multi_param, Throws an exception if
# key doesn't exist
multi_param_list = request.query_params.getlist('multi_param')
.. attribute:: headers A dict of the request headers.
.. attribute:: uri_params A dict of the captured URI params. This value is ``None`` if no URI params were provided in the request.
.. attribute:: method The HTTP method as a string.
.. attribute:: json_body The parsed JSON body (``json.loads(raw_body)``). This value will only be non-None if the Content-Type header is ``application/json``, which is the default content type value in chalice.
.. attribute:: raw_body The raw HTTP body as bytes. This is useful if you need to calculate a checksum of the HTTP body.
.. attribute:: context A dict of additional context information.
.. attribute:: stage_vars A dict of configuration for the API Gateway stage. .. attribute:: lambda_context A Lambda context object that is passed to the invoked view by AWS Lambda. You can find out more about this object by reading the `lambda context object documentation <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_.
.. method:: to_dict() Convert the :class:`Request` object to a dictionary. This is useful for debugging purposes. This dictionary is guaranteed to be JSON serializable so you can return this value from a chalice view.
A class that represents the response for the view function. You can optionally return an instance of this class from a view function if you want complete control over the returned HTTP response.
from chalice import Chalice, Response
app = Chalice(app_name='custom-response')
@app.route('/')
def index():
return Response(body='hello world!',
status_code=200,
headers={'Content-Type': 'text/plain'}).. versionadded:: 0.6.0
.. attribute:: body The HTTP response body to send back. This value must be a string.
.. attribute:: headers
An optional dictionary of HTTP headers to send back. This is a dictionary
of header name to header value, e.g ``{'Content-Type': 'text/plain'}``
.. attribute:: status_code The integer HTTP status code to send back in the HTTP response.
Each of these classes below can be provided using the authorizer argument
for an @app.route(authorizer=...) call:
authorizer = CognitoUserPoolAuthorizer(
'MyPool', header='Authorization',
provider_arns=['arn:aws:cognito:...:userpool/name'])
@app.route('/user-pools', methods=['GET'], authorizer=authorizer)
def authenticated():
return {"secure": True}.. versionadded:: 0.8.1
.. attribute:: name The name of the authorizer.
.. attribute:: provider_arns The Cognito User Pool arns to use.
.. attribute:: header The header where the auth token will be specified.
.. versionadded:: 0.8.3
.. versionadded:: 0.8.1
.. attribute:: name The name of the authorizer.
.. attribute:: authorizer_uri
The URI of the lambda function to use for the custom authorizer. This
usually has the form
``arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/{lambda_arn}/invocations``.
.. attribute:: ttl_seconds The number of seconds to cache the returned policy from a custom authorizer.
.. attribute:: header The header where the auth token will be specified.
These classes are used when defining built-in authorizers in Chalice.
An instance of this class is passed as the first argument
to an authorizer defined via @app.authorizer(). You
generally do not instantiate this class directly.
.. attribute:: auth_type The type of authentication
.. attribute:: token The authorization token. This is usually the value of the ``Authorization`` header.
.. attribute:: method_arn The ARN of the API gateway being authorized.
.. attribute:: routes A list of authorized routes. Each element in the list can either by a string route such as `"/foo/bar"` or an instance of ``AuthRoute``. If you specify the URL as a string, then all supported HTTP methods will be authorized. If you want to specify which HTTP methods are allowed, you can use ``AuthRoute``. If you want to specify that all routes and HTTP methods are supported you can use the wildcard value of ``"*"``: ``AuthResponse(routes=['*'], ...)``
.. attribute:: principal_id The principal id of the user.
.. attribute:: context An optional dictionary of key value pairs. This dictionary will be accessible in the ``app.current_request.context`` in all subsequent authorized requests for this user.
.. attribute:: usage_identifier_key An optional string value that represents a usage plan's api key if the ``apiKeySource`` for that plan is set to ``AUTHORIZER``.
This class be used in the routes attribute of a
:class:`AuthResponse` instance to get fine grained control
over which HTTP methods are allowed for a given route.
.. attribute:: path The allowed route specified as a string
.. attribute:: methods A list of allowed HTTP methods.
This class is used to control
how API Gateway interprets Content-Type headers in both requests and
responses.
There is a single instance of this class attached to each
:class:`Chalice` object under the api attribute.
.. attribute:: cors Global cors configuration. If a route-level cors configuration is not provided, or is ``None`` then this configuration will be used. By default it is set to ``False``. This can either be ``True``, ``False``, or an instance of the ``CORSConfig`` class. This makes it easy to enable CORS for your entire application by setting ``app.api.cors = True``. .. versionadded:: 1.12.1
.. attribute:: default_binary_types The value of ``default_binary_types`` are the ``Content-Types`` that are considered binary by default. This value should not be changed, instead you should modify the ``binary_types`` list to change the behavior of a content type. Its value is: ``application/octet-stream``, ``application/x-tar``, ``application/zip``, ``audio/basic``, ``audio/ogg``, ``audio/mp4``, ``audio/mpeg``, ``audio/wav``, ``audio/webm``, ``image/png``, ``image/jpg``, ``image/jpeg``, ``image/gif``, ``video/ogg``, ``video/mpeg``, ``video/webm``.
.. attribute:: binary_types
The value of ``binary_types`` controls how API Gateway interprets
requests and responses as detailed below.
If an incoming request has a ``Content-Type`` header value that is
present in the ``binary_types`` list it will be assumed that its body is
a sequence of raw bytes. You can access these bytes by accessing the
``app.current_request.raw_body`` property.
If an outgoing response from ``Chalice`` has a header ``Content-Type``
that matches one of the ``binary_types`` its body must be a ``bytes``
type object. It is important to note that originating request must have
the ``Accept`` header for the same type as the ``Content-Type`` on the
response. Otherwise a ``400`` error will be returned.
This value can be modified to change what types API Gateway treats as
binary. The easiest way to do this is to simply append new types to
the list.
.. code-block:: python
app.api.binary_types.append('application/my-binary-data')
Keep in mind that there can only be a total of 25 binary types at a time
and Chalice by default has a list of 16 types. It is recommended if you
are going to make extensive use of binary types to reset the list to
the exact set of content types you will be using. This can easily be
done by reassigning the whole list.
.. code-block:: python
app.api.binary_types = [
'application/octet-stream',
'application/my-binary-data',
]
**Implementation Note**: API Gateway and Lambda communicate through a
JSON event which is encoded using ``UTF-8``. The raw bytes are
temporarily encoded using base64 when being passed between API Gateway
and Lambda. In the worst case this encoding can cause the binary body
to be inflated up to ``4/3`` its original size. Lambda only accepts an
event up to ``6mb``, which means even if your binary data was not quite
at that limit, with the base64 encoding it may exceed that limit. This
will manifest as a ``502`` Bad Gateway error.
This class is used to send messages to websocket clients connected to an API Gateway Websocket API.
.. attribute:: session
A boto3 Session that will be used to send websocket messages to
clients. Any custom configuration can be set through a botocore
``session``. This **must** be manually set before websocket features can
be used.
.. code-block:: python
import botocore
from boto3.session import Session
from chalice import Chalice
app = Chalice('example')
session = botocore.session.Session()
session.set_config_variable('retries', {'max_attempts': 0})
app.websocket_api.session = Session(botocore_session=session)
.. method:: configure(domain_name, stage) Configure prepares the :class:`WebsocketAPI` to call the :meth:`send` method. Without first calling this method calls to :meth:`send` will fail with the message ``WebsocketAPI needs to be configured before sending messages.``. This is because a boto3 ``apigatewaymanagementapi`` client must be created from the :attr:`session` with a custom endpoint in order to properly communicate with our API Gateway WebsocketAPI. This method is called on your behalf before each of the websocket handlers: ``on_ws_connect``, ``on_ws_message``, ``on_ws_disconnect``. This ensures that the :meth:`send` method is available in each of those handlers.
.. method:: send(connection_id, message) *requires* ``boto3>=1.9.91`` Method to send a message to a client. The ``connection_id`` is the unique identifier of the socket to send the ``message`` to. The ``message`` must be a utf-8 string. If the socket is disconnected it raises a :class:`WebsocketDisconnectedError` error... method:: close(connection_id) *requires* ``boto3>=1.9.221`` Method to close a WebSocket connection. The ``connection_id`` is the unique identifier of the socket to close. If the socket is already disconnected it raises a :class:`WebsocketDisconnectedError` error... method:: info(connection_id) *requires* ``boto3>=1.9.221`` Method to get info about a WebSocket. The ``connection_id`` is the unique identifier of the socket to get info about. The following is an example of the format this method returns:: { 'ConnectedAt': datetime(2015, 1, 1), 'Identity': { 'SourceIp': 'string', 'UserAgent': 'string' }, 'LastActiveAt': datetime(2015, 1, 1) } If the socket is disconnected it raises a :class:`WebsocketDisconnectedError` error.
An exception raised when a message is sent to a websocket that has disconnected.
.. attribute:: connection_id The unique identifier of the websocket that was disconnected.
CORS configuration to attach to a route, or globally on app.api.cors.
from chalice import CORSConfig
cors_config = CORSConfig(
allow_origin='https://foo.example.com',
allow_headers=['X-Special-Header'],
max_age=600,
expose_headers=['X-Special-Header'],
allow_credentials=True
)
@app.route('/custom_cors', methods=['GET'], cors=cors_config)
def supports_custom_cors():
return {'cors': True}.. versionadded:: 0.8.1
.. attribute:: allow_origin The value of the ``Access-Control-Allow-Origin`` to send in the response. Keep in mind that even though the ``Access-Control-Allow-Origin`` header can be set to a string that is a space separated list of origins, this behavior does not work on all clients that implement CORS. You should only supply a single origin to the ``CORSConfig`` object. If you need to supply multiple origins you will need to define a custom handler for it that accepts ``OPTIONS`` requests and matches the ``Origin`` header against a whitelist of origins. If the match is successful then return just their ``Origin`` back to them in the ``Access-Control-Allow-Origin`` header.
.. attribute:: allow_headers The list of additional allowed headers. This list is added to list of built in allowed headers: ``Content-Type``, ``X-Amz-Date``, ``Authorization``, ``X-Api-Key``, ``X-Amz-Security-Token``.
.. attribute:: expose_headers A list of values to return for the ``Access-Control-Expose-Headers``:
.. attribute:: max_age The value for the ``Access-Control-Max-Age``
.. attribute:: allow_credentials A boolean value that sets the value of ``Access-Control-Allow-Credentials``.
.. versionadded:: 1.0.0b1
An instance of this class can be used as the expression value
in the :meth:`Chalice.schedule` method:
@app.schedule(Rate(5, unit=Rate.MINUTES))
def handler(event):
passExamples:
# Run every minute.
Rate(1, unit=Rate.MINUTES)
# Run every 2 hours.
Rate(2, unit=Rate.HOURS).. attribute:: value An integer value that presents the amount of time to wait between invocations of the scheduled event.
.. attribute:: unit The unit of the provided ``value`` attribute. This can be either ``Rate.MINUTES``, ``Rate.HOURS``, or ``Rate.DAYS``.
.. attribute:: MINUTES, HOURS, DAYS These values should be used for the ``unit`` attribute.
An instance of this class can be used as the expression value
in the :meth:`Chalice.schedule` method.
@app.schedule(Cron(15, 10, '?', '*', '6L', '2002-2005'))
def handler(event):
passIt provides more capabilities than the :class:`Rate` class. There are a few limits:
- You can't specify
day_of_monthandday_of_weekfields in the same Cron expression. If you specify a value in one of the fields, you must use a?in the other. - Cron expressions that lead to rates faster than 1 minute are not supported.
For more information, see the API docs page.
Examples:
# Run at 10:00am (UTC) every day.
Cron(0, 10, '*', '*', '?', '*')
# Run at 12:15pm (UTC) every day.
Cron(15, 12, '*', '*', '?', '*')
# Run at 06:00pm (UTC) every Monday through Friday.
Cron(0, 18, '?', '*', 'MON-FRI', '*')
# Run at 08:00am (UTC) every 1st day of the month.
Cron(0, 8, 1, '*', '?', '*')
# Run every 15 minutes.
Cron('0/15', '*', '*', '*', '?', '*')
# Run every 10 minutes Monday through Friday.
Cron('0/10', '*', '?', '*', 'MON-FRI', '*')
# Run every 5 minutes Monday through Friday between
# 08:00am and 5:55pm (UTC).
Cron('0/5', '8-17', '?', '*', 'MON-FRI', '*')This is the input argument for a scheduled or CloudWatch events.
@app.schedule('rate(1 hour)')
def every_hour(event: CloudWatchEvent):
passIn the code example above, the event argument is of
type CloudWatchEvent, which will have the following
attributes.
.. attribute:: version By default, this is set to 0 (zero) in all events.
.. attribute:: account The 12-digit number identifying an AWS account.
.. attribute:: region Identifies the AWS region where the event originated.
.. attribute:: detail For CloudWatch events this will be the event payload. For scheduled events, this will be an empty dictionary.
.. attribute:: detail_type For scheduled events, this value will be ``"Scheduled Event"``.
.. attribute:: source Identifies the service that sourced the event. All events sourced from within AWS will begin with "aws." Customer-generated events can have any value here as long as it doesn't begin with "aws." We recommend the use of java package-name style reverse domain-name strings. For scheduled events, this will be ``aws.events``.
.. attribute:: time The event timestamp, which can be specified by the service originating the event. If the event spans a time interval, the service might choose to report the start time, so this value can be noticeably before the time the event is actually received.
.. attribute:: event_id A unique value is generated for every event. This can be helpful in tracing events as they move through rules to targets, and are processed.
.. attribute:: resources This JSON array contains ARNs that identify resources that are involved in the event. Inclusion of these ARNs is at the discretion of the service. For scheduled events, this will include the ARN of the CloudWatch rule that triggered this event.
.. attribute:: context A `Lambda context object <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_ that is passed to the handler by AWS Lambda. This is useful if you need the AWS request ID for tracing, or any other data in the context object.
.. method:: to_dict()
Return the original event dictionary provided
from Lambda. This is useful if you need direct
access to the lambda event, for example if a
new key is added to the lambda event that has not
been mapped as an attribute to the ``CloudWatchEvent``
object. Example::
{'account': '123457940291',
'detail': {},
'detail-type': 'Scheduled Event',
'id': '12345678-b9f1-4667-9c5e-39f98e9a6113',
'region': 'us-west-2',
'resources': ['arn:aws:events:us-west-2:123457940291:rule/testevents-dev-every_minute'],
'source': 'aws.events',
'time': '2017-06-30T23:28:38Z',
'version': '0'}
This is the input argument for an S3 event.
@app.on_s3_event(bucket='mybucket')
def event_handler(event: S3Event):
app.log.info("Event received for bucket: %s, key %s",
event.bucket, event.key)In the code example above, the event argument is of
type S3Event, which will have the following
attributes.
.. attribute:: bucket The S3 bucket associated with the event.
.. attribute:: key The S3 key name associated with the event. The original key name in the S3 event payload is URL encoded. However, this ``key`` attribute automatically URL decodes the key name for you. If you need access to the original URL encoded key name, you can access it through the ``to_dict()`` method.
.. attribute:: context A `Lambda context object <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_ that is passed to the handler by AWS Lambda. This is useful if you need the AWS request ID for tracing, or any other data in the context object.
.. method:: to_dict() Return the original event dictionary provided from Lambda. This is useful if you need direct access to the lambda event, for example if a new key is added to the lambda event that has not been mapped as an attribute to the ``S3Event`` object. Note that this event is not modified in any way. This means that the key name of the S3 object is URL encoded, which is the way that S3 sends this value to Lambda.
This is the input argument for an SNS event handler.
@app.on_sns_message(topic='mytopic')
def event_handler(event: SNSEvent):
app.log.info("Message received with subject: %s, message: %s",
event.subject, event.message)In the code example above, the event argument is of
type SNSEvent, which will have the following
attributes.
.. attribute:: subject The subject of the SNS message that was published.
.. attribute:: message The string value of the SNS message that was published.
.. attribute:: context A `Lambda context object <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_ that is passed to the handler by AWS Lambda. This is useful if you need the AWS request ID for tracing, or any other data in the context object.
.. method:: to_dict() Return the original event dictionary provided from Lambda. This is useful if you need direct access to the lambda event, for example if a new key is added to the lambda event that has not been mapped as an attribute to the ``SNSEvent`` object.
This is the input argument for an SQS event handler.
@app.on_sqs_message(queue='myqueue')
def event_handler(event: SQSEvent):
app.log.info("Event: %s", event.to_dict())In the code example above, the event argument is of
type SQSEvent. An SQSEvent can have multiple
sqs messages associated with it. To access the multiple
messages, you can iterate over the SQSEvent.
.. method:: __iter__() Iterate over individual SQS messages associated with the event. Each element in the iterable is of type :class:`SQSRecord`.
.. attribute:: context A `Lambda context object <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_ that is passed to the handler by AWS Lambda. This is useful if you need the AWS request ID for tracing, or any other data in the context object.
.. method:: to_dict() Return the original event dictionary provided from Lambda. This is useful if you need direct access to the lambda event, for example if a new key is added to the lambda event that has not been mapped as an attribute to the ``SQSEvent`` object.
Represents a single SQS record within an :class:`SQSEvent`.
.. attribute:: body The body of the SQS message.
.. attribute:: receipt_handle The receipt handle associated with the message. This is useful if you need to manually delete an SQS message to account for partial failures.
.. attribute:: context A `Lambda context object <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_ that is passed to the handler by AWS Lambda.
.. method:: to_dict() Return the original dictionary associated with the given message. This is useful if you need direct access to the lambda event.
This is the input argument for a Kinesis data stream event handler.
@app.on_kinesis_record(stream='mystream')
def event_handler(event: KinesisEvent):
app.log.info("Event: %s", event.to_dict())In the code example above, the event argument is of
type KinesisEvent. A KinesisEvent can have multiple
messages associated with it. To access the multiple
messages, you can iterate over the KinesisEvent.
.. method:: __iter__() Iterate over individual Kinesis records associated with the event. Each element in the iterable is of type :class:`KinesisRecord`.
.. attribute:: context A `Lambda context object <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_ that is passed to the handler by AWS Lambda. This is useful if you need the AWS request ID for tracing, or any other data in the context object.
.. method:: to_dict() Return the original event dictionary provided from Lambda. This is useful if you need direct access to the lambda event, for example if a new key is added to the lambda event that has not been mapped as an attribute to the ``SQSEvent`` object.
Represents a single Kinesis record within a :class:`KinesisEvent`.
.. attribute:: data The payload data for the Kinesis record. This data is automatically base64 decoded for you and will be a ``bytes`` type.
.. attribute:: sequence_number The unique identifier of the record within its shard.
.. attribute:: partition_key Identifies which shard in the stream the data record is assigned to.
.. attribute:: schema_version Schema version for the record.
.. attribute:: timestamp The approximate time that the record was inserted into the stream. This is automatically converted to a ``datetime.datetime`` object.
.. attribute:: context A `Lambda context object <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_ that is passed to the handler by AWS Lambda.
.. method:: to_dict() Return the original dictionary associated with the given message. This is useful if you need direct access to the lambda event.
This is the input argument for a DynamoDB stream event handler.
@app.on_dynamodb_record(stream_arn='arn:aws:us-west-2:.../stream')
def event_handler(event: DynamoDBEvent):
app.log.info("Event: %s", event.to_dict())
for record in event:
app.log.info(record.to_dict())In the code example above, the event argument is of
type DynamoDBEvent. A DynamoDBEvent can have multiple
messages associated with it. To access the multiple
messages, you can iterate over the DynamoDBEvent.
.. method:: __iter__() Iterate over individual DynamoDB records associated with the event. Each element in the iterable is of type :class:`DynamoDBRecord`.
.. attribute:: context A `Lambda context object <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_ that is passed to the handler by AWS Lambda. This is useful if you need the AWS request ID for tracing, or any other data in the context object.
.. method:: to_dict() Return the original event dictionary provided from Lambda. This is useful if you need direct access to the lambda event, for example if a new key is added to the lambda event that has not been mapped as an attribute to the ``SQSEvent`` object.
Represents a single DynamoDB record within a :class:`DynamoDBEvent`.
.. attribute:: timestamp The approximate time that the record was the stream record was created. This is automatically converted to a ``datetime.datetime`` object.
.. attribute:: keys The primary key attribute(s) for the DynamoDB item that was modified.
.. attribute:: new_image The item in the DynamoDB table as it appeared after it was modified.
.. attribute:: old_image The item in the DynamoDB table as it appeared before it was modified.
.. attribute:: sequence_number The sequence number of the stream record.
.. attribute:: size_bytes The size of the stream record, in bytes.
.. attribute:: stream_view_type The type of data from the modified DynamoDB item.
.. attribute:: aws_region The region associated with the event.
.. attribute:: event_id A unique identifier for the event.
.. attribute:: event_name The type of data modification that was performed on the DynamoDB table. This can be: ``INSERT``, ``MODIFY``, or ``DELETE``.
.. attribute:: event_source_arn The ARN of the DynamoDB stream.
.. attribute:: table_name The name of the DynamoDB table associated with the stream. This value is computed from the ``event_source_arn`` parameter and will be an empty string if Chalice is unable to parse the table name from the event source ARN.
.. attribute:: context A `Lambda context object <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_ that is passed to the handler by AWS Lambda.
.. method:: to_dict() Return the original dictionary associated with the given message. This is useful if you need direct access to the lambda event.
This is the input argument of middleware registered to a
pure Lambda function (@app.lambda_function()).
.. attribute:: event The original input event dictionary.
.. attribute:: context A `Lambda context object <https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html>`_ that is passed to the handler by AWS Lambda.
An object used for grouping related handlers together.
This is primarily used as a mechanism for organizing your lambda
handlers. Any decorator methods defined in the :class:`Chalice`
object are also defined on a Blueprint object. You can register
a blueprint to a Chalice app using the :meth:`Chalice.register_blueprint`
method.
The import_name is the module in which the Blueprint is defined.
It is used to construct the appropriate handler string when creating
the Lambda functions associated with a Blueprint. This is typically
the __name__ attribute:mybp = Blueprint(__name__).
See :doc:`topics/blueprints` for more information.
# In ./app.py
from chalice import Chalice
from chalicelib import myblueprint
app = Chalice(app_name='blueprints')
app.register_blueprint(myblueprint)
# In chalicelib/myblueprint.py
from chalice import Blueprint
myblueprint = Blueprint(__name__)
@myblueprint.route('/')
def index():
return {'hello': 'world'}Event object event that is passed as the sole arugment to any handler
function decorated with one of the three websocket related handlers:
on_ws_connect, on_ws_disconnect, on_ws_message.
.. attribute:: domain_name The domain name of the endpoint for the API Gateway Websocket API.
.. attribute:: stage The API Gateway stage of the Websocket API.
.. attribute:: connection_id A handle that uniquely identifies a connection with API Gateway.
.. attribute:: body The message body received. This is only populated on the ``on_ws_message`` otherwise it will be set to ``None``.
.. attribute:: json_body The parsed JSON body (``json.loads(body)``) of the message. If the body is not JSON parsable then using this attribute will raise a ``ValueError``.
See :doc:`topics/websockets` for more information.
A test client used to write tests for Chalice apps. It allows you to test Lambda function invocation as well as REST APIs. Depending on what you want to test, you'll access the various attributes of this class. You can use this class as a context manager. When entering the context manager, any environment variables specified for your function will be set. The original environment variables are put back when the block is exited:
from chalice.test import Client
with Client(app) as client:
result = client.http.post("/my-data")See the :doc:`topics/testing` documentation for more details on testing your Chalice app.
.. attribute:: lambda_ Returns the Lambda test client :class:`TestLambdaClient`.
.. attribute:: http Returns the test client for REST APIs :class:`TestHTTPClient`.
.. attribute:: events Returns the test client for generating Lambda events :class:`TestEventsClient`.
Test client for invoking Lambda functions. This class should not be
instantiated directly, and instead should be accessed via the
Client.lambda_ attribute:
@app.lambda_function()
def myfunction(event, context):
return {"hello": "world"}
with Client(app) as client:
result = client.lambda_.invoke("myfunction")
assert result.payload == {"hello": "world"}.. method:: invoke(function_name, payload=None) Invoke a Lambda function by name. The name should match the resource name of the function. This is typically the name of the python function unless an explicit ``name=`` kwarg is provided when registering the function. Returns an :class:`InvokeResponse` instance.
Test client for REST APIs. This class should not be
instantiated directly, and instead should be accessed via the
Client.http attribute:
with Client(app) as client:
response = client.http.get("/my-route").. method:: request(method, path, headers=None, body=b'')
Makes a test HTTP request to your REST API. Returns
an :class:`HTTPResponse`. You can also use the methods below
to make a request with a specific HTTP method instead of using
this method directly, e.g. ``client.http.get("/foo")`` instead
of ``client.http.request("GET", "/foo")``.
.. method:: get(path, \*\*kwargs) Makes an HTTP GET request.
.. method:: post(path, \*\*kwargs) Makes an HTTP POST request.
.. method:: put(path, \*\*kwargs) Makes an HTTP PUT request.
.. method:: patch(path, \*\*kwargs) Makes an HTTP PATCH request.
.. method:: options(path, \*\*kwargs) Makes an HTTP OPTIONS request.
.. method:: delete(path, \*\*kwargs) Makes an HTTP DELETE request.
.. method:: head(path, \*\*kwargs) Makes an HTTP HEAD request.
Test client for generating Lambda events. This class should not be
instantiated directly, and instead should be accessed via the
Client.events attribute:
with Client(app) as client:
result = client.lambda_.invoke(
"my_sns_handler",
client.events.generate_sns_event("Hello world")
).. method:: generate_sns_event(message, subject='') Generates a sample SNS event.
.. method:: generate_s3_event(bucket, key, event_name='ObjectCreated:Put') Generates a sample S3 event.
.. method:: generate_sqs_event(message_bodies, queue_name='queue-name') Generates a sample SQS event.
.. method:: generate_cw_event(source, detail_type, detail, resources, region='us-west-2') Generates a sample CloudWatch event.
.. method:: generate_kinesis_event(message_bodies, stream_name='stream-name') Generates a Kinesis event.
.. attribute:: body The body of the HTTP response, in ``bytes``.
.. attribute:: headers A dictionary of HTTP headers in the resopnse.
.. attribute:: status_code The status code of the HTTP response.
.. attribute:: payload The response payload of Lambda invocation.
The Chalice CDK construct is available in the chalice.cdk namespace.
For more details on using the AWS CDK with Chalice, see :doc:`tutorials/cdk`.
from chalice import cdkA test client used to write tests for Chalice apps. It allows you to
| param scope: | The CDK scope that the construct is created within. |
|---|---|
| param str id: | The identifier for the construct. Must be unique within the scope in which it's created. |
| param str source_dir: | Path to Chalice application source code. |
| param dict stage_config: | Chalice stage configuration. The configuration object should have the same structure as Chalice JSON stage configuration. |
| param bool preserve_logical_ids: | Whether the resources should have
the same logical IDs in the resulting CDK template as they did in
the original CloudFormation template file. If you're vending a
Construct using cdk-chalice, make sure to pass this as False.
Note: regardless of whether this option is true or false, the
:attr:`sam_template`'s get_resource and related methods always
uses the original logical ID of the resource/element, as specified
in the template file. |
| raises ChaliceError: | Error packaging the Chalice application. |
chalice = Chalice(
self, 'ChaliceApp', source_dir='../runtime',
stage_config={
'environment_variables': {
'MY_ENV_VAR': 'FOO'
}
}
).. method:: get_resource(resource_name) Returns a low-level CfnResource from the resources in a Chalice app with the given resource name. The resource name corresponds to the logical ID of the underlying resource in the SAM template. Any modifications performed on that resource will be reflected in the resulting CDK template. :param str resource_name: The logical ID of the resource in the SAM template. :rtype: aws_cdk.cdk.CfnResource
.. method:: get_role(resource_name)
Returns an ``IRole`` for an underlying SAM template resource. This is useful
if you want to grant additional permissions to an IAM role constructed by Chalice.
.. code-block:: python
dynamodb_table = dynamodb.Table(...)
chalice = Chalice(scope, 'ChaliceApp', ....)
dynamodb_table.grant_read_write_data(chalice.get_role('DefaultRole'))
:param str resource_name: The logical ID of the resource in the SAM template.
:rtype: aws_cdk.aws_iam.IRole
.. method:: get_function(resource_name) Returns an ``IFunction`` for an underlying SAM template resource. :param str resource_name: The logical ID of the resource in the SAM template. :rtype: aws_cdk.aws_lambda.IFunction
.. method:: add_environment_variable(key, value, function_name) Convenience function to add environment variables to a single Lambda function constructed by Chalice. You can also add environment variables to Lambda functions using the ``stage_config`` parameter when creating the ``Chalice()`` construct. :param str key: The environment variable key name. :param str value: The value of the environment variable. :param str function_name: The logical ID of the Lambda function resource.