Skip to content

Instantly share code, notes, and snippets.

@hornc
Last active April 19, 2017 07:26
Show Gist options
  • Save hornc/36a6cadb4aa0a7c6eee4272bd15a5b68 to your computer and use it in GitHub Desktop.
Save hornc/36a6cadb4aa0a7c6eee4272bd15a5b68 to your computer and use it in GitHub Desktop.
Update single author test
from olclient.openlibrary import OpenLibrary
import json
import csv
import re
ol = OpenLibrary(base_url = 'https://dev.openlibrary.org')
def wikidata_id(url):
return re.search(r'[^/]*$', url).group(0)
def save_author(olid, data, comment):
data['_comment'] = comment
url = ol.base_url + "/authors/" + olid + ".json"
return ol.session.put(url, json.dumps(data))
def add_ids(author, viaf, wikidata):
r = ol.session.get(ol.base_url + "/authors/" + author + ".json")
# could check whether r.status_code == 200
data = r.json()
if 'remote_ids' in data and 'viaf' in data['remote_ids']:
if data['remote_ids']['viaf'] == viaf:
return "VIAF %s already added" % viaf
data[u'remote_ids'] = {u'viaf': viaf, u'wikidata': wikidata}
return save_author(author, data, "add VIAF and wikidata ID")
fname = 'some.csv'
with open(fname, 'rb') as f:
reader = csv.reader(f)
for row in reader:
wiki_url, name, viaf, olid = row
wiki_id = wikidata_id(wiki_url)
print name, olid, viaf, wiki_id
print add_ids(olid, viaf, wiki_id)
@mekarpeles
Copy link

On line #19 you can do r.json() (and not need to import json)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment