-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontextmanager.py
More file actions
37 lines (28 loc) · 948 Bytes
/
Copy pathcontextmanager.py
File metadata and controls
37 lines (28 loc) · 948 Bytes
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
"""contextmanager.py
Setup a connection to the user database, process incoming records, then tear
down the connection.
created: MAY 2020
"""
import json
class UserDB:
"""Manage the user/ favorite number database."""
def __init__(self, db_path="users.json"):
self.db_path = db_path
def query(self, name, number):
"""
Record/ update a user's favorite number. Return True if a new user was
created, else return False.
"""
is_new_user = name not in self.db
self.db[name] = number
return is_new_user
def __enter__(self):
# Setup the database needed by `query`
with open(self.db_path) as fs:
self.db = json.load(fs)
# return the method we want rmq_py_caller to use
return self.query
def __exit__(self, *_):
# Flush the DB updates
with open(self.db_path, "w") as fs:
json.dump(self.db, fs)