juhoinkinen commited on
Commit
0166771
1 Parent(s): bad373d

Upload collect.py

Browse files
Files changed (1) hide show
  1. collect.py +62 -0
collect.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import traceback
4
+ import time
5
+ import sys
6
+ import sickle
7
+ from lxml import etree
8
+
9
+ # monkey patch sickle.response to handle large XML responses
10
+ # by enabling the huge_tree option (aka XML_PARSE_HUGE)
11
+
12
+ sickle.response.XMLParser = etree.XMLParser(remove_blank_text=True,
13
+ recover=True,
14
+ resolve_entities=False,
15
+ huge_tree=True)
16
+
17
+ headers = {
18
+ 'User-Agent': 'Annif-Finna-collect'
19
+ }
20
+
21
+ sickle = sickle.Sickle('https://api.finna.fi/OAI/Server', headers=headers)
22
+
23
+ if len(sys.argv) > 1:
24
+ current_token = sys.argv[1]
25
+ else:
26
+ current_token = None
27
+
28
+ while True:
29
+ params = { 'metadataPrefix': 'oai_vufind_json',
30
+ 'set': 'non_dedup',
31
+ 'timeout': 30 }
32
+
33
+ if current_token is not None:
34
+ params['resumptionToken'] = current_token
35
+
36
+ try:
37
+ print("Performing call with params {}".format(params), file=sys.stderr)
38
+ records = sickle.ListRecords(**params)
39
+
40
+ for idx, rec in enumerate(records):
41
+ if records.resumption_token:
42
+ token = records.resumption_token.token
43
+ if token != current_token:
44
+ print("Resumption token: {} expires: {}".format(token, records.resumption_token.expiration_date), file=sys.stderr)
45
+ current_token = token
46
+ else:
47
+ print("No resumption token in response", file=sys.stderr)
48
+ print(records.oai_response.raw, file=sys.stderr)
49
+ current_token = None
50
+ if 'metadata' in rec.metadata and len(rec.metadata['metadata']) > 0:
51
+ json_data = rec.metadata['metadata'][0]
52
+ print(json_data)
53
+
54
+ if current_token is None:
55
+ # all records received, no token - we have probably reached the end
56
+ print("No further records, all done.", file=sys.stderr)
57
+ break
58
+
59
+ except Exception as e:
60
+ print(traceback.format_exc(), file=sys.stderr)
61
+ print("Waiting for 10 seconds before retrying...", file=sys.stderr)
62
+ time.sleep(10)