-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathlambda_function.py
61 lines (45 loc) · 1.32 KB
/
lambda_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import psycopg2
import json
import boto3
client = boto3.client('ssm')
db_host = client.get_parameter(
Name='/prod/api/DATABASE_HOST')['Parameter']['Value']
db_name = client.get_parameter(
Name='/prod/api/DATABASE_NAME')['Parameter']['Value']
db_user = client.get_parameter(
Name='/prod/api/DATABASE_USER')['Parameter']['Value']
db_pass = client.get_parameter(
Name='/prod/api/DATABASE_PASSWORD', WithDecryption=True)['Parameter']['Value']
db_port = 5432
def create_conn():
conn = None
try:
conn = psycopg2.connect("dbname={} user={} host={} password={}".format(
db_name, db_user, db_host, db_pass))
except:
print("Cannot connect.")
return conn
def fetch(conn, query):
result = []
print("Now executing: {}".format(query))
cursor = conn.cursor()
cursor.execute(query)
raw = cursor.fetchall()
for line in raw:
result.append(line)
return result
def lambda_handler(event, context):
print(event)
if 'query' in event.keys():
query = event['query']
else:
query = ''
query_cmd = "select * from articles_article where title like '%"+query+"%'"
print(query_cmd)
conn = create_conn()
result = fetch(conn, query_cmd)
conn.close()
return {
'statusCode': 200,
'body': str(result)
}