[PYTHON] Determine if AWS Chalice is chalice local

Introduction

WEB service using API Gateway and Lambda on AWS AWS Chalice, a Python framework that is useful when creating. One of the convenient points is that with a single chalice local command, a WEB server starts up on your PC (local) and the same thing that runs on AWS runs [^ 1]. Testing and debugging is insanely fast.

Task

It's a convenient chalice local, but there seemed to be no direct way to determine that it was running locally with code, so I thought about it.

Solution

You can do it with: Take advantage of environment variables [^ 3].

--Define the stage for chalice local in the chalice configuration file (config.json) and set the appropriate environment variables in the defined stage. --When doing chalice local, specify the stage defined above with the --stage option.

This allows the code to determine if it is chalice local (running locally) by checking for the existence of environment variables.

Example

setting file

config.json


{
  "version": "2.0",
  "app_name": "testapp",
  "environment_variables": {
  },
  "stages": {
    "dev": {
      "api_gateway_stage": "api"
    },
    "local": {
      "environment_variables": {
        "IS_LOCAL": "true"
      }
    }
  }
}

An environment variable called ʻIS_LOCAL is set in the stage called local`.

Code body

app.Part of py


import logging
import os

# setup logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logformat = (
    '[%(levelname)s] %(asctime)s.%(msecs)dZ (%(aws_request_id)s) '
    '%(filename)s:%(funcName)s[%(lineno)d] %(message)s'
)
if os.environ.get('IS_LOCAL'):
    logformat = (
        '[%(levelname)s] %(asctime)s.%(msecs)dZ '
        '%(filename)s:%(funcName)s[%(lineno)d] %(message)s'
    )
formatter = logging.Formatter(logformat, '%Y-%m-%dT%H:%M:%S')
for handler in logger.handlers:
    handler.setFormatter(formatter)

I am changing the log format when running on AWS and when running locally [^ 2].

Execution method

$ chalice local --stage local

When doing chalice local, specify the defined stage with the --stage option.

in conclusion

This method, the place where it is necessary to always add the --stage option to chalice local is not good, but the problem is certainly solved, so I am using it.

Recommended Posts

Determine if AWS Chalice is chalice local
Determine if the string is formatable
Determine if the library is installed.
Determine if the gold coin is genuine
Determine if an attribute is defined in the object
I touched AWS Chalice
Determine if a string is a time with a python regular expression
I tried using AWS Chalice
Determine if standard output is piped when running a Python script