Skip to content

Commit

Permalink
implementing ruff and cleaning up code #102
Browse files Browse the repository at this point in the history
  • Loading branch information
bensteUEM committed Oct 8, 2024
1 parent 0902ab4 commit b78c352
Show file tree
Hide file tree
Showing 21 changed files with 1,839 additions and 1,623 deletions.
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.6.7 # Use the latest stable version of Ruff
hooks:
- id: ruff
4 changes: 2 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"python.testing.pytestEnabled": true,
"python.testing.unittestEnabled": false,
"[python]": {
"editor.defaultFormatter": "ms-python.autopep8",
"editor.formatOnSave": true
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": false
},
"python.formatting.provider": "none"
}
2 changes: 1 addition & 1 deletion churchtools_api/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__all__ = ['churchtools_api']
__all__ = ["churchtools_api"]
121 changes: 63 additions & 58 deletions churchtools_api/calendar.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,47 @@
import json
import logging

from datetime import datetime

from churchtools_api.churchtools_api_abstract import ChurchToolsApiAbstract

logger = logging.getLogger(__name__)


class ChurchToolsApiCalendar(ChurchToolsApiAbstract):
""" Part definition of ChurchToolsApi which focuses on calendars
"""Part definition of ChurchToolsApi which focuses on calendars.
Args:
ChurchToolsApiAbstract: template with minimum references
"""

def __init__(self):
def __init__(self) -> None:
super()

def get_calendars(self) -> list[dict]:
"""
Function to retrieve all calendar objects
This does not include pagination yet
"""Function to retrieve all calendar objects
This does not include pagination yet.
Returns:
Dict of calendars
"""
url = self.domain + '/api/calendars'
headers = {
'accept': 'application/json'
}
url = self.domain + "/api/calendars"
headers = {"accept": "application/json"}
params = {}

response = self.session.get(url=url, params=params, headers=headers)

if response.status_code == 200:
response_content = json.loads(response.content)
return response_content['data'].copy()
else:
logger.warning(
"%s Something went wrong fetching events: %s", response.status_code, response.content)
return response_content["data"].copy()
logger.warning(
"%s Something went wrong fetching events: %s",
response.status_code,
response.content,
)
return None

def get_calendar_appointments(
self, calendar_ids: list, **kwargs) -> list[dict]:
"""
Retrieve a list of appointments
def get_calendar_appointments(self, calendar_ids: list, **kwargs) -> list[dict]:
"""Retrieve a list of appointments.
Arguments:
calendar_ids: list of calendar ids to be checked
Expand All @@ -60,73 +59,79 @@ def get_calendar_appointments(
startDate and endDate overwritten by actual date if calculated date of series is unambiguous
Nothing in case something is off or nothing exists
"""

url = self.domain + '/api/calendars'
url = self.domain + "/api/calendars"
params = {}

if len(calendar_ids) > 1:
url += '/appointments'
params['calendar_ids[]'] = calendar_ids
elif 'appointment_id' in kwargs.keys():
url += "/appointments"
params["calendar_ids[]"] = calendar_ids
elif "appointment_id" in kwargs:
url += f"/{calendar_ids[0]}/appointments/{kwargs['appointment_id']}"
else:
url += f"/{calendar_ids[0]}/appointments"

headers = {
'accept': 'application/json'
}
headers = {"accept": "application/json"}

if 'from_' in kwargs.keys():
from_ = kwargs['from_']
if "from_" in kwargs:
from_ = kwargs["from_"]
if isinstance(from_, datetime):
from_ = from_.strftime("%Y-%m-%d")
if len(from_) == 10:
params['from'] = from_
if 'to_' in kwargs.keys() and 'from_' in kwargs.keys():
to_ = kwargs['to_']
params["from"] = from_
if "to_" in kwargs and "from_" in kwargs:
to_ = kwargs["to_"]
if isinstance(to_, datetime):
to_ = to_.strftime("%Y-%m-%d")
if len(to_) == 10:
params['to'] = to_
elif 'to_' in kwargs.keys():
logger.warning(
'Use of to_ is only allowed together with from_')
params["to"] = to_
elif "to_" in kwargs:
logger.warning("Use of to_ is only allowed together with from_")

response = self.session.get(url=url, params=params, headers=headers)

if response.status_code == 200:
response_content = json.loads(response.content)
response_data = self.combine_paginated_response_data(
response_content, url=url, headers=headers
response_content,
url=url,
headers=headers,
)

result = [response_data] if isinstance(response_data, dict) else response_data
result = (
[response_data] if isinstance(response_data, dict) else response_data
)

if len(result) == 0:
logger.info(
'There are not calendar appointments with the requested params')
return
"There are not calendar appointments with the requested params",
)
return None
# clean result
elif 'base' in result[0].keys():
if "base" in result[0]:
merged_appointments = []
for appointment in result:
appointment['base']['startDate'] = appointment['calculated']['startDate']
appointment['base']['endDate'] = appointment['calculated']['endDate']
merged_appointments.append(appointment['base'])
appointment["base"]["startDate"] = appointment["calculated"][
"startDate"
]
appointment["base"]["endDate"] = appointment["calculated"][
"endDate"
]
merged_appointments.append(appointment["base"])
return merged_appointments
elif 'appointment' in result[0].keys():
if len(result[0]['calculatedDates']) > 2:
logger.info('returning a series calendar appointment!')
if "appointment" in result[0]:
if len(result[0]["calculatedDates"]) > 2:
logger.info("returning a series calendar appointment!")
return result
else:
logger.debug(
'returning a simplified single calendar appointment with one date')
return [appointment['appointment']
for appointment in result]
else:
logger.warning('unexpected result')

else:
logger.warning(
"%s Something went wrong fetching calendar appointments: %s", response.status_code, response.content
)
logger.debug(
"returning a simplified single calendar appointment with one date",
)
return [appointment["appointment"] for appointment in result]
logger.warning("unexpected result")
return None

logger.warning(
"%s Something went wrong fetching calendar appointments: %s",
response.status_code,
response.content,
)
return None
Loading

0 comments on commit b78c352

Please sign in to comment.