moviewyrm/fedireads/openlibrary.py

52 lines
1.8 KiB
Python
Raw Normal View History

2020-01-25 21:46:30 +00:00
''' activitystream api and books '''
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest
from django.core.exceptions import ObjectDoesNotExist
from django.core import serializers
2020-01-25 23:25:19 +00:00
from fedireads.models import Author, Book, Work
2020-01-25 21:46:30 +00:00
import requests
openlibrary_url = 'https://openlibrary.org'
def get_book(request, olkey):
# check if this is a valid open library key, and a book
response = requests.get(openlibrary_url + '/book/' + olkey + '.json')
# get the existing entry from our db, if it exists
try:
book = Book.objects.get(openlibary_key=olkey)
except ObjectDoesNotExist:
book = Book(openlibary_key=olkey)
data = response.json()
book.data = data
2020-01-26 20:14:27 +00:00
if request and request.user and request.user.is_authenticated:
book.added_by = request.user
2020-01-25 21:46:30 +00:00
book.save()
for work_id in data['works']:
work_id = work_id['key']
book.works.add(get_or_create_work(work_id))
2020-01-25 23:25:19 +00:00
for author_id in data['authors']:
author_id = author_id['key']
book.authors.add(get_or_create_author(author_id))
2020-01-25 21:46:30 +00:00
return HttpResponse(serializers.serialize('json', [book]))
def get_or_create_work(olkey):
try:
work = Work.objects.get(openlibary_key=olkey)
except ObjectDoesNotExist:
2020-01-25 23:25:19 +00:00
response = requests.get(openlibrary_url + olkey + '.json')
2020-01-25 21:46:30 +00:00
data = response.json()
work = Work(openlibary_key=olkey, data=data)
work.save()
return work
2020-01-25 23:25:19 +00:00
def get_or_create_author(olkey):
try:
author = Author.objects.get(openlibary_key=olkey)
except ObjectDoesNotExist:
response = requests.get(openlibrary_url + olkey + '.json')
data = response.json()
author = Author(openlibary_key=olkey, data=data)
author.save()
return author