Skip to content

Instantly share code, notes, and snippets.

@leiarenee
Last active March 18, 2022 22:08
Show Gist options
  • Save leiarenee/5197663d1594a33f3ff2026b07eb3af7 to your computer and use it in GitHub Desktop.
Save leiarenee/5197663d1594a33f3ff2026b07eb3af7 to your computer and use it in GitHub Desktop.
Python3 Sample code to run functions along with their arguments, when passed to Lambda as part of event object.
# Python3 Sample code to run functions along with their
# arguments, when passed to Lambda as part of event object
#
# Leia Renée 2022 Mit Licence
#
# leiarene20@gmail.com
# https://github.com/leiarenee
# https://www.linkedin.com/in/leia-renee/
# https://www.xn--rene-dpa.io/
#
import logging, sys
from datetime import datetime, timedelta
from timeit import default_timer as timer
from functools import wraps, partial
# Decorator Function
def safe_run(func=None, **dkwargs):
global debug_mode
if func is None:
return partial(safe_run, **dkwargs)
@wraps(func)
def wrapper(*args, **kwargs):
logging.debug(f'{func.__name__} function started with following paramaters: {args} {kwargs}')
start = timer()
result = func(*args, **kwargs)
end = timer()
process_time = '{:.2f}'.format((end - start) * 1000)
logging.debug(f'{func.__name__} function ended in {process_time} milliseconds. returned {result}')
return result
return wrapper
# Task Function
def prepare_cron(minutes=10):
"""Prepares Cron Expression adding time interval with relative to current time
Args:
minutes (int): Time interval in minutes to be added to current time
Returns:
str: Cron Expression
"""
dt = datetime.utcnow() + timedelta(minutes=minutes)
return f'cron({dt.minute} {dt.hour} {dt.day} {dt.month} ? {dt.year})'
# Lambda Handler function
def handler(event, context):
"""Lambda Handler Function
Args:
event (dict): Input parameters passed from the proxy
context (object): Lambda context object passed from the proxy
Returns:
dict: Body of the returning json
"""
if not 'args' in event:
event['args']=[]
if not 'kwargs' in event:
event['kwargs']={}
result = safe_run(getattr(sys.modules[__name__], event['function']))(*event['args'],**event['kwargs'])
return result
# For debugging
if __name__ == '__main__':
print(handler({'function':'prepare_cron','kwargs':{'minutes':30}},{}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment