Created
August 5, 2017 15:54
-
-
Save JamieCressey/8dae08c82c8ecc46d7c3d688a008baad to your computer and use it in GitHub Desktop.
Local Development Server for AWS SAM - used with CodeStar Projects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import imp | |
import yaml | |
from bottle import Bottle | |
def get_yaml(): | |
with open("template.yml", 'r') as stream: | |
string = '' | |
for line in stream.readlines(): | |
string += line.replace('!', '') | |
return yaml.load(string) | |
def get_endpoints(yml): | |
resp = [] | |
for res in yml['Resources']: | |
handler = yml['Resources'][res]['Properties']['Handler'] | |
for event in [v['Properties'] for k, v in yml['Resources'][res][ | |
'Properties']['Events'].iteritems() if v['Type'] == 'Api']: | |
resp.append({ | |
'path': event['Path'].replace('{', '<').replace('}', '>'), | |
'method': event['Method'], | |
'handler': handler | |
}) | |
return resp | |
def setup_routing(app, endpoints): | |
for ep in endpoints: | |
func = """def func(**kwargs): | |
import json | |
from bottle import response, request | |
from importlib import import_module | |
p, m = "{}".rsplit('.', 1) | |
mod = import_module(p) | |
met = getattr(mod, m) | |
event = {{}} | |
try: | |
event['headers'] = {{k: v for k,v in dict(request.headers).iteritems()}} | |
except: | |
pass | |
try: | |
event['body'] = request.body.read() | |
except: | |
pass | |
event['pathParameters'] = kwargs | |
resp = met(event, {{}}) | |
try: | |
for k,v in resp['headers'].iteritems(): | |
response.set_header(k, v) | |
except KeyError: | |
pass | |
try: | |
response.status = resp['statusCode'] | |
except KeyError: | |
pass | |
return resp['body'] | |
""".format(ep['handler']) | |
module = imp.new_module('myfunctions') | |
exec func in module.__dict__ | |
print ep['path'], ep['method'] | |
app.route(ep['path'], ep['method'], module.func) | |
app = Bottle() | |
yml = get_yaml() | |
endpoints = get_endpoints(yml) | |
setup_routing(app, endpoints) | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment