@@ -40,6 +40,8 @@ class PpmsConnection:
40
40
cache_users_only : bool
41
41
Flag indicating that only PPMS user details will be stored in the
42
42
on-disk cache, nothing else.
43
+ last_served_from_cache
44
+ Indicates if the last request was served from the cache or on-line.
43
45
users : dict
44
46
A dict with usernames as keys, mapping to the related
45
47
: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):
108
110
}
109
111
self .cache_path = cache
110
112
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."""
111
115
112
116
# run in cache-only mode (e.g. for testing or off-line usage) if no API
113
117
# key has been specified, skip authentication then:
@@ -126,7 +130,7 @@ def __authenticate(self):
126
130
requests.exceptions.ConnectionError
127
131
Raised in case authentication failed for any reason.
128
132
"""
129
- log .debug (
133
+ log .trace (
130
134
"Attempting authentication against {} with key [{}...{}]" ,
131
135
self .url ,
132
136
self .api_key [:2 ],
@@ -167,7 +171,7 @@ def __authenticate(self):
167
171
log .error (msg )
168
172
raise requests .exceptions .ConnectionError (msg )
169
173
170
- log .info (
174
+ log .debug (
171
175
"Authentication succeeded, response=[{}], http_status=[{}]" ,
172
176
response .text ,
173
177
response .status_code ,
@@ -208,18 +212,18 @@ def request(self, action, parameters={}, skip_cache=False):
208
212
# log.debug("Request parameters: {}", parameters)
209
213
210
214
response = None
211
- read_from_cache = False
212
215
try :
213
216
if skip_cache : # pragma: no cover
214
217
raise LookupError ("Skipping the cache has been requested" )
215
218
response = self .__intercept_read (req_data )
216
- read_from_cache = True
219
+ self . last_served_from_cache = True
217
220
except LookupError as err :
218
- log .debug (f"Doing an on-line request: { err } " )
221
+ log .trace (f"Doing an on-line request: { err } " )
219
222
response = requests .post (self .url , data = req_data , timeout = self .timeout )
223
+ self .last_served_from_cache = False
220
224
221
225
# 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
223
227
self .__intercept_store (req_data , response )
224
228
225
229
# NOTE: the HTTP status code returned is always `200` even if
@@ -390,7 +394,7 @@ def flush_cache(self, keep_users=False):
390
394
will be kept, by default `False`.
391
395
"""
392
396
if self .cache_path == "" :
393
- log .info ("No cache path configured, not flushing!" )
397
+ log .debug ("No cache path configured, not flushing!" )
394
398
return
395
399
396
400
dirs_to_remove = [self .cache_path ] # by default remove the entire cache dir
@@ -404,11 +408,11 @@ def flush_cache(self, keep_users=False):
404
408
continue
405
409
dirs_to_remove .append (os .path .join (self .cache_path , subdir ))
406
410
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 )
408
412
for directory in dirs_to_remove :
409
413
try :
410
414
shutil .rmtree (directory )
411
- log .debug ("Removed directory [{}]." , directory )
415
+ log .trace ("Removed directory [{}]." , directory )
412
416
except Exception as ex : # pylint: disable-msg=broad-except
413
417
log .warning ("Removing the cache at [{}] failed: {}" , directory , ex )
414
418
@@ -427,7 +431,7 @@ def get_admins(self):
427
431
for username in admins :
428
432
user = self .get_user (username )
429
433
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 ))
431
435
return users
432
436
433
437
def get_booking (self , system_id , booking_type = "get" ):
@@ -478,7 +482,7 @@ def get_booking(self, system_id, booking_type="get"):
478
482
if booking_type == "get" :
479
483
desc = "a currently active booking"
480
484
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 )
482
486
return None
483
487
484
488
return PpmsBooking (response .text , booking_type , system_id )
@@ -502,7 +506,7 @@ def get_group(self, group_id):
502
506
line of the PUMAPI response, values from the data line.
503
507
"""
504
508
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 )
506
510
507
511
if not response .text :
508
512
msg = f"Group [{ group_id } ] is unknown to PPMS"
@@ -511,7 +515,7 @@ def get_group(self, group_id):
511
515
512
516
details = dict_from_single_response (response .text )
513
517
514
- log .debug ("Details of group {}: {}" , group_id , details )
518
+ log .trace ("Details of group {}: {}" , group_id , details )
515
519
return details
516
520
517
521
def get_group_users (self , unitlogin ):
@@ -534,7 +538,7 @@ def get_group_users(self, unitlogin):
534
538
for username in members :
535
539
user = self .get_user (username )
536
540
users .append (user )
537
- log .debug (
541
+ log .trace (
538
542
"{} members in PPMS group [{}]: {}" ,
539
543
len (members ),
540
544
unitlogin ,
@@ -553,7 +557,7 @@ def get_groups(self):
553
557
response = self .request ("getgroups" )
554
558
555
559
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 ))
557
561
return groups
558
562
559
563
def get_next_booking (self , system_id ):
@@ -593,17 +597,17 @@ def get_running_sheet(self, core_facility_ref, date, ignore_uncached_users=False
593
597
"plateformid" : f"{ core_facility_ref } " ,
594
598
"day" : date .strftime ("%Y-%m-%d" ),
595
599
}
596
- log .debug ("Requesting runningsheet for {}" , parameters ["day" ])
600
+ log .trace ("Requesting runningsheet for {}" , parameters ["day" ])
597
601
response = self .request ("getrunningsheet" , parameters )
598
602
try :
599
603
entries = parse_multiline_response (response .text , graceful = False )
600
604
except NoDataError :
601
605
# 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!" )
603
607
return []
604
608
except Exception as err : # pylint: disable-msg=broad-except
605
609
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 )
607
611
return []
608
612
609
613
for entry in entries :
@@ -613,14 +617,14 @@ def get_running_sheet(self, core_facility_ref, date, ignore_uncached_users=False
613
617
log .debug ("Ignoring booking for uncached user [{}]" , full )
614
618
continue
615
619
616
- log .info ("Booking for an uncached user ({}) found!" , full )
620
+ log .debug ("Booking for an uncached user ({}) found!" , full )
617
621
self .update_users ()
618
622
619
623
if full not in self .fullname_mapping :
620
624
log .error ("PPMS doesn't seem to know user [{}], skipping" , full )
621
625
continue
622
626
623
- log .info (
627
+ log .trace (
624
628
"Booking for user '{}' ({}) found" , self .fullname_mapping [full ], full
625
629
)
626
630
system_name = entry ["Object" ]
@@ -659,7 +663,7 @@ def get_systems(self, force_refresh=False):
659
663
fails for any reason, the system is skipped entirely.
660
664
"""
661
665
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 ))
663
667
else :
664
668
self .update_systems ()
665
669
@@ -702,7 +706,7 @@ def get_systems_matching(self, localisation, name_contains):
702
706
if localisation == "" :
703
707
loc_desc = "(no location filter given)"
704
708
705
- log .info (
709
+ log .trace (
706
710
"Querying PPMS for systems {}, name matching any of {}" ,
707
711
loc_desc ,
708
712
name_contains ,
@@ -719,7 +723,7 @@ def get_systems_matching(self, localisation, name_contains):
719
723
)
720
724
continue
721
725
722
- # log.debug ('System [{}] is matching location [{}], checking if '
726
+ # log.trace ('System [{}] is matching location [{}], checking if '
723
727
# 'the name is matching any of the valid pattern {}',
724
728
# system.name, loc, name_contains)
725
729
for valid_name in name_contains :
@@ -729,11 +733,11 @@ def get_systems_matching(self, localisation, name_contains):
729
733
break
730
734
731
735
# 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: {}',
733
737
# system.name, name_contains)
734
738
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 )
737
741
return system_ids
738
742
739
743
def get_user (self , login_name , skip_cache = False ):
@@ -826,7 +830,7 @@ def get_user_dict(self, login_name, skip_cache=False):
826
830
# u'true\r\n'
827
831
# )
828
832
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 )
830
834
return details
831
835
832
836
def get_user_experience (self , login = None , system_id = None ):
@@ -854,7 +858,7 @@ def get_user_experience(self, login=None, system_id=None):
854
858
response = self .request ("getuserexp" , parameters = data )
855
859
856
860
parsed = parse_multiline_response (response .text )
857
- log .debug (
861
+ log .trace (
858
862
"Received {} experience entries for filters [user:{}] and [id:{}]" ,
859
863
len (parsed ),
860
864
login ,
@@ -886,8 +890,8 @@ def get_user_ids(self, active=False):
886
890
887
891
users = response .text .splitlines ()
888
892
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 ))
891
895
return users
892
896
893
897
def get_users (self , force_refresh = False , active_only = True ):
@@ -908,7 +912,7 @@ def get_users(self, force_refresh=False, active_only=True):
908
912
A dict of PpmsUser objects with the username (login) as key.
909
913
"""
910
914
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 ))
912
916
else :
913
917
self .update_users (active_only = active_only )
914
918
@@ -939,7 +943,7 @@ def get_users_emails(self, users=None, active=False):
939
943
if not email :
940
944
log .warning ("--- WARNING: no email for user [{}]! ---" , user )
941
945
continue
942
- # log.debug ("{}: {}", user, email)
946
+ # log.trace ("{}: {}", user, email)
943
947
emails .append (email )
944
948
945
949
return emails
@@ -972,14 +976,14 @@ def get_users_with_access_to_system(self, system_id):
972
976
for line in lines :
973
977
permission , username = line .split (":" )
974
978
if permission .upper () == "D" :
975
- log .debug (
979
+ log .trace (
976
980
"User [{}] is deactivated for booking system [{}], skipping" ,
977
981
username ,
978
982
system_id ,
979
983
)
980
984
continue
981
985
982
- log .debug (
986
+ log .trace (
983
987
"User [{}] has permission to book system [{}]" , username , system_id
984
988
)
985
989
users .append (username )
@@ -1068,8 +1072,8 @@ def new_user( # pylint: disable-msg=too-many-arguments
1068
1072
log .error (msg )
1069
1073
raise RuntimeError (msg )
1070
1074
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 )
1073
1077
1074
1078
def remove_user_access_from_system (self , username , system_id ):
1075
1079
"""Remove permissions for a user to book a given system in PPMS.
@@ -1156,9 +1160,9 @@ def permission_name(shortname):
1156
1160
# NOTE: the 'setright' action will accept ANY permission type and return 'done'
1157
1161
# on the request, so there is no way to check from the response if setting the
1158
1162
# permission really worked!!
1159
- # log.debug ('Request returned text: {}', response.text)
1163
+ # log.trace ('Request returned text: {}', response.text)
1160
1164
if response .text .lower ().strip () == "done" :
1161
- log .debug (
1165
+ log .trace (
1162
1166
"User [{}] now has permission level [{}] on system [{}]" ,
1163
1167
login ,
1164
1168
permission_name (permission ),
@@ -1184,7 +1188,7 @@ def update_systems(self):
1184
1188
cache. If parsing the PUMAPI response for a system fails for any reason, the
1185
1189
system is skipped entirely.
1186
1190
"""
1187
- log .debug ("Updating list of bookable systems..." )
1191
+ log .trace ("Updating list of bookable systems..." )
1188
1192
systems = {}
1189
1193
parse_fails = 0
1190
1194
response = self .request ("getsystems" )
@@ -1199,7 +1203,7 @@ def update_systems(self):
1199
1203
1200
1204
systems [system .system_id ] = system
1201
1205
1202
- log .debug (
1206
+ log .trace (
1203
1207
"Updated {} bookable systems from PPMS ({} systems failed parsing)" ,
1204
1208
len (systems ),
1205
1209
parse_fails ,
@@ -1228,7 +1232,7 @@ def update_users(self, user_ids=[], active_only=True):
1228
1232
if not user_ids :
1229
1233
user_ids = self .get_user_ids (active = active_only )
1230
1234
1231
- log .debug ("Updating details on {} users" , len (user_ids ))
1235
+ log .trace ("Updating details on {} users" , len (user_ids ))
1232
1236
for user_id in user_ids :
1233
1237
self .get_user (user_id , skip_cache = True )
1234
1238
0 commit comments