-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.py
51 lines (45 loc) · 1.26 KB
/
index.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
# -*- coding: utf-8 -*-
import logging
import pymysql
import os,sys
logger = logging.getLogger()
def getConnection():
try:
conn = pymysql.connect(
host = os.environ['MYSQL_HOST'],
port = int(os.environ['MYSQL_PORT']),
user = os.environ['MYSQL_USER'],
passwd = os.environ['MYSQL_PASSWORD'],
db = os.environ['MYSQL_DBNAME'],
connect_timeout = 5)
return conn
except Exception as e:
logger.error(e)
logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
sys.exit()
def conditionallyCreateUsersTable():
try:
conn = getConnection()
with conn.cursor() as cursor:
sql = """CREATE TABLE IF NOT EXISTS users (
id VARCHAR(64) NOT NULL,
name VARCHAR(128) NOT NULL,
PRIMARY KEY(id))"""
cursor.execute(sql)
conn.commit()
finally:
conn.close()
def initializer(context):
conditionallyCreateUsersTable()
def handler(event, context):
try:
conn = getConnection()
with conn.cursor() as cursor:
sql = "REPLACE INTO users (id, name) VALUES(%s, %s)"
cursor.execute(sql, ('2', 'wan'))
cursor.execute("SELECT * FROM users")
result = cursor.fetchone()
logger.info(result)
return result
finally:
conn.close()