Skip to content

Instantly share code, notes, and snippets.

@an01f01
Created July 8, 2022 16:15
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/f68d9ed20b6dd0eb91fc34163109476a to your computer and use it in GitHub Desktop.
Save an01f01/f68d9ed20b6dd0eb91fc34163109476a 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):
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()
"""
POST handler for adding a new book to the database
"""
@gen.coroutine
def post(self):
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
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment