Skip to content

Commit

Permalink
google books search endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
bbengfort committed May 18, 2015
1 parent 2283749 commit 62a9f19
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 7 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ env:
- EMAIL_HOST_PASSWORD=''
- GOOGLE_OAUTH2_CLIENT_ID=''
- GOOGLE_OAUTH2_CLIENT_SECRET=''
- GOOGLE_BOOKS_API_KEY=''

notifications:
email:
Expand Down
19 changes: 16 additions & 3 deletions stacks/books/gbs.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,10 @@ class GoogleBooks(object):

ENDPOINT = "https://www.googleapis.com/books/v1/volumes"

def __init__(self, **kwargs):
def __init__(self, apikey=None, **kwargs):

# add in the API key
self.apikey = apikey

# add any additional parameters to query or orverride defaults:
for (k, v) in kwargs.iteritems():
Expand Down Expand Up @@ -209,6 +212,11 @@ def get_required_params(self):
Returns a dictionary of the parameters that must be added to the
query.
"""
if self.apikey:
return {
"key": self.apikey,
}

return {}

def execute(self, params):
Expand Down Expand Up @@ -279,8 +287,9 @@ def authors(self):
will be helpful
Note: Currently yields full name strings.
"""
for author in self['authors']:
yield author
if self['authors']:
for author in self['authors']:
yield author

@property
def publisher(self):
Expand Down Expand Up @@ -341,6 +350,9 @@ def thumbnail_url(self):
with the Google specific identifier.
TODO: Strip weirdness out of URL
"""
if not self["imageLinks"]:
return None

sizes = ("thumbnail", "smallThumbnail")
for size in sizes:
if size in self["imageLinks"]:
Expand Down Expand Up @@ -429,6 +441,7 @@ def serialize(self):
'pages': self.pages,
'description': self.description,
'language': self.language,
'thumbnail': self.thumbnail_url,
}

def __getitem__(self, name):
Expand Down
6 changes: 3 additions & 3 deletions stacks/books/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ class BookMediaSerializer(serializers.ModelSerializer):
download data for a piece of media for a book.
"""

book = serializers.RelatedField(many=False)
uploader = serializers.RelatedField(many=False)
book = serializers.HyperlinkedRelatedField(view_name='api:book-detail', read_only=True)
uploader = serializers.HyperlinkedRelatedField(view_name='api:user-detail', read_only=True)
content = AbsoluteFileField()

class Meta:
Expand Down Expand Up @@ -88,7 +88,7 @@ class BookSerializer(serializers.ModelSerializer):
publisher = PublisherSerializer(many=False)
media = SimpleBookMediaSerializer(many=True)
cover = AbsoluteImageField()
tags = serializers.RelatedField(many=True)
tags = serializers.StringRelatedField(many=True)
description = MarkdownField()

class Meta:
Expand Down
47 changes: 47 additions & 0 deletions stacks/books/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,53 @@ class BookMediaViewSet(viewsets.ModelViewSet):
queryset = BookMedia.objects.all()
serializer_class = BookMediaSerializer


from books.gbs import QueryBuilder, GoogleBooks
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings

class GoogleBooksSearch(viewsets.ViewSet):

def list(self, request):
"""
The search endpoint - queries the Google Books API.
"""
isbn = request.query_params.get('isbn')
title = request.query_params.get('title')


if isbn:
# ISBN takes the highest preference
query = QueryBuilder(isbn=isbn)

elif title:
# Search for title keywords as second preference
query = QueryBuilder(intitle=title)

else:
# Required to search for either ISBN or Title
return Response({
"message": "Welcome to the Google Books Search interface, query with either title or isbn."
})

result = GoogleBooks(apikey=settings.GOOGLE_BOOKS_API_KEY).lookup(query)

if result is None:
return Response({
'isbn': isbn,
'success': False,
'message': "Could not find an ISBN that matched the query."
}, status=status.HTTP_404_NOT_FOUND)

elif isinstance(result, list):
return Response([
book.serialize() for book in result
])

else:
return Response(result.serialize())

##########################################################################
## Normal HTTP Views for Browser
##########################################################################
Expand Down
6 changes: 6 additions & 0 deletions stacks/stacks/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,12 @@ def environ_setting(name, default=None):
'PAGINATE_BY': 50,
}

##########################################################################
## Google Books API Key
##########################################################################

GOOGLE_BOOKS_API_KEY = environ_setting('GOOGLE_BOOKS_API_KEY', '')

##########################################################################
## AWS Access Keys
##########################################################################
Expand Down
2 changes: 2 additions & 0 deletions stacks/stacks/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from rest_framework import routers
from users.views import UserViewSet
from stacks.views import HeartbeatViewSet
from books.views import GoogleBooksSearch

##########################################################################
## Endpoint Discovery
Expand All @@ -36,6 +37,7 @@
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'status', HeartbeatViewSet, "status")
router.register(r'gbs', GoogleBooksSearch, "gbs")

#############################################################################
## The URL Patterns for the app
Expand Down
2 changes: 1 addition & 1 deletion stacks/stacks/utils/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def to_native(self, value):
##########################################################################


class MarkdownField(serializers.WritableField):
class MarkdownField(serializers.Field):

def to_native(self, obj):
return unicode(obj)

0 comments on commit 62a9f19

Please sign in to comment.