forked from mendhak/waveshare-epaper-display
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utility.py
71 lines (54 loc) · 2.19 KB
/
utility.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
import codecs
import logging
import os
import time
import contextlib
from http.client import HTTPConnection # py3
def configure_logging():
"""
Sets up logging with a specific logging format.
Call this at the beginning of a script.
Then using logging methods as normal
"""
log_level = os.getenv("LOG_LEVEL", "INFO")
log_format = "%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s"
log_dateformat = "%Y-%m-%d:%H:%M:%S"
logging.basicConfig(level=log_level, format=log_format, datefmt=log_dateformat)
logger = logging.getLogger()
logger.setLevel(level=log_level)
# Adds debug logging to python requests
# https://stackoverflow.com/a/24588289/974369
HTTPConnection.debuglevel = 1 if log_level == "DEBUG" else 0
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(level=log_level)
requests_log.propagate = True
formatter = logging.Formatter(fmt=log_format, datefmt=log_dateformat)
handler = logger.handlers[0]
handler.setFormatter(formatter)
# utilize a template svg as a base for output of values
def update_svg(template_svg_filename, output_svg_filename, output_dict):
"""
Update the `template_svg_filename` SVG.
Replaces keys with values from `output_dict`
Writes the output to `output_svg_filename`
"""
# replace tags with values in SVG
output = codecs.open(template_svg_filename, 'r', encoding='utf-8').read()
for output_key in output_dict:
logging.debug("update_svg() - {} -> {}"
.format(output_key, output_dict[output_key]))
output = output.replace(output_key, output_dict[output_key])
logging.debug("update_svg() - Write to SVG {}".format(output_svg_filename))
codecs.open(output_svg_filename, 'w', encoding='utf-8').write(output)
def is_stale(filepath, ttl):
"""
Checks if the specified `filepath` is older than the `ttl` in seconds
Returns true if the file doesn't exist.
"""
verdict = True
if (os.path.isfile(filepath)):
verdict = time.time() - os.path.getmtime(filepath) > ttl
logging.debug(
"is_stale({}) - {}"
.format(filepath, str(verdict)))
return verdict