1 | #!/usr/bin/env python3 |
||
2 | # -*- coding: utf-8 -*- |
||
3 | |||
4 | # pylint: disable=C0111,C0326,C0103 |
||
5 | |||
6 | """Tools to manage dumps of API requests.""" |
||
7 | |||
8 | import errno |
||
9 | import glob |
||
10 | import os |
||
11 | import random |
||
12 | import time |
||
13 | from math import floor |
||
14 | |||
15 | from . import ansi |
||
16 | |||
17 | |||
18 | def get_timestamp_random(): |
||
19 | """Generate timestamp + random part to avoid collisions.""" |
||
20 | millis = floor(time.time() * 1000) |
||
21 | tail = "{:06d}".format(random.randint(0, 999999)) |
||
22 | return "{}_{}".format(str(millis), tail) |
||
23 | |||
24 | |||
25 | def write_info_if_dumps_found(): |
||
26 | """Notify user to upload dumps if present.""" |
||
27 | # To disable this info, uncomment the following line. |
||
28 | # return |
||
29 | files = glob.glob(os.path.normpath("logs/*.xml")) |
||
30 | if files: |
||
31 | print() |
||
32 | print("{}There are {} logs collected in the logs/ directory.{} Please consider uploading".format(ansi.YELLOW, len(files), ansi.RESET)) |
||
33 | print("them to https://tclota.birth-online.de/ by running {}./upload_logs.py{}.".format(ansi.CYAN, ansi.RESET)) |
||
34 | |||
35 | |||
36 | class DumpMgr: |
||
0 ignored issues
–
show
Unused Code
introduced
by
![]() |
|||
37 | """A class for XML dump management.""" |
||
38 | |||
39 | def __init__(self): |
||
40 | """Populate dump file name.""" |
||
41 | self.last_dump_filename = None |
||
42 | |||
43 | def write_dump(self, data): |
||
44 | """Write dump to file.""" |
||
45 | outfile = os.path.normpath("logs/{}.xml".format(get_timestamp_random())) |
||
46 | if not os.path.exists(os.path.dirname(outfile)): |
||
47 | try: |
||
48 | os.makedirs(os.path.dirname(outfile)) |
||
49 | except OSError as err: |
||
50 | if err.errno != errno.EEXIST: |
||
51 | raise |
||
52 | with open(outfile, "w", encoding="utf-8") as fhandle: |
||
53 | fhandle.write(data) |
||
54 | self.last_dump_filename = outfile |
||
55 | |||
56 | def delete_last_dump(self): |
||
57 | """Delete last dump.""" |
||
58 | if self.last_dump_filename: |
||
59 | os.unlink(self.last_dump_filename) |
||
60 | self.last_dump_filename = None |
||
61 |