Belle II Software  release-05-01-25
rundb.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 
4 '''
5 rundb - Helper classes for retrieving information from the RunDB
6 ----------------------------------------------------------------
7 
8 This modules contains classes useful to deal with the RunDB:
9 
10 * `RunDB`, a simple API class to just get run information from the RunDB
11 '''
12 
13 import requests
14 import getpass
15 
16 
17 class RunDB:
18  """
19  Simple API class to just get run information from the RunDB.
20 
21  Parameters:
22  apikey (str): RunDB API key (see `here <https://questions.belle2.org/question/9847/obtaining-api-key-for-rundb/>`_
23  how to get one)
24  username (str): DESY username
25  """
26 
27 
28  URL = "https://rundb.belle2.org"
29 
30  def __init__(self, apikey=None, username=None):
31  """Create an object and setup authentication."""
32  self._session = requests.Session()
33  if apikey is None:
34  # If no specific username use the local system username
35  if username is None:
36  username = getpass.getuser()
37  # If we don't have an api key use desy username/password
38  self._session.auth = (username, getpass.getpass(f"DESY password ({username}): "))
39  else:
40  # Otherwise use the api key
41  self._session.headers.update({'Authorization': f'Bearer {apikey}'})
42  # And request json output ...
43  self._session.headers.update({'Content-Type': 'application/json'})
44 
45  def _pagination(self, request):
46  """Deal with API pagination of an initial request to the API.
47 
48  It will return all the objects from all pages lazily requesting new pages
49  as objects are consumed. Will work for all list requests to the server.
50  """
51  while True:
52  # check the return value and raise exception on error
53  request.raise_for_status()
54  # and otherwise get the json
55  result = request.json()
56  # and return the objects one by one by yielding objects from the list
57  # of results
58  yield from result['results']
59  # check if there's a next page, if not done
60  if result['next'] is None:
61  break
62  # otherwise continue with the next page
63  # yees, global variable ...
64  request = self._session.get(result['next'])
65 
66  def get_run_info(self, **search_params):
67  """Return the run information from the run registry.
68 
69  All arguments are forwarded to the run registry ``/run/`` method
70  documented at the following `link <https://rundb.belle2.org/rest/v1/swagger/>`_.
71  Please check there for up to date documentation, at the time of
72  this writing the supported arguments are:
73 
74  * min_experiment (int)
75  * min_run (int)
76  * max_experiment (int)
77  * max_run (int)
78  * min_date (iso8601 date string, e.g. 2020-05-06)
79  * max_date (iso8601 date string, e.g. 2020-05-06)
80  * all_detectors_running (bool)
81  * expand (bool): If true return full run objects, not just a summary
82  links to the run objects
83 
84  If ``expand=False`` you can request the full objects for each run by calling
85  `get_details` with the returned run summary object as argument.
86  ``expand=False`` is much faster if no further details are needed but
87  getting the details in a separate step for many many runs will be slow
88  so depending on how many runs are selected one or the other may be
89  faster.
90  """
91  req = self._session.get(f'{self.URL}/rest/v1/runs/', params=search_params)
92  return self._pagination(req)
93 
94  def get_details(self, run_summary):
95  """
96  Return details for a run summary object returned from `get_run_info`
97  if ``expand`` was not set to True
98 
99  Parameters:
100  run_summary: a run summary object returned from `get_run_info`
101  """
102  # Get the url object
103  req = self._session.get(run_summary['url'])
104  # Raise an exception in case of any error
105  req.raise_for_status()
106  # And return the json object
107  return req.json()
rundb.RunDB._session
_session
Definition: rundb.py:32
rundb.RunDB.get_details
def get_details(self, run_summary)
Definition: rundb.py:94
rundb.RunDB.get_run_info
def get_run_info(self, **search_params)
Definition: rundb.py:66
rundb.RunDB.__init__
def __init__(self, apikey=None, username=None)
Definition: rundb.py:30
rundb.RunDB
Definition: rundb.py:17
rundb.RunDB._pagination
def _pagination(self, request)
Definition: rundb.py:45