Skip to content

Commit

Permalink
Refactor with context manager
Browse files Browse the repository at this point in the history
Signed-off-by: Wei-Chun, Chang <[email protected]>
Co-authored-by: Ching Yi, Chan <[email protected]>
  • Loading branch information
wcchang1115 and qrtt1 committed Oct 18, 2023
1 parent 1337176 commit c9ee12d
Showing 1 changed file with 18 additions and 19 deletions.
37 changes: 18 additions & 19 deletions piperider_cli/event/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import platform
import sys
import time
from contextlib import contextmanager
from datetime import datetime
from json import JSONDecodeError

Expand Down Expand Up @@ -83,48 +84,46 @@ def _is_full(self):
o = json.loads(f.read())
return len(o.get('unsend_events', [])) >= self._upload_threshold

def send_events(self):
@contextmanager
def load_json(self):
with portalocker.Lock(self._unsend_events_file, 'r+', timeout=5) as f:
o = json.loads(f.read())
try:
o = json.loads(f.read())
yield o
except JSONDecodeError:
o = dict(unsend_events=[])
yield o

Check warning on line 95 in piperider_cli/event/collector.py

View check run for this annotation

Codecov / codecov/patch

piperider_cli/event/collector.py#L93-L95

Added lines #L93 - L95 were not covered by tests
finally:
f.seek(0)
f.truncate()
f.write(json.dumps(o))

def send_events(self):
with self.load_json() as o:
payload = dict(
api_key=self._api_key,
events=o['unsend_events'],
)
o['unsend_events'] = []
f.seek(0)
f.truncate()
f.write(json.dumps(o))
try:
requests.post(self._api_endpoint, json=payload)
except Exception:
# TODO: handle exception when sending events
pass

def _store_to_file(self, event):
with portalocker.Lock(self._unsend_events_file, 'r+', timeout=5) as f:
try:
o = json.loads(f.read())
except JSONDecodeError:
o = dict(unsend_events=[])
with self.load_json() as o:
events = o.get('unsend_events', None)
if events is None:
o['unsend_events'] = []

o['unsend_events'].append(event)
f.seek(0)
f.truncate()
f.write(json.dumps(o))

def _cleanup_unsend_events(self):
with portalocker.Lock(self._unsend_events_file, 'r+', timeout=5) as f:
o = json.loads(f.read())
with self.load_json() as o:
events = o.get('unsend_events', None)
if events is None:
o['unsend_events'] = []

while len(o['unsend_events']) > self._delete_threshold:
o['unsend_events'].pop(0)

f.seek(0)
f.truncate()
f.write(json.dumps(o))

0 comments on commit c9ee12d

Please sign in to comment.