def create_book(user_id: int, args: dict, author_id: int):
    Author.query.get_or_404(
        author_id, description=f'Author with id {author_id} not found')
    if Book.query.filter(Book.isbn == args['isbn']).first():
        abort(409, description=f'Bok with ISBN {args["isbn"]} already exists')

    book = Book(author_id=author_id, **args)
    db.session.add(book)
    db.session.commit()

    return jsonify({'success': True, 'data': book_schema.dump(book)}), 201
Exemplo n.º 2
0
def add_data():
    """Add sample data to database."""
    try:
        data_json = load_json_data('authors.json')
        for item in data_json:
            item['birth_date'] = datetime.strptime(item['birth_date'], '%d-%m-%Y').date()
            author = Author(**item)
            db.session.add(author)

        data_json = load_json_data('books.json')
        for item in data_json:
            book = Book(**item)
            db.session.add(book)

        db.session.commit()
        print('Data has been successfully added to the database.')
    except Exception as exc:
        print('Unexpected error: {}'.format(exc))