Connecting to a Managed Service for YDB database from a Python function in Yandex Cloud Functions
Create a function with a Python
A function with an associated service account is authorized in YDB via the metadata service.
The application creates a YDB database connection driver, a session, and a transaction, and runs a query using the ydb
library. This library is installed as a dependency when creating a function version. The DB connection parameters are passed to the application via environment variables.
To create a function and connect to the database:
- Prepare your cloud.
- Create a service account.
- Create a YDB database.
- Create a function.
- Test the function.
If you no longer need the resources you created, delete them.
Prepare your cloud
Sign up for Yandex Cloud and create a billing account:
- Go to the management console
and log in to Yandex Cloud or create an account if you do not have one yet. - On the Yandex Cloud Billing
page, make sure you have a billing account linked and it has theACTIVE
orTRIAL_ACTIVE
status. If you do not have a billing account, create one.
If you have an active billing account, you can go to the cloud page
Learn more about clouds and folders.
Required paid resources
The infrastructure support cost for this scenario includes:
- Fee for using the function (see Yandex Cloud Functions pricing).
- Fee for running queries to the database (see Managed Service for YDB pricing).
Create a service account
-
In the management console
, select the folder where you want to create a service account. -
In the list of services, select Identity and Access Management.
-
Click Create service account.
-
Enter a name for the service account, e.g.,
sa-function
. The naming requirements are as follows:- The name must be from 3 to 63 characters long.
- It may contain lowercase Latin letters, numbers, and hyphens.
- The first character must be a letter and the last character cannot be a hyphen.
-
Click Add role and select
editor
. -
Click Create.
Create a YDB database
-
In the management console
, select the folder where you want to create a database. -
In the list of services, select Managed Service for YDB.
-
Click Create a database.
-
Name the database. The naming requirements are as follows:
- The name must be from 3 to 63 characters long.
- It may contain lowercase Latin letters, numbers, and hyphens.
- The first character must be a letter and the last character cannot be a hyphen.
-
Under Database type, select
Serverless
. -
Click Create a database.
Wait for the DB to start. When being created, a database has the
Provisioning
status. Once it is ready for use, its status will change toRunning
. -
Click the name of the database you created.
-
Under Connection, find the Endpoint field and save its value. You will need it at the next step.
Create a function
-
In the management console
, select the folder to create the function in. -
In the list of services, select Cloud Functions.
-
Click Create function.
-
Enter a name and description for the function. The naming requirements are as follows:
- The name must be from 3 to 63 characters long.
- It may contain lowercase Latin letters, numbers, and hyphens.
- The first character must be a letter and the last character cannot be a hyphen.
-
Click Create.
-
Under Editor, select
Python
as the runtime environment, disable Add files with code examples, and click Continue. -
Under Function code, create a file named
index.py
and paste the following code into it:import os import ydb import ydb.iam # Create driver in global space. driver = ydb.Driver( endpoint=os.getenv('YDB_ENDPOINT'), database=os.getenv('YDB_DATABASE'), credentials=ydb.iam.MetadataUrlCredentials(), ) # Wait for the driver to become active for requests. driver.wait(fail_fast=True, timeout=5) # Create the session pool instance to manage YDB sessions. pool = ydb.SessionPool(driver) def execute_query(session): # Create the transaction and execute query. return session.transaction().execute( 'select 1 as cnt;', commit_tx=True, settings=ydb.BaseRequestSettings().with_timeout(3).with_operation_timeout(2) ) def handler(event, context): # Execute query with the retry_operation helper. result = pool.retry_operation_sync(execute_query) return { 'statusCode': 200, 'body': str(result[0].rows[0].cnt == 1), }
-
Under Function code, create a file named
requirements.txt
and paste the following text into it:ydb
-
Specify the entry point:
index.handler
. -
Select a service account, e.g.,
sa-function
. -
Configure the environment variables:
YDB_ENDPOINT
: Enter the first part of the previously saved Endpoint field value (preceding/?database=
), e.g.,grpcs://ydb.serverless.yandexcloud.net:2135
.YDB_DATABASE
: Enter the second part of the previously saved Endpoint field value (following/?database=
), e.g.,/ru-central1/r1gra875baom********/g5n22e7ejfr1********
.
-
Click Save changes.
Test the function
-
Go to the Testing tab.
-
Click Run test and check out the testing results.
If a DB connection is established and a query is executed, the function status will change to
Done
and its output will contain the following text:{ "statusCode": 200, "body": "True" }
How to delete the resources you created
To stop paying for the resources you created: