Skip to content

Instantly share code, notes, and snippets.

@an01f01
Created July 14, 2022 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save an01f01/66ea49677932730b01266d9a0e261709 to your computer and use it in GitHub Desktop.
Save an01f01/66ea49677932730b01266d9a0e261709 to your computer and use it in GitHub Desktop.
class BooksHandler(BaseHandler):
def initialize(self):
database_url = os.environ['BOOKS_DB_CONN']
self.session = queries.TornadoSession(uri=database_url)
"""
GET handler for fetching numbers from database
"""
@gen.coroutine
def get(self):
auth_header = self.request.headers.get('Authorization')
print(auth_header)
if auth_header:
auth_token = auth_header.split(" ")[1]
else:
auth_token = ''
if auth_token:
token = decode_auth_token(auth_token)
print(token)
if token['success'] == 0:
try:
sql = "SELECT array_to_json(array_agg(row_to_json(json))) json FROM (SELECT bookid, title, book_info FROM books ORDER BY title) as json;"
results = yield self.session.query(sql, {})
data_ret = results.as_dict()
results.free()
print(data_ret)
self.set_status(200)
self.write({'message': 'All books sorted by title', 'books': data_ret['json']})
self.finish()
except (queries.DataError, queries.IntegrityError) as error:
print(error)
self.set_status(500)
self.write({'message': 'Error getting books', 'books': [] })
self.finish()
else:
self.set_status(401)
self.write({'status': 'fail', 'message': token['message'] })
self.finish()
return
else:
self.set_status(403)
self.write({'status': 'fail', 'message': 'Invalid authentication token' })
self.finish()
return
"""
POST handler for adding a new book to the database
"""
@gen.coroutine
def post(self):
auth_header = self.request.headers.get('Authorization')
if auth_header:
auth_token = auth_header.split(" ")[1]
else:
auth_token = ''
if auth_token:
book_json = self.request.body.decode('utf-8')
if (book_json == None or book_json == ''):
self.set_status(200)
self.write({'message': 'Book data is missing', 'book': {}})
self.finish()
return
try:
book_json = tornado.escape.json_decode(book_json)
except (Exception) as e:
self.set_status(500)
self.write({'message': 'Error: Book data is not in valid JSON format', 'book': {} })
self.finish()
return
token = decode_auth_token(auth_token)
if token['success'] == 0:
if 'title' not in book_json:
self.set_status(200)
self.write({'message': 'Error: book data is missing title, no book was created', 'book': {} })
self.finish()
return
book_json['book_info'] = book_json.get('book_info', {})
try:
sql = "INSERT INTO public.books(title, book_info) VALUES (%(book_title)s, %(book_info)s) RETURNING json_build_object('title', title, 'book_info', book_info);"
results = yield self.session.query(sql, {'book_title': book_json['title'], 'book_info': tornado.escape.json_encode(book_json['book_info'])})
data_ret = results.as_dict()
results.free()
self.set_status(201)
self.write({'message': 'Book added', 'book': data_ret['json_build_object']})
self.finish()
except (queries.DataError, queries.IntegrityError) as error:
print(error)
self.set_status(500)
self.write({'message': 'Error: no book with that id exists', 'book': {} })
self.finish()
else:
self.set_status(401)
self.write({'status': 'fail', 'message': token['message'] })
self.finish()
return
else:
self.set_status(403)
self.write({'status': 'fail', 'message': 'Invalid authentication token' })
self.finish()
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment