How to check if Python application is running in AWS lambda function?

I have a Python application that connects to a database, and I would like the db credentials to be different when they work in the local environment (for testing) or inside the lambda function (for production).

Is there a way from a Python application to detect that it works inside a lambda function?

+8
source share
5 answers

How to check for the presence of a context object in a handler function? http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html

+2
source

This works for me os.environ.get("AWS_EXECUTION_ENV") is not None

EDIT: I believe that the existence of the context object is not enough for such a check, because you can mock it when it does not work in the AWS lambda function.

+7
source

For unit testing, I use the structure:

 + my_function/ +- __init__.py - empty files +- code/ +- __init__.py +- lambda_function.py +- unittest/ +- __init__.py +- tests.py - from ..code.lambda_function import * 

When doing unit tests with python -m my_function.unittest.tests , lambda_function.py uses __name__ == 'my_function.code.lambda_function'.

When launched in Lambda, __name__ == 'lambda_function'. Note that you will get the same value if you use python -m my_function.code.lambda_function , so you will always need a wrapper.

+1
source

This is what I use

 import os try: region = os.environ['AWS_REGION'] except: # Not in Lambda environment region = "us-east-1" 
+1
source

Because of this error, you can find out if you work inside the AWS Lambda function.

 import multiprocessing def on_lambda(): try: multiprocessing.Pool() on_lambda = False except: on_lambda = True return on_lambda 

I used this to successfully implement context sensitive metric reporting. We hope that they will not fix the error in the near future!

-1
source

Source: https://habr.com/ru/post/1245995/


All Articles