Untitled
unknown
plain_text
3 years ago
2.6 kB
5
Indexable
## Template AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: "Serverless Stack" Resources: hello: Type: AWS::Serverless::Function Properties: Runtime: python3.9 Handler: lambda.hello CodeUri: src/ Environment: Variables: LINKS_TABLE: !Ref linkTable Events: Hello: Type: Api Properties: Path: / Method: get create: Type: AWS::Serverless::Function Properties: Runtime: python3.9 Handler: lambda.create CodeUri: src/ Policies: - AmazonDynamoDBFullAccess Environment: Variables: LINKS_TABLE: !Ref linkTable Events: Create: Type: Api Properties: Path: /create Method: put redirect: Type: AWS::Serverless::Function Properties: Runtime: python3.9 Handler: lambda.redirect CodeUri: src/ Policies: - AmazonDynamoDBFullAccess Environment: Variables: LINKS_TABLE: !Ref linkTable Events: Redirect: Type: Api Properties: Path: /{backhalf} Method: get linkTable: Type: AWS::Serverless::SimpleTable Properties: TableName: 'linkstable' PrimaryKey: Name: id Type: String Outputs: url: Value: !Sub https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod table: Value: !Ref linkTable ## Lambda function import boto3 import json import os dynamodb = boto3.resource('dynamodb') table_name = os.environ['LINKS_TABLE'] table = dynamodb.Table(table_name) def hello(event, context): body = {"hello": table_name} return { "statusCode": 200, "body": json.dumps(body) } def create(event, context): body = json.loads(event['body']) # { 'backhalf': 'binxio-blog', 'url': 'https://binx.io/blog' } backhalf = body['backhalf'] url = body['url'] response = table.put_item( Item={ 'id': backhalf, 'url': url } ) print(response) shorturl = 'https://' + event['headers']['Host'] + '/Prod/' + body['backhalf'] return { "statusCode": 200, "body": json.dumps({ 'shorturl': shorturl }) } def redirect(event, context): query = event['pathParameters']['backhalf'] response = table.get_item( Key={ 'id': query } ) url = response['Item']['url'] return { 'statusCode': 301, 'headers': { 'Location': url } }
Editor is loading...