This repository has been archived by the owner on Oct 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.py
executable file
·88 lines (65 loc) · 2.09 KB
/
app.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
82
83
84
85
86
87
88
#!/usr/bin/env python3
from gevent import monkey # noqa
monkey.patch_all() # noqa
import json
import os
import redis
import connexion
import datetime
import logging
from connexion import NoContent
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
REDIS_PORT = int(os.getenv("REDIS_PORT", "6379"))
logger = logging.getLogger(__name__)
# the socket_timeout parameter is rather important as the default is "no timeout" :-/
r = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=0, socket_timeout=5)
def get_redis_key(pet_id: str) -> str:
return "pets:{}".format(pet_id)
def get_pets(limit: int, animal_type=None):
# TODO: filter by animal_type
keys = r.keys(get_redis_key("*"))
return {
"pets": [_get_pet(key.decode("utf-8").split(":")[1]) for key in keys][:limit]
}
def _get_pet(pet_id: str) -> dict:
"""Get Pet object from Redis"""
pet = r.get(get_redis_key(pet_id))
if pet:
pet = json.loads(pet)
return pet
def get_pet(pet_id: str):
pet = _get_pet(pet_id)
return pet or connexion.problem(404, "Not found", "Pet not found")
def put_pet(pet_id: str, pet):
exists = _get_pet(pet_id)
pet["id"] = pet_id
if exists:
logger.info("Updating pet %s..", pet_id)
exists.update(pet)
pet = exists
else:
logger.info("Creating pet %s..", pet_id)
pet["created"] = datetime.datetime.utcnow().isoformat()
r.set(get_redis_key(pet_id), json.dumps(pet))
return NoContent, (200 if exists else 201)
def delete_pet(pet_id: str):
exists = _get_pet(pet_id)
if exists:
logger.info("Deleting pet %s..", pet_id)
r.delete(get_redis_key(pet_id))
return NoContent, 204
else:
return NoContent, 404
def get_health():
try:
r.ping()
except Exception:
return connexion.problem(503, "Service Unavailable", "Unhealthy")
else:
return "Healthy"
logging.basicConfig(level=logging.INFO)
app = connexion.App(__name__)
app.add_api("swagger.yaml")
if __name__ == "__main__":
# run our standalone gevent server
app.run(port=8080, server="gevent")