Skip to content

Instantly share code, notes, and snippets.


rezen/ Secret

Last active Oct 19, 2020
What would you like to do?
Attempt at aiohttp server in lambda
#!/usr/bin/env python
import sys
import base64
import schema
from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer
from graphql_server.aiohttp import GraphQLView
import asyncio
async def get_schema(request):
return web.Response(text=str(schema))
schema = schema.get_schema()
app = web.Application()
app.add_routes([web.get('/', get_schema)])
GraphQLView.attach(app, schema=schema.graphql_schema, graphiql=True, enable_async=True)
async def make_request(loop, path, method, options):
method = method.lower()
if method not in ['get', 'post', 'delete', 'head']:
return {}
server = TestServer(app)
client = TestClient(server)
await server.start_server()
data = {
'statusCode': 0,
'headers': {},
'body': '',
'isBase64Encoded': False
response = await getattr(client, method)(path,
params=options.get('query', ''),
data=options.get('body', ''),
headers=options.get('headers', {}),
data = {
"isBase64Encoded": False,
'statusCode': response.status,
'headers': {h: response.headers[h] for h in response.headers if h not in ['Server']},
'body': await response.text(),
except Exception as err:
await client.close()
await server.close()
return data
def handler(event, context):
path = event.get('path', '/')
if "multiValueHeaders" in event:
headers = event["multiValueHeaders"]
headers = event.get("headers", [])
headers = {} if headers is None else headers
query = event.get("multiValueQueryStringParameters")
if query:
query = ""
query = event.get("queryStringParameters") or {}
body = event.get("body", "") or ""
if event.get("isBase64Encoded", False):
body = base64.b64decode(body)
loop = asyncio.get_event_loop()
return loop.run_until_complete(make_request(loop, path, event.get("httpMethod", 'GET'), {
'headers': headers,
'body': event.get('body', ''),
'query': query,
if __name__ == '__main__':
web.run_app(app, port=5000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment