-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser_greeting_service.py
48 lines (32 loc) · 1.14 KB
/
user_greeting_service.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
import json
import redis
from flask import Flask, request
from typing import Text, Optional, Dict, Any
app = Flask(__name__)
def get_current_user() -> Optional[Dict[Text, Any]]:
"""Retrieve the current user from intermediate storage."""
red = redis.StrictRedis(host="redis", port=6379, db=1)
encoded_user = red.get("user")
if encoded_user:
return json.loads(encoded_user)
else:
return None
def store_user(user: Dict[Text, Any]) -> None:
"""Store a users details to our intermediate storage."""
red = redis.StrictRedis(host="redis", port=6379, db=1)
red.set("user", json.dumps(user))
@app.route('/', methods=["GET"])
def greet():
"""Send a welcoming message to the user."""
user = get_current_user()
if user is not None:
return "Hello, {}!".format(user.get("name"))
else:
return "Hello, unknown stranger!"
@app.route('/', methods=["POST"])
def save_name():
"""Change a users details, most importantly his name."""
user = request.json
store_user(user)
return "I'll try to remember your name, {}!".format(user.get("name"))
app.run(host='0.0.0.0', port=9090)