Пример #1
0
def first_loader():
    df = pd.read_csv(
        'main/management/commands/all_celebrities_data_processed.csv')
    df = df[~pd.isna(df['ISBN'])]
    for book_title in df['title'].unique():
        print(f'Adding {book_title} to the DB')
        filtered = df[df['title'] == book_title].head(1)
        for index, row in filtered.iterrows():
            newbook = Book(title_en=row['title'],
                           author=row['author'],
                           isbn=row['ISBN'])
            newbook.save()

    for celeb in df['influencer'].unique():
        print(f'Adding {celeb} to the DB')
        influencer = Influencer(name=celeb)
        influencer.save()
        filtered = df[df['influencer'] == celeb]
        for index, row in filtered.iterrows():

            try:
                print(f'Added book {row["title"]} to recommended by {celeb}')
                book_to_add = Book.objects.get(isbn=row['ISBN'])
                influencer.recommended_books.add(book_to_add)
            except Exception as e:
                print(
                    f'An exception occured when trying to add books for {celeb},\
                    trying to add row: {row} \n got the following exception: {str(e)}'
                )
Пример #2
0
    def handle(self, *args, **options):
        book = Book.objects.get(title='Good Omens')
        print(book.title)
        print(book.year_published)

        print(book.authors.all())
        for author in book.authors.all():
            print(author.name)

        author = Author.objects.get(name='Terry Pratchett')
        print(author.books.all())
        for book in author.books.all():
            print(book.title)

        # book = Book(title='Tiny Pretty Things', year_published=2019)
        # book.save()

        # author1 = Author(name='Sona Charaipotra')
        # author1.save()

        # author2 = Author(name='Dhonielle Clayton')
        # author2.save()

        # book.authors.add(author1)
        # book.authors.add(author2)

        # book.authors.set([author1, author2])

        # book.authors.clear()

        books_data = [{
            'title': 'Hogfather',
            'year_published': 1996,
            'authors': ['Terry Pratchett']
        }, {
            'title': 'Wyrd Sisters',
            'year_published': 1988,
            'authors': ['Terry Pratchett']
        }]

        for book_data in books_data:
            title = book_data['title']
            year_published = book_data['year_published']

            book = Book(title=title, year_published=year_published)
            book.save()

            for author_name in book_data['authors']:

                # author = author.objects.get(name=author_name)

                # author = Author(name=author_name)
                # author.save()

                author, created = Author.objects.get_or_create(
                    name=author_name)

                book.authors.add(author)
Пример #3
0
def create_book(course_id):
    form = BookForm()
    if form.validate_on_submit():
        title = form.book_title.data
        params = {'q': title, 'key': os.environ['API_KEY']}
        response = requests.get('https://www.googleapis.com/books/v1/volumes',
                                params=params)
        if response.status_code == 200:
            api_response = json.loads(response.text)
            first_book = api_response["items"][0]
            if first_book is None:
                flash('Your book has not been found. Try adding another book.')
                return redirect(url_for('.show_admin_course'))
            else:
                volume_info = first_book["volumeInfo"]
                title = volume_info["title"]
                thumbnail = volume_info["imageLinks"]["thumbnail"]
                preview_link = volume_info["previewLink"]
                book = Book(book_title=title,
                            thumbnail=thumbnail,
                            preview_link=preview_link,
                            course_id=course_id)
                db.session.add(book)
                db.session.commit()
                flash('Your book has been added to the course.')
                return redirect(url_for('.show_admin_dashboard'))
        flash('Your book has not been found.')
        return redirect(url_for('.show_admin_dashboard'))

    return render_template('book_form.html', form=form)
Пример #4
0
def page(request, slug):
    try:
        book = Book.get()
        page = book.pages.get(slug=slug)
    except ObjectDoesNotExist:
        raise Http404
    return {
        'page': page
    }
Пример #5
0
def index(request):
    try:
        book = Book.get()
        page = book.pages.get(slug='index')
    except ObjectDoesNotExist:
        page = None
    return {
        'page': page
    }
Пример #6
0
def populate_database(request):
    mobooks_db = connect_to_db()

    books_collection = mobooks_db['main_book']
    books_collection.drop()
    with open('static/pop_data/books.json') as file:
        data = json.load(file)
        for datum in data:
            book = Book(title=datum['title'],
                        release_year=datum['release_year'],
                        author=datum['author'],
                        genre=datum['genre'],
                        publisher=datum['publisher'],
                        synopsis=datum['synopsis'],
                        available_quantity=datum['available_quantity'])
            Book.save(book)

    authors_collection = mobooks_db['main_author']
    authors_collection.drop()
    with open('static/pop_data/authors.json') as file:
        data = json.load(file)
        for datum in data:
            author = Author(name=datum['author'])
            Author.save(author)

    genres_collection = mobooks_db['main_genre']
    genres_collection.drop()
    with open('static/pop_data/genres.json') as file:
        data = json.load(file)
        for datum in data:
            genre = Genre(name=datum['genre'])
            Genre.save(genre)

    publishers_collection = mobooks_db['main_publisher']
    publishers_collection.drop()
    with open('static/pop_data/publishers.json') as file:
        data = json.load(file)
        for datum in data:
            publisher = Publisher(name=datum['publisher'])
            Publisher.save(publisher)
    return redirect('/')
Пример #7
0
def populateLibros():
    print("Cargando libros...")
        
    lista=[]
    fileobj=open(path+"\\books.csv", "r")
    for line in fileobj.readlines()[1:]:
        rip = line.split(';')
        l=Book(isbn=int(rip[0]), titulo=rip[1], autor=rip[2], anyo=rip[3], editor=rip[4])
        lista.append(l)
    Book.objects.bulk_create(lista)  # bulk_create hace la carga masiva para acelerar el proceso
    
    print("Libros añadidos: " + str(Book.objects.count()))
    print("---------------------------------------------------------")
Пример #8
0
    def put(self, request, id=None):
        post = request.POST
        if not self._validate(post.keys()):
            return JsonResponse(self.parameter_error_resp)

        authors = self._get_authors_or_fail(post['authors'])
        if not authors:
            return JsonResponse(self.authors_error_resp)

        del post['authors']
        book = Book(id=id)
        for key, value in post.items():
            setattr(book, key, value)
        book.save()
        book.authors.clear()
        book.authors.add(*authors)

        resp = {
            'status': 200,
            'result': Book.objects.get_from_id_with_authors(id)
        }
        return JsonResponse(resp)
Пример #9
0
def second_loader():
    df = pd.read_csv('main/management/commands/final_df.csv')
    for book_title in df['title'].unique():
        print(f'Adding {book_title} to the DB')
        filtered = df[df['title'] == book_title].head(1)
        for index, row in filtered.iterrows():
            title_en = row['title_en']
            title_pt = row['title_pt']
            author = row['author_y']
            isbn_pt = row['isbn_pt']
            isbn_en = row['id_code']
            img_url = row['img_amz']
            newbook = Book(title_en=title_en,
                           title_pt=title_pt,
                           author=author,
                           isbn_pt=isbn_pt,
                           isbn_en=isbn_en,
                           img_url=img_url)
            newbook.save()
    for celeb in df['influencer'].unique():
        print(f'Adding {celeb} to the DB')
        influencer = Influencer(name=celeb)
        influencer.save()
        filtered_df = df[df['influencer'] == celeb]
        for index, row in filtered_df.iterrows():
            try:
                print(
                    f'Added book {row["title"]} to the recommended by {celeb}')
                book_to_add = Book.objects.get(isbn_en=row['id_code'])
                influencer.recommended_books.add(book_to_add)
            except Exception as e:
                print(
                    f'An exception occured when trying to add books for {celeb},\
                    trying to add row: {row} \n got the following exception: {str(e)}'
                )


### testing a change
Пример #10
0
    def handle(self, *args, **options):
        faker = Faker()
        file = "book genres.txt"
        for _ in range(300):
            Author(name=faker.name(), email=faker.email()).save()

        with open(file, "r") as file:
            for line in file:
                Category(title=line).save()

        for i in range(1000):
            author = Author.objects.order_by("?").last()
            category = Category.objects.order_by("?").last()
            Book(title=f"Title {i}", author=author, category=category).save()
Пример #11
0
def create(request):
    # Get the user object for the logged in user
    this_user = User.objects.get(id=request.session['userid'])

    # Add new book and review
    print(request.POST)

    if request.POST['author_name'] != '':
        # Check if that author name is already in the database
        # ...And if it is, then use the existing record, do not add a new author
        authors_found = Author.objects.filter(
            name=request.POST['author_name'].strip())
        if authors_found:
            this_author = authors_found[0]
        else:
            # Adding a new author
            this_author = Author(name=request.POST['author_name'].strip())
            this_author.save()
            print('new_author.name', this_author.name)

    else:
        print('Using an author from select list')
        # get the user pulled from the select menu
        this_author = Author.objects.get(id=request.POST['author_list'])
        print('this_author', this_author.name, this_author.id)

    # Add the book
    new_book = Book(title=request.POST['title'],
                    author=this_author, user=this_user)
    new_book.save()

    # Add the review
    new_review = Review(
        text=request.POST['review'], rating=request.POST['rating'], book=new_book, user=this_user)
    new_review.save()

    return redirect('/books/'+str(new_book.id))
Пример #12
0
    def handle(self, *args, **options):
        fake = Faker()
        for _ in range(10):
            Author(name=fake.name(),
                   email=fake.email(),
                   age=random.randint(1, 100)).save()

        categories = ['Adventure', 'Detective', 'Mystery']
        for category in categories:
            Category(name=category).save()

        for i in range(20):
            author = Author.objects.order_by('?').last()
            category = Category.objects.order_by('?').first()
            Book(title=f'Title {i}', author=author, category=category).save()
Пример #13
0
def create_books(num_entries=15, overwrite=False):

    if overwrite:
        Book.objects.all().delete()
    choices = [
        'Snake Of The Land', 'Army Of The North', 'Wives Without Glory',
        'Priests Of The Prison', 'Girls And Defenders', 'Slaves And Enemies',
        'Wand Of Eternity', 'Spear Without Courage', 'Meeting At The Future',
        'Guarded By My Home', 'God Of The Ancestors', 'Owl Of Next Year',
        'Gods With Money', 'Butchers With Silver', 'Serpents And Witches',
        'Serpents And Mice', 'Murder Of Freedom', 'Love Of The World',
        'Blood At The Dark', 'Eating At Myself'
    ]
    users = list(UserProfile.objects.all())
    for _ in range(num_entries):
        b = Book(name=random.choice(choices),
                 author=fake.name(),
                 user=random.choice(users),
                 price=fake.random_int(1, 9999),
                 pages_count=fake.random_int(1, 10),
                 created_add=fake.date_time_this_month(),
                 updated_add=fake.date_time_this_month(),
                 amazon_rating=fake.random_int(1, 10))
        b.save()
Пример #14
0
    def handle(self, *args, **kwargs):
        """Procedure which generate books."""
        fake = Faker()

        for _ in range(100):
            Author(name=fake.name(), surname=fake.name(),
                   email=fake.email()).save()

        for cat in open('main/management/commands/categories.txt', 'r'):
            Category(name=cat.rstrip()).save()

        authors = list(Author.objects.all())
        categories = list(Category.objects.all())

        for _ in range(500):
            author, category = random.choice(authors), random.choice(
                categories)
            Book(title=fake.text(max_nb_chars=25).replace('.', ''),
                 author=author,
                 category=category).save()
Пример #15
0
def edit(request, id_book):
    book = Book.objects.get(pk=id_book)
    book_copy = Book(title=book.title,
                     release_year=book.release_year,
                     author=book.author,
                     genre=book.genre,
                     publisher=book.publisher,
                     synopsis=book.synopsis,
                     available_quantity=book.available_quantity)
    form = BookForm(instance=book)

    if request.method == 'POST':
        form = BookForm(data=request.POST, instance=book)

        if form.is_valid():
            form.save()
            check_delete_integrity(book_copy)
            check_create_integrity(book)
            return redirect('/book/' + str(book.id))

    return render(request, 'form.html', {
        'form': form,
        'title': 'Editar libro'
    })
Пример #16
0
def add_book(category, el):
    kwargs = get_book_dict(el)
    b = Book(**kwargs)
    cover_fname = get_book_cover(el)
    if cover_fname is not None:
        b.book_cover.name = cover_fname
    try:
        b.save()
    except:
        print("Error saving book %s" % b.title, sys.exc_info())
    else:
        b.categories.add(category)
        folders = get_or_create_folders(el)
        if folders is not None:
            for f in folders:
                b.folders.add(f)
            try:
                b.save()
            except:
                print("Error saving folders of book %s" % b.title,
                      sys.exc_info())
Пример #17
0
from csv import reader
from main.models import Book

f = open('books.csv', 'r')  #open books.csv and insert each row in the database
table = reader(f, delimiter=',')
count = 0
for row in table:
    if count == 0:
        count += 1
        continue
    isbn = row[0]
    title = row[1]
    author = row[2]
    year = int(row[3])
    book = Book(isbn, title, author, year).save()
    count += 1
f.close()
Пример #18
0
 def post(request):
     book = Book(**request.info)
     book.id = None
     book.save()
     return RestJsonResponse(book)
Пример #19
0
def index(request):
    book = Book.get()
    return {
        'book': book
    }