Skip to content

Commit 7c1983f

Browse files
committed
Merge branch 'devel'
2 parents 338626e + 5214ee2 commit 7c1983f

File tree

4 files changed

+68
-52
lines changed

4 files changed

+68
-52
lines changed

CHANGELOG.md

+12
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,18 @@
44

55
NOTE: potentially breaking changes are flagged with a 🧨 symbol.
66

7+
## 3.2.0
8+
9+
### Added
10+
11+
- `pyppms.booking.PpmsBooking.last_served_from_cache` has been added to indicate
12+
if the last request was served from the cache or on-line.
13+
14+
### Changed
15+
16+
- Several log messages have been demoted to lower levels for further reducing
17+
logging clutter.
18+
719
## 3.1.0
820

921
### Added

src/pyppms/common.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def parse_multiline_response(text, graceful=True):
140140
try:
141141
lines = text.splitlines()
142142
if len(lines) < 2:
143-
log.info("Response has less than TWO lines: >>>{}<<<", text)
143+
log.debug("Response has less than TWO lines: >>>{}<<<", text)
144144
if not graceful:
145145
raise NoDataError("Invalid response format!")
146146
return []

src/pyppms/ppms.py

+45-41
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ class PpmsConnection:
4040
cache_users_only : bool
4141
Flag indicating that only PPMS user details will be stored in the
4242
on-disk cache, nothing else.
43+
last_served_from_cache
44+
Indicates if the last request was served from the cache or on-line.
4345
users : dict
4446
A dict with usernames as keys, mapping to the related
4547
:py:class:`pyppms.user.PpmsUser` object, serves as a cache during the object's
@@ -108,6 +110,8 @@ def __init__(self, url, api_key, timeout=10, cache="", cache_users_only=False):
108110
}
109111
self.cache_path = cache
110112
self.cache_users_only = cache_users_only
113+
self.last_served_from_cache = False
114+
"""Indicates if the last request was served from the cache or on-line."""
111115

112116
# run in cache-only mode (e.g. for testing or off-line usage) if no API
113117
# key has been specified, skip authentication then:
@@ -126,7 +130,7 @@ def __authenticate(self):
126130
requests.exceptions.ConnectionError
127131
Raised in case authentication failed for any reason.
128132
"""
129-
log.debug(
133+
log.trace(
130134
"Attempting authentication against {} with key [{}...{}]",
131135
self.url,
132136
self.api_key[:2],
@@ -167,7 +171,7 @@ def __authenticate(self):
167171
log.error(msg)
168172
raise requests.exceptions.ConnectionError(msg)
169173

170-
log.info(
174+
log.debug(
171175
"Authentication succeeded, response=[{}], http_status=[{}]",
172176
response.text,
173177
response.status_code,
@@ -208,18 +212,18 @@ def request(self, action, parameters={}, skip_cache=False):
208212
# log.debug("Request parameters: {}", parameters)
209213

210214
response = None
211-
read_from_cache = False
212215
try:
213216
if skip_cache: # pragma: no cover
214217
raise LookupError("Skipping the cache has been requested")
215218
response = self.__intercept_read(req_data)
216-
read_from_cache = True
219+
self.last_served_from_cache = True
217220
except LookupError as err:
218-
log.debug(f"Doing an on-line request: {err}")
221+
log.trace(f"Doing an on-line request: {err}")
219222
response = requests.post(self.url, data=req_data, timeout=self.timeout)
223+
self.last_served_from_cache = False
220224

221225
# store the response if it hasn't been read from the cache before:
222-
if not read_from_cache: # pragma: no cover
226+
if not self.last_served_from_cache: # pragma: no cover
223227
self.__intercept_store(req_data, response)
224228

225229
# NOTE: the HTTP status code returned is always `200` even if
@@ -390,7 +394,7 @@ def flush_cache(self, keep_users=False):
390394
will be kept, by default `False`.
391395
"""
392396
if self.cache_path == "":
393-
log.info("No cache path configured, not flushing!")
397+
log.debug("No cache path configured, not flushing!")
394398
return
395399

396400
dirs_to_remove = [self.cache_path] # by default remove the entire cache dir
@@ -404,11 +408,11 @@ def flush_cache(self, keep_users=False):
404408
continue
405409
dirs_to_remove.append(os.path.join(self.cache_path, subdir))
406410

407-
log.info("Flushing the on-disk cache at [{}] {}...", self.cache_path, keep_msg)
411+
log.debug("Flushing the on-disk cache at [{}] {}...", self.cache_path, keep_msg)
408412
for directory in dirs_to_remove:
409413
try:
410414
shutil.rmtree(directory)
411-
log.debug("Removed directory [{}].", directory)
415+
log.trace("Removed directory [{}].", directory)
412416
except Exception as ex: # pylint: disable-msg=broad-except
413417
log.warning("Removing the cache at [{}] failed: {}", directory, ex)
414418

@@ -427,7 +431,7 @@ def get_admins(self):
427431
for username in admins:
428432
user = self.get_user(username)
429433
users.append(user)
430-
log.debug("{} admins in the PPMS database: {}", len(admins), ", ".join(admins))
434+
log.trace("{} admins in the PPMS database: {}", len(admins), ", ".join(admins))
431435
return users
432436

433437
def get_booking(self, system_id, booking_type="get"):
@@ -478,7 +482,7 @@ def get_booking(self, system_id, booking_type="get"):
478482
if booking_type == "get":
479483
desc = "a currently active booking"
480484
if not response.text.strip():
481-
log.debug("System [{}] doesn't have {}", system_id, desc)
485+
log.trace("System [{}] doesn't have {}", system_id, desc)
482486
return None
483487

484488
return PpmsBooking(response.text, booking_type, system_id)
@@ -502,7 +506,7 @@ def get_group(self, group_id):
502506
line of the PUMAPI response, values from the data line.
503507
"""
504508
response = self.request("getgroup", {"unitlogin": group_id})
505-
log.debug("Group details returned by PPMS (raw): {}", response.text)
509+
log.trace("Group details returned by PPMS (raw): {}", response.text)
506510

507511
if not response.text:
508512
msg = f"Group [{group_id}] is unknown to PPMS"
@@ -511,7 +515,7 @@ def get_group(self, group_id):
511515

512516
details = dict_from_single_response(response.text)
513517

514-
log.debug("Details of group {}: {}", group_id, details)
518+
log.trace("Details of group {}: {}", group_id, details)
515519
return details
516520

517521
def get_group_users(self, unitlogin):
@@ -534,7 +538,7 @@ def get_group_users(self, unitlogin):
534538
for username in members:
535539
user = self.get_user(username)
536540
users.append(user)
537-
log.debug(
541+
log.trace(
538542
"{} members in PPMS group [{}]: {}",
539543
len(members),
540544
unitlogin,
@@ -553,7 +557,7 @@ def get_groups(self):
553557
response = self.request("getgroups")
554558

555559
groups = response.text.splitlines()
556-
log.debug("{} groups in the PPMS database: {}", len(groups), ", ".join(groups))
560+
log.trace("{} groups in the PPMS database: {}", len(groups), ", ".join(groups))
557561
return groups
558562

559563
def get_next_booking(self, system_id):
@@ -593,17 +597,17 @@ def get_running_sheet(self, core_facility_ref, date, ignore_uncached_users=False
593597
"plateformid": f"{core_facility_ref}",
594598
"day": date.strftime("%Y-%m-%d"),
595599
}
596-
log.debug("Requesting runningsheet for {}", parameters["day"])
600+
log.trace("Requesting runningsheet for {}", parameters["day"])
597601
response = self.request("getrunningsheet", parameters)
598602
try:
599603
entries = parse_multiline_response(response.text, graceful=False)
600604
except NoDataError:
601605
# in case no bookings exist the response will be empty!
602-
log.debug("Runningsheet for the given day was empty!")
606+
log.trace("Runningsheet for the given day was empty!")
603607
return []
604608
except Exception as err: # pylint: disable-msg=broad-except
605609
log.error("Parsing runningsheet details failed: {}", err)
606-
log.debug("Runningsheet PUMPAI response was: >>>{}<<<", response.text)
610+
log.trace("Runningsheet PUMPAI response was: >>>{}<<<", response.text)
607611
return []
608612

609613
for entry in entries:
@@ -613,14 +617,14 @@ def get_running_sheet(self, core_facility_ref, date, ignore_uncached_users=False
613617
log.debug("Ignoring booking for uncached user [{}]", full)
614618
continue
615619

616-
log.info("Booking for an uncached user ({}) found!", full)
620+
log.debug("Booking for an uncached user ({}) found!", full)
617621
self.update_users()
618622

619623
if full not in self.fullname_mapping:
620624
log.error("PPMS doesn't seem to know user [{}], skipping", full)
621625
continue
622626

623-
log.info(
627+
log.trace(
624628
"Booking for user '{}' ({}) found", self.fullname_mapping[full], full
625629
)
626630
system_name = entry["Object"]
@@ -659,7 +663,7 @@ def get_systems(self, force_refresh=False):
659663
fails for any reason, the system is skipped entirely.
660664
"""
661665
if self.systems and not force_refresh:
662-
log.debug("Using cached details for {} systems", len(self.systems))
666+
log.trace("Using cached details for {} systems", len(self.systems))
663667
else:
664668
self.update_systems()
665669

@@ -702,7 +706,7 @@ def get_systems_matching(self, localisation, name_contains):
702706
if localisation == "":
703707
loc_desc = "(no location filter given)"
704708

705-
log.info(
709+
log.trace(
706710
"Querying PPMS for systems {}, name matching any of {}",
707711
loc_desc,
708712
name_contains,
@@ -719,7 +723,7 @@ def get_systems_matching(self, localisation, name_contains):
719723
)
720724
continue
721725

722-
# log.debug('System [{}] is matching location [{}], checking if '
726+
# log.trace('System [{}] is matching location [{}], checking if '
723727
# 'the name is matching any of the valid pattern {}',
724728
# system.name, loc, name_contains)
725729
for valid_name in name_contains:
@@ -729,11 +733,11 @@ def get_systems_matching(self, localisation, name_contains):
729733
break
730734

731735
# if sys_id not in system_ids:
732-
# log.debug('System [{}] does NOT match a valid name: {}',
736+
# log.trace('System [{}] does NOT match a valid name: {}',
733737
# system.name, name_contains)
734738

735-
log.info("Found {} bookable systems {}", len(system_ids), loc_desc)
736-
log.debug("IDs of matching bookable systems {}: {}", loc_desc, system_ids)
739+
log.trace("Found {} bookable systems {}", len(system_ids), loc_desc)
740+
log.trace("IDs of matching bookable systems {}: {}", loc_desc, system_ids)
737741
return system_ids
738742

739743
def get_user(self, login_name, skip_cache=False):
@@ -826,7 +830,7 @@ def get_user_dict(self, login_name, skip_cache=False):
826830
# u'true\r\n'
827831
# )
828832
details = dict_from_single_response(response.text)
829-
log.debug("Details for user [{}]: {}", login_name, details)
833+
log.trace("Details for user [{}]: {}", login_name, details)
830834
return details
831835

832836
def get_user_experience(self, login=None, system_id=None):
@@ -854,7 +858,7 @@ def get_user_experience(self, login=None, system_id=None):
854858
response = self.request("getuserexp", parameters=data)
855859

856860
parsed = parse_multiline_response(response.text)
857-
log.debug(
861+
log.trace(
858862
"Received {} experience entries for filters [user:{}] and [id:{}]",
859863
len(parsed),
860864
login,
@@ -886,8 +890,8 @@ def get_user_ids(self, active=False):
886890

887891
users = response.text.splitlines()
888892
active_desc = "active " if active else ""
889-
log.info("{} {}users in the PPMS database", len(users), active_desc)
890-
log.debug(", ".join(users))
893+
log.trace("{} {}users in the PPMS database", len(users), active_desc)
894+
log.trace(", ".join(users))
891895
return users
892896

893897
def get_users(self, force_refresh=False, active_only=True):
@@ -908,7 +912,7 @@ def get_users(self, force_refresh=False, active_only=True):
908912
A dict of PpmsUser objects with the username (login) as key.
909913
"""
910914
if self.users and not force_refresh:
911-
log.debug("Using cached details for {} users", len(self.users))
915+
log.trace("Using cached details for {} users", len(self.users))
912916
else:
913917
self.update_users(active_only=active_only)
914918

@@ -939,7 +943,7 @@ def get_users_emails(self, users=None, active=False):
939943
if not email:
940944
log.warning("--- WARNING: no email for user [{}]! ---", user)
941945
continue
942-
# log.debug("{}: {}", user, email)
946+
# log.trace("{}: {}", user, email)
943947
emails.append(email)
944948

945949
return emails
@@ -972,14 +976,14 @@ def get_users_with_access_to_system(self, system_id):
972976
for line in lines:
973977
permission, username = line.split(":")
974978
if permission.upper() == "D":
975-
log.debug(
979+
log.trace(
976980
"User [{}] is deactivated for booking system [{}], skipping",
977981
username,
978982
system_id,
979983
)
980984
continue
981985

982-
log.debug(
986+
log.trace(
983987
"User [{}] has permission to book system [{}]", username, system_id
984988
)
985989
users.append(username)
@@ -1068,8 +1072,8 @@ def new_user( # pylint: disable-msg=too-many-arguments
10681072
log.error(msg)
10691073
raise RuntimeError(msg)
10701074

1071-
log.info("Created user [{}] in PPMS.", login)
1072-
log.debug("Response was: {}", response.text)
1075+
log.debug("Created user [{}] in PPMS.", login)
1076+
log.trace("Response was: {}", response.text)
10731077

10741078
def remove_user_access_from_system(self, username, system_id):
10751079
"""Remove permissions for a user to book a given system in PPMS.
@@ -1156,9 +1160,9 @@ def permission_name(shortname):
11561160
# NOTE: the 'setright' action will accept ANY permission type and return 'done'
11571161
# on the request, so there is no way to check from the response if setting the
11581162
# permission really worked!!
1159-
# log.debug('Request returned text: {}', response.text)
1163+
# log.trace('Request returned text: {}', response.text)
11601164
if response.text.lower().strip() == "done":
1161-
log.debug(
1165+
log.trace(
11621166
"User [{}] now has permission level [{}] on system [{}]",
11631167
login,
11641168
permission_name(permission),
@@ -1184,7 +1188,7 @@ def update_systems(self):
11841188
cache. If parsing the PUMAPI response for a system fails for any reason, the
11851189
system is skipped entirely.
11861190
"""
1187-
log.debug("Updating list of bookable systems...")
1191+
log.trace("Updating list of bookable systems...")
11881192
systems = {}
11891193
parse_fails = 0
11901194
response = self.request("getsystems")
@@ -1199,7 +1203,7 @@ def update_systems(self):
11991203

12001204
systems[system.system_id] = system
12011205

1202-
log.debug(
1206+
log.trace(
12031207
"Updated {} bookable systems from PPMS ({} systems failed parsing)",
12041208
len(systems),
12051209
parse_fails,
@@ -1228,7 +1232,7 @@ def update_users(self, user_ids=[], active_only=True):
12281232
if not user_ids:
12291233
user_ids = self.get_user_ids(active=active_only)
12301234

1231-
log.debug("Updating details on {} users", len(user_ids))
1235+
log.trace("Updating details on {} users", len(user_ids))
12321236
for user_id in user_ids:
12331237
self.get_user(user_id, skip_cache=True)
12341238

0 commit comments

Comments
 (0)