Skip to content

Instantly share code, notes, and snippets.

@meganlkm
Created October 9, 2017 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meganlkm/0b75e598c22ec07ecbe69ceb3246bd09 to your computer and use it in GitHub Desktop.
Save meganlkm/0b75e598c22ec07ecbe69ceb3246bd09 to your computer and use it in GitHub Desktop.
function and decorator that returns a boto3 client or resource
import os
from functools import wraps
from inspect import getargspec
import boto3
AWS_REGION = os.getenv('AWS_REGION', 'us-east-1')
def get_client(name, client_type='client', region=None, *args, **kwargs):
if region is None:
region = AWS_REGION
fn = getattr(boto3, client_type)
return fn(name, region_name=region, **kwargs)
def boto_client(service_name, client_type='client', region=AWS_REGION,
client_param='client', region_param='region'):
def _get_client(func):
@wraps(func)
def make_client(*args, **kwargs):
fn_spec = getargspec(func)
params = dict(
zip(fn_spec.args[-len(fn_spec.defaults):], fn_spec.defaults)
)
params.update(dict((zip(fn_spec.args[:len(args)], args))))
params.update(kwargs)
if params.get(region_param) is None:
params[region_param] = region
if params.get(client_param) is None:
params[client_param] = get_client(
service_name,
client_type,
params[region_param]
)
return func(**params)
return make_client
return _get_client
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment