diff --git a/sru/almasru.py b/sru/almasru.py index dd300db1be65e298e965b5e6f41d41624da024bc..f756b384501e58b14852508e273cbc5b3d42a7ab 100644 --- a/sru/almasru.py +++ b/sru/almasru.py @@ -77,14 +77,27 @@ class RecordRetriever: :raises SruDiagnostics: if SRU returns an error """ + sru_url = self._create_url(alma_query) + + response = request.urlopen(sru_url).read() + sru_xml = fromstring(response) + + self._raise_errors_single_records(sru_xml) + + xml_list = self._extract_marc_xml(sru_xml, namespaces) + return xml_list[0] + + def _create_url(self, alma_query: str) -> str: + self.url_query['startRecord'] = '0' self.url_query['maximumRecords'] = '1' self.url_query['query'] = alma_query url_query_string = parse.urlencode(self.url_query) sru_url = self.url_base + url_query_string - response = request.urlopen(sru_url).read() - sru_xml = fromstring(response) + return sru_url + + def _raise_errors_single_records(self, sru_xml: Element): namespaces = { 'srw': 'http://www.loc.gov/zing/srw/', @@ -95,14 +108,14 @@ class RecordRetriever: num_recs = sru_xml.find("srw:numberOfRecords", namespaces) if ( - num_recs is not None and - num_recs.text == '0' + num_recs is not None and + num_recs.text == '0' ): raise NoRecord('No matching records found!') elif ( - num_recs is not None and - num_recs.text > '1' + num_recs is not None and + num_recs.text > '1' ): raise MultiRecord('More than one record found' 'while exactly one was expected!') @@ -112,10 +125,10 @@ class RecordRetriever: sru_message = sru_xml.find(xpath, namespaces).text raise SruDiagnostics(sru_message) - else: - record_xpath = 'srw:records/srw:record//marc:record' - marc_xml = sru_xml.find(record_xpath, namespaces) - return marc_xml + def _extract_marc_xml(self, sru_xml, namespaces): + record_xpath = 'srw:records/srw:record//marc:record' + marc_xml = sru_xml.findall(record_xpath, namespaces) + return marc_xml def by_marc_009(self, marc_009: str) -> Element: """Return record by MARC 009 (control number).