Python aws lambda example

Building Lambda functions with Python

You can run Python code in AWS Lambda. Lambda provides runtimes for Python that run your code to process events. Your code runs in an environment that includes the SDK for Python (Boto3), with credentials from an AWS Identity and Access Management (IAM) role that you manage.

Lambda supports the following Python runtimes.

The runtime information in this table undergoes continuous updates. For more information on using AWS SDKs in Lambda, see Managing AWS SDKs in Lambda functions in Serverless Land.

To create a Python function
  • Function name: Enter a name for the function.
  • Runtime: Choose Python 3.10.

The console creates a Lambda function with a single source file named lambda_function . You can edit this file and add more files in the built-in code editor. To save your changes, choose Save. Then, to run your code, choose Test.

Note

The Lambda console uses AWS Cloud9 to provide an integrated development environment in the browser. You can also use AWS Cloud9 to develop Lambda functions in your own environment. For more information, see Working with AWS Lambda functions using the AWS Toolkit in the AWS Cloud9 user guide.

Note

To get started with application development in your local environment, deploy one of the sample applications available in this guide’s GitHub repository.

Читайте также:  Зачем нужен абстрактный класс java
Sample Lambda applications in Python
  • blank-python – A Python function that shows the use of logging, environment variables, AWS X-Ray tracing, layers, unit tests and the AWS SDK.

Your Lambda function comes with a CloudWatch Logs log group. The function runtime sends details about each invocation to CloudWatch Logs. It relays any logs that your function outputs during invocation. If your function returns an error, Lambda formats the error and returns it to the invoker.

Topics

Источник

Lambda function handler in Python

The Lambda function handler is the method in your function code that processes events. When your function is invoked, Lambda runs the handler method. Your function runs until the handler returns a response, exits, or times out.

You can use the following general syntax when creating a function handler in Python:

def handler_name(event, context): . return some_value

Naming

The Lambda function handler name specified at the time that you create a Lambda function is derived from:

  • The name of the file in which the Lambda handler function is located.
  • The name of the Python handler function.

A function handler can be any name; however, the default name in the Lambda console is lambda_function.lambda_handler . This function handler name reflects the function name ( lambda_handler ) and the file where the handler code is stored ( lambda_function.py ).

If you create a function in the console using a different file name or function handler name, you must edit the default handler name.

To change the function handler name (console)
  1. Open the Functions page of the Lambda console and choose your function.
  2. Choose the Code tab.
  3. Scroll down to the Runtime settings pane and choose Edit.
  4. In Handler, enter the new name for your function handler.
  5. Choose Save.

How it works

When Lambda invokes your function handler, the Lambda runtime passes two arguments to the function handler:

  • The first argument is the event object. An event is a JSON-formatted document that contains data for a Lambda function to process. The Lambda runtime converts the event to an object and passes it to your function code. It is usually of the Python dict type. It can also be list , str , int , float , or the NoneType type. The event object contains information from the invoking service. When you invoke a function, you determine the structure and contents of the event. When an AWS service invokes your function, the service defines the event structure. For more information about events from AWS services, see Using AWS Lambda with other services.
  • The second argument is the context object. A context object is passed to your function by Lambda at runtime. This object provides methods and properties that provide information about the invocation, function, and runtime environment.

Returning a value

Optionally, a handler can return a value. What happens to the returned value depends on the invocation type and the service that invoked the function. For example:

  • If you use the RequestResponse invocation type, such as Synchronous invocation, AWS Lambda returns the result of the Python function call to the client invoking the Lambda function (in the HTTP response to the invocation request, serialized into JSON). For example, AWS Lambda console uses the RequestResponse invocation type, so when you invoke the function on the console, the console will display the returned value.
  • If the handler returns objects that can’t be serialized by json.dumps , the runtime returns an error.
  • If the handler returns None , as Python functions without a return statement implicitly do, the runtime returns null .
  • If you use the Event invocation type (an asynchronous invocation), the value is discarded.
Note

In Python 3.9 and later releases, Lambda includes the requestId of the invocation in the error response.

Examples

The following section shows examples of Python functions you can use with Lambda. If you use the Lambda console to author your function, you do not need to attach a .zip archive file to run the functions in this section. These functions use standard Python libraries which are included with the Lambda runtime you selected. For more information, see Lambda deployment packages.

Returning a message

The following example shows a function called lambda_handler . The function accepts user input of a first and last name, and returns a message that contains data from the event it received as input.

def lambda_handler(event, context): message = 'Hello > >!'.format(event['first_name'], event['last_name']) return  'message' : message >

You can use the following event data to invoke the function:

 "first_name": "John", "last_name": "Smith" >

The response shows the event data passed as input:

Parsing a response

The following example shows a function called lambda_handler . The function uses event data passed by Lambda at runtime. It parses the environment variable in AWS_REGION returned in the JSON response.

import os import json def lambda_handler(event, context): json_region = os.environ['AWS_REGION'] return  "statusCode": 200, "headers":  "Content-Type": "application/json" >, "body": json.dumps( "Region ": json_region >) >

You can use any event data to invoke the function:

 "key1": "value1", "key2": "value2", "key3": "value3" >

Lambda runtimes set several environment variables during initialization. For more information on the environment variables returned in the response at runtime, see Using Lambda environment variables.

The function in this example depends on a successful response (in 200 ) from the Invoke API. For more information on the Invoke API status, see the Invoke Response Syntax.

Returning a calculation

The following example shows a function called lambda_handler . The function accepts user input and returns a calculation to the user. For more information about this example, see the aws-doc-sdk-examples GitHub repository .

import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): . result = None action = event.get('action') if action == 'increment': result = event.get('number', 0) + 1 logger.info('Calculated result of %s', result) else: logger.error("%s is not a valid action.", action) response = 'result': result> return response

You can use the following event data to invoke the function:

 "action": "increment", "number": 3 >

Источник

Обработка изображений на AWS Lambda и API Gateway за 10 минут

Давайте узнаем, сможем ли мы создать простое приложение на Python 3.6, которое:

Доступно через API, которое

  • без готового сервера
  • без оплаты (за исключением случаев, где ваш трафик превысит бесплатный пакет Lambda)

Для этого примера мы используем сервис от AWS под названием Lambda, который позволит вам развернуть вашу функцию и ее зависимости, а также легко подключить ее к API. Чтобы создать API, мы воспользуемся API Gateway — еще один сервис, предоставляемый AWS.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Для простоты данного руководства, мы развернем наш код, загрузив его в Lambda через веб консоль AWS. Мы также напишем код нашей функции внутри консоли AWS, чтобы сохранять процесс максимально простым. В любом другом случае вам нужно выполнять развертывание через AWS CLI.

1. Начнем с входа в консоль AWS и поиск Lambda.

Обработка изображений на AWS Lambda и API Gateway за 10 минут

2. Нажимаем на Create function (создать функцию).

Обработка изображений на AWS Lambda и API Gateway за 10 минут

3. Настраиваем параметры функции.

Мы назовем нашу функцию lambda-demo . Нужно убедиться, что мы работаем с Python 3.6 в качестве среды выполнения и создайте новую роль из шаблонов политики AWS.

Обработка изображений на AWS Lambda и API Gateway за 10 минут

4. После создания функции, вам дадут определенный шаблонный код в консоли Lambda.

Вы можете сразу вызвать эту функцию, настроив тестовое событие. Нажмите на Test и настройте первое тестовое событие. Для целей данной статьи, шаблон по умолчанию работает как надо.

Обработка изображений на AWS Lambda и API Gateway за 10 минут

Обработка изображений на AWS Lambda и API Gateway за 10 минут

После создания тестового события, нажмите Test. Вы должны получить следующее в логах функции:

Теперь создадим что-нибудь более полезное.

Построим функцию, которая получает изображение и делает её черно-белым. Для этого мы воспользуемся OpenCV. Кроме этого, использование OpenCV может быть идеальным для такой задачи, она показывает, как такая полезная библиотека может быть добавлена в вашу среду Lambda с относительной легкостью.

Сейчас мы сделаем следующее:

  1. Генерируем заточенный под Python пакет Lambda для OpenCV.
  2. Загрузим пакет в Lambda Layers, так что он может быть использован в любой функции, которую вы создаете.
  3. Импортируем OpenCV в нашу функцию Lambda.

Генерация заточенного под Python пакет Lambda для OpenCV

Я собрал очень простой инструмент — образ Docker, который может получить любой пакет pip и генерировать .ZIP , который мы можем загружать в Lambda Layers. Если вы хотите изучить этот инструмент, вы можете найти его в LambdaZipper.

Если у вас есть установленный Docker, вы можете открыть терминал и запустить следующее:

Это все! В вашей текущей рабочей папке вы можете найти opencv-python.zip

Один из самых полезных безсерверных наборов инструментов — это serverless. Однако мы не будем использовать его в данном примере. Изобретение велосипеда далеко не всегда хорошая идея, за исключением тех случаев, когда вы хотите изучить, как и что устроено внутри. Несмотря на то, что такие продвинутые фреймворки как serverless существуют, хорошей идеей будет найти ряд корневых функций, которые эти фреймворки абстрагируют.

Давайте узнаем, что наш инструмент абстрагирует от нас.

Если вы взглянете на package.sh, то вы увидите, что он выполнил команду установки pip install с аргументом opencv-python . Все это было выполнено в среде amazonlinux:2017.03 , которая в некоторой степени имитирует среду AWS Lambda. Вы можете изучить среду выполнения в Dockerfile.

Загрузка пакета в Lambda Layers для использования в любой из созданых функций

Давайте загрузим opencv-python.zip в Lambda Layers, чтобы мы могли использовать этот пакет во всех наших функциях. Относитесь к Layers как к данным, которые могут быть использованы в любой из написанных вами функций. Это могут быть модули Python, части кодов, бинарные файлы, и т.д.

Перейдите в панель Layers в AWS Lambda и нажмите создать слой (Create layer).

Обработка изображений на AWS Lambda и API Gateway за 10 минут

Укажите название слоя, его описание и загрузите zip файл. Убедитесь в том, что выбрали правильную среду выполнения (в нашем случае это Python 3.6). Нажмите создать слой (Create layer).

Обработка изображений на AWS Lambda и API Gateway за 10 минут

На момент написания этой статьи, загрузка zip файла из веб интерфейса ограничено 50МВ. К счастью, наш пакет opencv-python весит меньше. В случае, если ваш пакет весит больше, вы можете загрузить пакет в качестве ссылки из корзины S3 . Обратите внимание на то, что Lambda указывает ограничение развертывание пакета в 250MB.

После создания функции, вас должно приветствовать уведомление:

Источник

Оцените статью