Yandex Cloud
  • Services
  • Solutions
  • Why Yandex Cloud
  • Pricing
  • Documentation
  • Contact us
Get started
Language / Region
© 2022 Yandex.Cloud LLC
Yandex Cloud Functions
  • Comparison with other Yandex Cloud services
  • Getting started
    • Overview
    • Creating a function
      • Overview
      • Node.js
      • Python
      • Go
      • PHP
      • Bash
      • Java
    • Creating a trigger
      • Overview
      • Timer
      • Trigger for Message Queue
      • Trigger for Object Storage
      • Trigger for Container Registry
      • Trigger for Cloud Logs
      • Trigger for Cloud Logging
      • Trigger for Yandex IoT Core
      • Trigger for budgets
      • Trigger for Data Streams
  • Step-by-step instructions
    • All instructions
    • Using functions to get an IAM token for a service account
    • Connecting to managed databases from functions
    • Managing rights to access functions
    • Managing functions
      • Creating a function
      • Managing function versions
      • Working in the code editor
      • Invoking a function
      • Updating a function
      • Scaling a function
      • Function monitoring
      • Viewing the execution log
      • Deleting a function
    • Managing triggers
      • Getting information about a trigger
      • Creating a timer
      • Creating a trigger for Message Queue
      • Creating a trigger for Object Storage
      • Creating a trigger for Container Registry
      • Creating a trigger for Cloud Logs
      • Creating a trigger for Cloud Logging
      • Creating a trigger for Yandex IoT Core
      • Creating a trigger for budgets
      • Creating a trigger for Data Streams
      • Updating a trigger
      • Trigger monitoring
      • Deleting a trigger
  • Concepts
    • Overview
    • Function
    • Invoking a function
    • Runtime environment
      • Overview
      • Environment
      • Execution context
      • Preloaded runtime environment
    • Builder
    • Trigger
      • Overview
      • Timer
      • Trigger for Message Queue
      • Trigger for Object Storage
      • Trigger for Container Registry
      • Trigger for Cloud Logs
      • Trigger for Cloud Logging
      • Trigger for Yandex IoT Core
      • Trigger for budgets
      • Trigger for Data Streams
    • Dead Letter Queue
    • Log groups
    • Backups
    • Quotas and limits
  • Developing in Node.js
    • Overview
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
    • Using the SDK
  • Developing in Python
    • Overview
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
    • Using the SDK
  • Developing in Go
    • Overview
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
    • Using the SDK
  • Developing in PHP
    • Overview
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
  • Developing in Bash
    • Overview
    • Request handler
    • Logging
    • Handling errors
    • Using the SDK
  • Developing in Java
    • Overview
    • Programming model
      • Overview
      • Function interface
      • YcFunction interface
      • HttpServlet class
      • Spring Boot
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
    • Using the SDK
  • Developing in R
    • Overview
    • Programming model
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
  • Developing in C#
    • Overview
    • Programming model
      • Overview
      • Function interface
      • YcFunction interface
    • Managing dependencies
    • Request handler
    • Invocation context
    • Logging
    • Handling errors
    • Using the SDK
  • Practical guidelines
    • Creating skills for Alice
    • Deploying a web application
    • Developing a skill for Alice and a website with authorization
    • Writing data from a device to Managed Service for PostgreSQL
    • Developing a Slack bot
    • Developing a Telegram bot
    • Connecting to a YDB database from a Python function
    • Connecting to a YDB database from a function in Node.js
    • Converting a video to a GIF in Python
    • Creating a Node.js function using TypeScript
  • Pricing policy
  • Access management
  • API Functions reference
    • Authentication in the API
    • gRPC
      • Overview
      • FunctionService
      • OperationService
    • REST
      • Overview
      • Function
        • Overview
        • create
        • createVersion
        • delete
        • get
        • getVersion
        • getVersionByTag
        • list
        • listAccessBindings
        • listOperations
        • listRuntimes
        • listScalingPolicies
        • listTagHistory
        • listVersions
        • removeScalingPolicy
        • removeTag
        • setAccessBindings
        • setScalingPolicy
        • setTag
        • update
        • updateAccessBindings
  • API Triggers reference
    • Authentication in the API
    • gRPC
      • Overview
      • TriggerService
      • OperationService
    • REST
      • Overview
      • Trigger
        • Overview
        • create
        • delete
        • get
        • list
        • listOperations
        • pause
        • resume
        • update
  • Questions and answers
  1. Developing in Python
  2. Request handler

Python function call handler

Written by
Yandex Cloud
  • Handler types
  • Synchronous handler
  • Asynchronous handler
  • Examples
    • HTTP request structure output

A call handler is a method used to process each Python function call. When creating a function version, you should specify an entry point that consists of a file name and a call handler name (such as, main.handler).

Note

At any given time, a single function instance processes only one request. This lets you use global variables without having to provide data integrity control.

When invoking the handler, the runtime passes the following arguments:

  1. Call body (event parameter):

    • If the call body is a JSON document, it's converted to dict using the json.loads method.
    • If a function was invoked with the integration=raw request string parameter, the HTTP request body is passed to the function as-is (unprocessed).
  2. Invocation context (context parameter).

    The context contains the necessary information about the function version. The structure of this object is described in Python function invocation context.

Handler types

A function can use both synchronous and asynchronous request handlers.

Synchronous handler

To have the output returned, use the return statement or raise an exception using the raise statement. A synchronous function must return a result or throw an exception.

Asynchronous handler

A handler can be an async def asynchronous function. In this case you can use the following statements:

  • return: Returns the function response.
  • raise: Reports an error to the runtime environment.
  • await: Tracks the execution of asynchronous function invocations.

Note

The service only supports the asyncio library as a runtime environment for asynchronous functions.

For more information about development using async/await, see the relevant documentation section.

Examples

HTTP request structure output

The following function outputs the request structure and invocation context to both the execution log and function response:

import json


def handler(event, context):
    return {
        'statusCode': 200,
        'body': json.dumps(
            {
                'event': event,
                'context': context,
            },
            default=vars,
        ),
    }

Function invocation example:

curl --data '{"hello": "world"}' -H 'Content-Type: application/json' https://functions.yandexcloud.net/d4eo2faf62**********?param=one

Result:

{
    "context": {
        "aws_request_id": "6e8356f9-489b-4c7b-8ba6-c8cd74f25455",
        "deadline_ms": 1657713543198,
        "function_name": "d4eo2faf62**********",
        "function_version": "d4e3vrugh3**********",
        "invoked_function_arn": "d4eo2faf62**********",
        "log_group_name": "ckgjmanjlh**********",
        "log_stream_name": "d4e3vrugh3**********",
        "memory_limit_in_mb": 128,
        "request_id": "6e8356f9-489b-4c7b-8ba6-c8cd74f25455",
        "token": {
            "access_token": "<IAM token>",
            "expires_in": 42299,
            "token_type": "Bearer"
        }
    },
    "event": {
        "body": "{\"hello\": \"world\"}",
        "headers": {
            "Accept": "*/*",
            "Content-Length": "18",
            "Content-Type": "application/json",
            "Host": "functions.yandexcloud.net",
            "User-Agent": "curl/7.64.1",
            "X-Forwarded-For": "109.252.148.209",
            "X-Real-Remote-Address": "[109.252.148.209]:2816",
            "X-Request-Id": "6e8356f9-489b-4c7b-8ba6-c8cd74f25455",
            "X-Trace-Id": "e9fe9b05-c1aa-4fb8-94d8-a514fd6f3ff7"
        },
        "httpMethod": "POST",
        "isBase64Encoded": false,
        "multiValueHeaders": {
            "Accept": [
                "*/*"
            ],
            "Content-Length": [
                "18"
            ],
            "Content-Type": [
                "application/json"
            ],
            "Host": [
                "functions.yandexcloud.net"
            ],
            "User-Agent": [
                "curl/7.64.1"
            ],
            "X-Forwarded-For": [
                "109.252.148.209"
            ],
            "X-Real-Remote-Address": [
                "[109.252.148.209]:2816"
            ],
            "X-Request-Id": [
                "6e8356f9-489b-4c7b-8ba6-c8cd74f25455"
            ],
            "X-Trace-Id": [
                "e9fe9b05-c1aa-4fb8-94d8-a514fd6f3ff7"
            ]
        },
        "multiValueParams": {},
        "multiValueQueryStringParameters": {
            "param": [
                "one"
            ]
        },
        "params": {},
        "pathParams": {},
        "queryStringParameters": {
            "param": "one"
        },
        "requestContext": {
            "httpMethod": "POST",
            "identity": {
                "sourceIp": "109.252.148.209",
                "userAgent": "curl/7.64.1"
            },
            "requestId": "6e8356f9-489b-4c7b-8ba6-c8cd74f25455",
            "requestTime": "13/Jul/2022:11:58:59 +0000",
            "requestTimeEpoch": 1657713539
        },
        "url": ""
    }
}

Was the article helpful?

Language / Region
© 2022 Yandex.Cloud LLC
In this article:
  • Handler types
  • Synchronous handler
  • Asynchronous handler
  • Examples
  • HTTP request structure output