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.
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.
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.
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`.
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].
$ chalice local --stage local
When doing chalice local
, specify the defined stage with the --stage
option.
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