-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathexample.py
81 lines (57 loc) · 1.88 KB
/
example.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import os
import json
import redis
import pymysql
class DB:
def __init__(self, **params):
params.setdefault("charset", "utf8mb4")
params.setdefault("cursorclass", pymysql.cursors.DictCursor)
self.mysql = pymysql.connect(**params)
def query(self, sql):
with self.mysql.cursor() as cursor:
cursor.execute(sql)
return cursor.fetchall()
def record(self, sql, values):
with self.mysql.cursor() as cursor:
cursor.execute(sql, values)
return cursor.fetchone()
# Time to live for cached data
TTL = 10
# Read the Redis credentials from the REDIS_URL environment variable.
REDIS_URL = os.environ.get('REDIS_URL')
# Read the DB credentials from the DB_* environment variables.
DB_HOST = os.environ.get('DB_HOST')
DB_USER = os.environ.get('DB_USER')
DB_PASS = os.environ.get('DB_PASS')
DB_NAME = os.environ.get('DB_NAME')
# Initialize the database
Database = DB(host=DB_HOST, user=DB_USER, password=DB_PASS, db=DB_NAME)
# Initialize the cache
Cache = redis.Redis.from_url(REDIS_URL)
def fetch(sql):
"""Retrieve records from the cache, or else from the database."""
res = Cache.get(sql)
if res:
return json.loads(res)
res = Database.query(sql)
Cache.setex(sql, TTL, json.dumps(res))
return res
def planet(id):
"""Retrieve a record from the cache, or else from the database."""
key = f"planet:{id}"
res = Cache.hgetall(key)
if res:
return res
sql = "SELECT `id`, `name` FROM `planet` WHERE `id`=%s"
res = Database.record(sql, (id,))
if res:
Cache.hmset(key, res)
Cache.expire(key, TTL)
return res
# Display the result of some queries
print(fetch("SELECT * FROM planet"))
print(planet(1))
print(planet(2))
print(planet(3))