Skip to content

Commit 9b3438e

Browse files
committed
Adding artifacts for tutorials.
1 parent 62475a4 commit 9b3438e

File tree

14 files changed

+380
-8
lines changed

14 files changed

+380
-8
lines changed

database-caching/.DS_Store

-6 KB
Binary file not shown.

database-caching/INSTALL

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
This code is part of an Amazon ElastiCache Tutorial
2+
3+
4+
1. Install dependencies:
5+
6+
$ pip3 install -r requirements.txt
7+
8+
9+
2. Populate the database:
10+
11+
$ mysql -h endpoint -P 3306 -u admin -p < seed.sql
12+
13+
14+
3. Configure environment
15+
16+
$ export REDIS_URL=redis://redis_endpoint:6379/
17+
$ export DB_HOST=mysql_endpoint
18+
$ export DB_USER=admin
19+
$ export DB_PASS=password
20+
$ export DB_NAME=tutorial
21+
22+
23+
Note that you have to supply the real values for `redis_endpoint`,
24+
`mysql_endpoint`, and `password`.
25+
26+
27+
4. Run the example:
28+
29+
$ python example.py
30+

database-caching/README.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ $ sudo yum install git -y
2929
$ sudo yum install mysql -y
3030
$ sudo yum install python3 -y
3131
$ pip3 install --user virtualenv
32-
$ git clone <repository-url>/elc-cache-aside
33-
$ cd elc-cache-aside
32+
$ git clone https://github.com/aws-samples/amazon-elasticache-samples/
33+
$ cd amazon-elasticache-samples/database-caching
3434
$ virtualenv venv
3535
$ source ./venv/bin/activate
3636
$ pip3 install -r requirements.txt
@@ -246,7 +246,7 @@ While the instances are being created, you will see a banner explaining how to o
246246

247247
# Step 3: Populate your MySQL database
248248

249-
You can populate the database with the seed.sql file provided in the tutorial repository. Log into your EC2 instance and run this command:
249+
You can populate the database with the [seed.sql](./seed.sql) file provided in the [tutorial repository](./). Log into your EC2 instance and run this command:
250250

251251
**syntax: shell**
252252

@@ -260,7 +260,7 @@ If the command hangs, chances are you are being blocked by the Security Group se
260260

261261
In Source, you can start typing the name of the security group and you'll be able to click on the Security Group ID. If you need to learn more about Security Groups, you can check [the documentation](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html) or the [Security Group Rules Reference](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html).
262262

263-
Below is a breakdown of the commands contained in the seed.sql file. If you succeeded in populating the database, you can skip the steps below and go directly to step 4.
263+
Below is a breakdown of the commands contained in the [seed.sql](./seed.sql) file. If you succeeded in populating the database, you can skip the steps below and go directly to step 4.
264264

265265
### 3.1 — Connect to your database:
266266

@@ -282,7 +282,7 @@ mysql> CREATE database tutorial;
282282
Query OK, 1 row affected (0.01 sec)
283283
```
284284

285-
At this point you can use the tutorial database, create tables and add some records.
285+
At this point you can use the tutorial database, create tables and add some records.
286286

287287
**syntax: SQL**
288288

@@ -387,7 +387,7 @@ In Source, you can start typing the name of the security group and you'll be abl
387387

388388
## Configure the environment
389389

390-
In the repository you will find some Python code that you can run in your EC2 instance. But first you need to configure some environment variables:
390+
In the [repository](./) you will find some [Python code](./example.py) that you can run in your EC2 instance. But first you need to configure some environment variables:
391391

392392
**syntax: shell**
393393

database-caching/example.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import os
2+
import json
3+
4+
import redis
5+
import pymysql
6+
7+
8+
class DB:
9+
def __init__(self, **params):
10+
params.setdefault("charset", "utf8mb4")
11+
params.setdefault("cursorclass", pymysql.cursors.DictCursor)
12+
13+
self.mysql = pymysql.connect(**params)
14+
15+
def query(self, sql):
16+
with self.mysql.cursor() as cursor:
17+
cursor.execute(sql)
18+
return cursor.fetchall()
19+
20+
def record(self, sql, values):
21+
with self.mysql.cursor() as cursor:
22+
cursor.execute(sql, values)
23+
return cursor.fetchone()
24+
25+
26+
# Time to live for cached data
27+
TTL = 10
28+
29+
# Read the Redis credentials from the REDIS_URL environment variable.
30+
REDIS_URL = os.environ.get('REDIS_URL')
31+
32+
# Read the DB credentials from the DB_* environment variables.
33+
DB_HOST = os.environ.get('DB_HOST')
34+
DB_USER = os.environ.get('DB_USER')
35+
DB_PASS = os.environ.get('DB_PASS')
36+
DB_NAME = os.environ.get('DB_NAME')
37+
38+
# Initialize the database
39+
Database = DB(host=DB_HOST, user=DB_USER, password=DB_PASS, db=DB_NAME)
40+
41+
# Initialize the cache
42+
Cache = redis.Redis.from_url(REDIS_URL)
43+
44+
45+
def fetch(sql):
46+
"""Retrieve records from the cache, or else from the database."""
47+
res = Cache.get(sql)
48+
49+
if res:
50+
return json.loads(res)
51+
52+
res = Database.query(sql)
53+
Cache.setex(sql, TTL, json.dumps(res))
54+
return res
55+
56+
57+
def planet(id):
58+
"""Retrieve a record from the cache, or else from the database."""
59+
key = f"planet:{id}"
60+
res = Cache.hgetall(key)
61+
62+
if res:
63+
return res
64+
65+
sql = "SELECT `id`, `name` FROM `planet` WHERE `id`=%s"
66+
res = Database.record(sql, (id,))
67+
68+
if res:
69+
Cache.hmset(key, res)
70+
Cache.expire(key, TTL)
71+
72+
return res
73+
74+
75+
# Display the result of some queries
76+
print(fetch("SELECT * FROM planet"))
77+
print(planet(1))
78+
print(planet(2))
79+
print(planet(3))

database-caching/requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
PyMySQL==0.9.3
2+
redis==3.2.1

database-caching/seed.sql

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
CREATE database tutorial;
2+
USE tutorial;
3+
CREATE TABLE planet (
4+
id INT UNSIGNED AUTO_INCREMENT,
5+
name VARCHAR(30),
6+
PRIMARY KEY(id));
7+
INSERT INTO planet (name) VALUES ("Mercury");
8+
INSERT INTO planet (name) VALUES ("Venus");
9+
INSERT INTO planet (name) VALUES ("Earth");
10+
INSERT INTO planet (name) VALUES ("Mars");
11+
INSERT INTO planet (name) VALUES ("Jupiter");
12+
INSERT INTO planet (name) VALUES ("Saturn");
13+
INSERT INTO planet (name) VALUES ("Uranus");
14+
INSERT INTO planet (name) VALUES ("Neptune");

session-store/.DS_Store

-6 KB
Binary file not shown.

session-store/INSTALL

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
This code is part of an Amazon ElastiCache Tutorial
2+
3+
4+
1. Install dependencies:
5+
6+
$ pip3 install -r requirements.txt
7+
8+
9+
2. Configure environment variables:
10+
11+
# Use the name of the example you want to run.
12+
$ export FLASK_APP=example-1.py
13+
14+
# Replace the value with a random string.
15+
$ export SECRET_KEY=some_secret_string
16+
17+
# Replace the hostname with the endpoint of your ElastiCache instance.
18+
$ export REDIS_URL=redis://hostname:6379/
19+
20+
21+
3. Start the server on port 5000:
22+
23+
$ flask run -h 0.0.0.0 -p 5000

session-store/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ Once you have access to your EC2 instance, run the following commands:
2626
$ sudo yum install git
2727
$ sudo yum install python3
2828
$ sudo pip3 install virtualenv
29-
$ git clone https://github.com/aws-samples/amazon-elasticache-samples/session-store/
30-
$ cd session-store
29+
$ git clone https://github.com/aws-samples/amazon-elasticache-samples/
30+
$ cd amazon-elasticache-samples/session-store
3131
$ virtualenv venv
3232
$ source ./venv/bin/activate
3333
$ pip3 install -r requirements.txt

session-store/example-1.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import os
2+
3+
from flask import Flask, session, redirect, escape, request
4+
5+
6+
# Configure the application name with the FLASK_APP environment variable.
7+
app = Flask(__name__)
8+
9+
10+
# Configure the secret_key with the SECRET_KEY environment variable.
11+
app.secret_key = os.environ.get('SECRET_KEY', default=None)
12+
13+
14+
@app.route('/')
15+
def index():
16+
if 'username' in session:
17+
return 'Logged in as %s' % escape(session['username'])
18+
return 'You are not logged in'
19+
20+
21+
@app.route('/login', methods=['GET', 'POST'])
22+
def login():
23+
if request.method == 'POST':
24+
session['username'] = request.form['username']
25+
return redirect('/')
26+
return '''
27+
<form method="post">
28+
<p><input type=text name=username>
29+
<p><input type=submit value=Login>
30+
</form>
31+
'''
32+
33+
34+
@app.route('/logout')
35+
def logout():
36+
session.pop('username', None)
37+
return redirect('/')

0 commit comments

Comments
 (0)