readability improvements

switched from string formatting to f-strings
removed some non-required validation
Standardised some logging outputs
better formatting of config inside tests
This commit is contained in:
Ace 2020-11-29 14:51:19 +01:00
parent 545a6207fb
commit 636172f157
12 changed files with 72 additions and 81 deletions

View File

@ -61,7 +61,7 @@ class iCalendar:
else:
ical = [auth_ical(url, username, password)]
else:
raise Exception ("Input: '{}' is not a string or list!".format(url))
raise Exception (f"Input: '{url}' is not a string or list!")
def auth_ical(url, uname, passwd):
@ -89,7 +89,7 @@ class iCalendar:
elif type(url) == str:
ical = (Calendar.from_ical(open(path)))
else:
raise Exception ("Input: '{}' is not a string or list!".format(url))
raise Exception (f"Input: '{url}' is not a string or list!")
self.icalendars += icals
logger.info('loaded iCalendars from filepaths')
@ -210,4 +210,4 @@ class iCalendar:
if __name__ == '__main__':
print('running {0} in standalone mode'.format(filename))
print(f'running {filename} in standalone mode')

View File

@ -82,25 +82,7 @@ class Agenda(inkycal_module):
self.timezone = get_system_tz()
# give an OK message
print('{0} loaded'.format(filename))
def _validate(self):
"""Validate module-specific parameters"""
if not isinstance(self.date_format, str):
print('date_format has to be an arrow-compatible token')
if not isinstance(self.time_format, str):
print('time_format has to be an arrow-compatible token')
if not isinstance(self.language, str):
print('language has to be a string: "en" ')
if not isinstance(self.ical_urls, list):
print('ical_urls has to be a list ["url1", "url2"] ')
if not isinstance(self.ical_files, list):
print('ical_files has to be a list ["path1", "path2"] ')
print(f'{filename} loaded')
def generate_image(self):
"""Generate image for this module"""
@ -110,7 +92,7 @@ class Agenda(inkycal_module):
im_height = int(self.height - (2 * self.padding_top))
im_size = im_width, im_height
logger.info('Image size: {0}'.format(im_size))
logger.info(f'Image size: {im_size}')
# Create an image for black pixels and one for coloured pixels
im_black = Image.new('RGB', size = im_size, color = 'white')
@ -121,7 +103,7 @@ class Agenda(inkycal_module):
line_height = int(self.font.getsize('hg')[1]) + line_spacing
line_width = im_width
max_lines = im_height // line_height
logger.debug(('max lines:',max_lines))
logger.debug(f'max lines: {max_lines}')
# Create timeline for agenda
now = arrow.now()
@ -156,11 +138,11 @@ class Agenda(inkycal_module):
date_width = int(max([self.font.getsize(
dates['begin'].format(self.date_format, locale=self.language))[0]
for dates in agenda_events]) * 1.2)
logger.debug(('date_width:', date_width))
logger.debug(f'date_width: {date_width}')
# Calculate positions for each line
line_pos = [(0, int(line * line_height)) for line in range(max_lines)]
logger.debug(('line_pos:', line_pos))
logger.debug(f'line_pos: {line_pos}')
# Check if any events were filtered
if upcoming_events:
@ -170,19 +152,19 @@ class Agenda(inkycal_module):
time_width = int(max([self.font.getsize(
events['begin'].format(self.time_format, locale=self.language))[0]
for events in upcoming_events]) * 1.2)
logger.debug(('time_width:', time_width))
logger.debug(f'time_width: {time_width}')
# Calculate x-pos for time
x_time = date_width
logger.debug(('x-time:', x_time))
logger.debug(f'x-time: {x_time}')
# Find out how much space is left for event titles
event_width = im_width - time_width - date_width
logger.debug(('width for events:', event_width))
logger.debug(f'width for events: {event_width}')
# Calculate x-pos for event titles
x_event = date_width + time_width
logger.debug(('x-event:', x_event))
logger.debug(f'x-event: {x_event}')
# Merge list of dates and list of events
agenda_events += upcoming_events
@ -247,4 +229,4 @@ class Agenda(inkycal_module):
return im_black, im_colour
if __name__ == '__main__':
print('running {0} in standalone mode'.format(filename))
print(f'running {filename} in standalone mode')

View File

@ -85,7 +85,7 @@ class Calendar(inkycal_module):
fonts['NotoSans-SemiCondensed'], size = self.fontsize)
# give an OK message
print('{0} loaded'.format(filename))
print(f'{filename} loaded')
def generate_image(self):
"""Generate image for this module"""
@ -95,7 +95,7 @@ class Calendar(inkycal_module):
im_height = int(self.height - (2 * self.padding_top))
im_size = im_width, im_height
logger.info('Image size: {0}'.format(im_size))
logger.info(f'Image size: {im_size}')
# Create an image for black pixels and one for coloured pixels
im_black = Image.new('RGB', size = im_size, color = 'white')
@ -104,8 +104,8 @@ class Calendar(inkycal_module):
# Allocate space for month-names, weekdays etc.
month_name_height = int(im_height * 0.1)
weekdays_height = int(im_height * 0.05)
logger.debug((f"month_name_height: {month_name_height}"))
logger.debug((f"weekdays_height: {weekdays_height}"))
logger.debug(f"month_name_height: {month_name_height}")
logger.debug(f"weekdays_height: {weekdays_height}")
if self.show_events == True:
@ -129,8 +129,8 @@ class Calendar(inkycal_module):
x_spacing_calendar = int((im_width % calendar_cols) / 2)
y_spacing_calendar = int((im_height % calendar_rows) / 2)
logger.debug((f"x_spacing_calendar: {x_spacing_calendar}"))
logger.debug((f"y_spacing_calendar :{y_spacing_calendar}"))
logger.debug(f"x_spacing_calendar: {x_spacing_calendar}")
logger.debug(f"y_spacing_calendar :{y_spacing_calendar}")
# Calculate positions for days of month
grid_start_y = (month_name_height + weekdays_height + y_spacing_calendar)
@ -160,7 +160,7 @@ class Calendar(inkycal_module):
# Set up weeknames in local language and add to main section
weekday_names = [weekstart.shift(days=+_).format('ddd',locale=self.language)
for _ in range(7)]
logger.debug('weekday names: {}'.format(weekday_names))
logger.debug(f'weekday names: {weekday_names}')
for _ in range(len(weekday_pos)):
write(
@ -333,4 +333,4 @@ class Calendar(inkycal_module):
return im_black, im_colour
if __name__ == '__main__':
print('running {0} in standalone mode'.format(filename))
print(f'running {filename} in standalone mode')

View File

@ -53,7 +53,7 @@ class Feeds(inkycal_module):
# Check if all required parameters are present
for param in self.requires:
if not param in config:
raise Exception('config is missing {}'.format(param))
raise Exception(f'config is missing {param}')
# required parameters
if config["feed_urls"] and isinstance(config['feed_urls'], str):
@ -65,7 +65,7 @@ class Feeds(inkycal_module):
self.shuffle_feeds = config["shuffle_feeds"]
# give an OK message
print('{0} loaded'.format(filename))
print(f'{filename} loaded')
def _validate(self):
"""Validate module-specific parameters"""
@ -81,7 +81,7 @@ class Feeds(inkycal_module):
im_width = int(self.width - (2 * self.padding_left))
im_height = int(self.height - (2 * self.padding_top))
im_size = im_width, im_height
logger.info('image size: {} x {} px'.format(im_width, im_height))
logger.info(f'Image size: {im_size}')
# Create an image for black pixels and one for coloured pixels
im_black = Image.new('RGB', size = im_size, color = 'white')
@ -111,7 +111,7 @@ class Feeds(inkycal_module):
for feeds in self.feed_urls:
text = feedparser.parse(feeds)
for posts in text.entries:
parsed_feeds.append('{0}: {1}'.format(posts.title, posts.summary))
parsed_feeds.append(f'{posts.title}: {posts.summary}')
self._parsed_feeds = parsed_feeds
@ -151,4 +151,4 @@ class Feeds(inkycal_module):
return im_black, im_colour
if __name__ == '__main__':
print('running {0} in standalone/debug mode'.format(filename))
print(f'running {filename} in standalone/debug mode')

View File

@ -33,7 +33,7 @@ class Jokes(inkycal_module):
config = config['config']
# give an OK message
print('{0} loaded'.format(filename))
print(f'{filename} loaded')
def generate_image(self):
"""Generate image for this module"""
@ -42,7 +42,7 @@ class Jokes(inkycal_module):
im_width = int(self.width - (2 * self.padding_left))
im_height = int(self.height - (2 * self.padding_top))
im_size = im_width, im_height
logger.info('image size: {} x {} px'.format(im_width, im_height))
logger.info(f'image size: {im_width} x {im_height} px')
# Create an image for black pixels and one for coloured pixels
im_black = Image.new('RGB', size = im_size, color = 'white')
@ -76,7 +76,7 @@ class Jokes(inkycal_module):
header = {"accept": "text/plain"}
response = requests.get(url, headers=header)
response.encoding = 'utf-8' # Change encoding to UTF-8
joke = response.text
joke = response.text.rstrip() # use to remove newlines
logger.debug(f"joke: {joke}")
# wrap text in case joke is too large
@ -87,13 +87,18 @@ class Jokes(inkycal_module):
if len(wrapped) > max_lines:
logger.error("Ohoh, Joke is too large for given space, please consider "
"increasing the size for this module")
logger.error("Removing lines in reverse order")
wrapped = wrapped[:max_lines]
# Write feeds on image
# Write the joke on the image
for _ in range(len(wrapped)):
if _+1 > max_lines:
logger.error('Ran out of lines for this joke :/')
break
write(im_black, line_positions[_], (line_width, line_height),
wrapped[_], font = self.font, alignment= 'left')
# Save image of black and colour channel in image-folder
return im_black, im_colour
if __name__ == '__main__':
print(f'running {filename} in standalone/debug mode')

View File

@ -60,7 +60,7 @@ class Stocks(inkycal_module):
im_width = int(self.width - (2 * self.padding_left))
im_height = int(self.height - (2 * self.padding_top))
im_size = im_width, im_height
logger.info('image size: {} x {} px'.format(im_width, im_height))
logger.info(f'Image size: {im_size}')
# Create an image for black pixels and one for coloured pixels (required)
im_black = Image.new('RGB', size = im_size, color = 'white')

View File

@ -34,7 +34,7 @@ class Todoist(inkycal_module):
optional = {
'project_filter': {
"label":"Show Todos only from following project (separated by a comma). Leave empty to show "+
"todos from all projects",
"todos from all projects",
}
}
@ -48,7 +48,7 @@ class Todoist(inkycal_module):
# Check if all required parameters are present
for param in self.requires:
if not param in config:
raise Exception('config is missing {}'.format(param))
raise Exception(f'config is missing {param}')
# module specific parameters
self.api_key = config['api_key']
@ -63,7 +63,7 @@ class Todoist(inkycal_module):
self._api.sync()
# give an OK message
print('{0} loaded'.format(self.name))
print(f'{filename} loaded')
def _validate(self):
"""Validate module-specific parameters"""
@ -77,7 +77,7 @@ class Todoist(inkycal_module):
im_width = int(self.width - (2 * self.padding_left))
im_height = int(self.height - (2 * self.padding_top))
im_size = im_width, im_height
logger.info('image size: {} x {} px'.format(im_width, im_height))
logger.info(f'Image size: {im_size}')
# Create an image for black pixels and one for coloured pixels
im_black = Image.new('RGB', size = im_size, color = 'white')
@ -196,4 +196,4 @@ class Todoist(inkycal_module):
return im_black, im_colour
if __name__ == '__main__':
print('running {0} in standalone/debug mode'.format(filename))
print(f'running {filename} in standalone/debug mode')

View File

@ -90,7 +90,7 @@ class Weather(inkycal_module):
# Check if all required parameters are present
for param in self.requires:
if not param in config:
raise Exception('config is missing {}'.format(param))
raise Exception(f'config is missing {param}')
# required parameters
self.api_key = config['api_key']
@ -146,7 +146,7 @@ class Weather(inkycal_module):
im_width = int(self.width - (2 * self.padding_left))
im_height = int(self.height - (2 * self.padding_top))
im_size = im_width, im_height
logger.info('image size: {} x {} px'.format(im_width, im_height))
logger.info(f'Image size: {im_size}')
# Create an image for black pixels and one for coloured pixels
im_black = Image.new('RGB', size = im_size, color = 'white')
@ -391,7 +391,7 @@ class Weather(inkycal_module):
daily_temp = [round(_.temperature(unit=temp_unit)['temp'],
ndigits=dec_temp) for _ in forecasts]
# Calculate min. and max. temp for this day
temp_range = '{}°/{}°'.format(max(daily_temp), min(daily_temp))
temp_range = f'{max(daily_temp)}°/{min(daily_temp)}°'
# Get all weather icon codes for this day
@ -510,4 +510,4 @@ class Weather(inkycal_module):
return im_black, im_colour
if __name__ == '__main__':
print('running {0} in standalone mode'.format(filename))
print(f'running {filename} in standalone mode')

View File

@ -44,9 +44,9 @@ class inkycal_module(metaclass=abc.ABCMeta):
self.fontsize = value
else:
setattr(self, key, value)
print("set '{}' to '{}'".format(key,value))
print(f"set '{key}' to '{value}'")
else:
print('{0} does not exist'.format(key))
print(f'{key} does not exist')
pass
# Check if validation has been implemented
@ -70,12 +70,12 @@ class inkycal_module(metaclass=abc.ABCMeta):
if hasattr(cls, 'requires'):
for each in cls.requires:
if not "label" in cls.requires[each]:
raise Exception("no label found for {}".format(each))
raise Exception(f"no label found for {each}")
if hasattr(cls, 'optional'):
for each in cls.optional:
if not "label" in cls.optional[each]:
raise Exception("no label found for {}".format(each))
raise Exception(f"no label found for {each}")
conf = {
"name": cls.__name__,

View File

@ -9,10 +9,7 @@ tests = [
"size": [400,100],
"feed_urls": "http://feeds.bbci.co.uk/news/world/rss.xml#",
"shuffle_feeds": True,
"padding_x": 10,
"padding_y": 10,
"fontsize": 12,
"language": "en"
"padding_x": 10, "padding_y": 10, "fontsize": 12, "language": "en"
}
},
{
@ -22,10 +19,7 @@ tests = [
"size": [400,100],
"feed_urls": "http://feeds.bbci.co.uk/news/world/rss.xml#",
"shuffle_feeds": False,
"padding_x": 10,
"padding_y": 10,
"fontsize": 12,
"language": "en"
"padding_x": 10, "padding_y": 10, "fontsize": 12, "language": "en"
}
},
]

View File

@ -10,11 +10,8 @@ tests = [
"path": "https://cdn.britannica.com/s:700x500/84/73184-004-E5A450B5/Sunflower-field-Fargo-North-Dakota.jpg",
"rotation": "0",
"layout": "fill",
"padding_x": 0,
"padding_y": 0,
"fontsize": 12,
"language": "en",
"colours": "bwr"
"colours": "bwr",
"padding_x": 0, "padding_y": 0, "fontsize": 12, "language": "en",
}
},
]

View File

@ -7,10 +7,23 @@ tests = [
"name": "Jokes",
"config": {
"size": [300, 60],
"padding_x": 10,
"padding_y": 10,
"fontsize": 12,
"language": "en"
"padding_x": 10, "padding_y": 10, "fontsize": 12, "language": "en"
}
},
{
"position": 1,
"name": "Jokes",
"config": {
"size": [300, 30],
"padding_x": 10, "padding_y": 10, "fontsize": 12, "language": "en"
}
},
{
"position": 1,
"name": "Jokes",
"config": {
"size": [100, 800],
"padding_x": 10, "padding_y": 10, "fontsize": 18, "language": "en"
}
},
]