コード例 #1
0
def get_genres():  # Used in reset_db() to get genres using a google search
    genre_list = scrape_genres(
        'https://www.google.com/search?q=music+genres&rlz=1C5CHFA_enUS738US738&oq=music+'
        +
        'genres&aqs=chrome..69i57j69i60j0l4.1688j0j7&sourceid=chrome&ie=UTF-8')
    for genre in genre_list:
        new_genre = Genre(name=genre)
        new_genre.save(cascade=True)
コード例 #2
0
def post_create_genre(request):
    # Obtiene el nombre de la categoría
    nombre_categoria = request.POST['name']
    # Crea el objeto categoría
    categoria = Genre(name=nombre_categoria)
    # Guarda el objeto en la base de datos
    categoria.save()
    # Redirecciona a la página de categorías
    return redirect('app:view_genres')
コード例 #3
0
def create_metadata():
    """Create the table metadata.

    Application types and Genres need to be added to the database
    in order for new applications to be added.
    """
    from app.models import Genre, ApplicationType

    Genre.seed()
    ApplicationType.seed()
コード例 #4
0
ファイル: books_service.py プロジェクト: roomanidzee/Back-End
def get_books_for_user(token: str):
    user_token = session.get(token)

    api_url = "{0}/{1}/{2}".format(app.config['API_URL'], 'books', user_token)
    genre_api_url = "{0}/{1}".format(app.config['API_URL'], 'genres')

    resp = requests.get(api_url)
    data = resp.json()
    print(data)

    resp1 = requests.get(genre_api_url)
    data1 = resp1.json()

    books = []
    genres = []

    size = len(data)
    size1 = len(data1)

    for i in range(size):
        books.append(
            Book(data[i]['id'], data[i]['name'], data[i]['author'],
                 data[i]['description'], data[i]['mark']))

    for i in range(size1):
        genres.append(Genre(data1[i]['id'], data1[i]['name']))

    if len(data) == 0:
        books = None

    return books, genres
コード例 #5
0
def get_movie_genres():
    res = requests.get(
        f'https://api.themoviedb.org/3/genre/movie/list?api_key={key}')
    genres = res.json()
    for genre in genres['genres']:
        genre_seed = Genre(type=genre['name'], mdb_id=genre["id"])
        db.session.add(genre_seed)
コード例 #6
0
    def save_data(self, movie_data_list, collections_list, genre_data_list,
                  production_companies_list, production_countries_list):
        movie_objects = Movie.get_or_create(*movie_data_list)

        for n, movie in enumerate(movie_objects):
            if collections_list[n] is not None:
                collection_object = Collection.get_or_create(
                    collections_list[n])[0]
                movie.is_part_of.connect(collection_object)

        for n, genres in enumerate(genre_data_list):
            movie = movie_objects[n]
            genres_objects = Genre.get_or_create(*genres)
            [movie.genres.connect(genre) for genre in genres_objects]

        for n, production_companies in enumerate(production_companies_list):
            movie = movie_objects[n]
            production_companies_objects = ProductionCompany.get_or_create(
                *production_companies)
            [
                movie.produced_by.connect(production_company)
                for production_company in production_companies_objects
            ]

        for n, production_country in enumerate(production_countries_list):
            movie = movie_objects[n]
            production_country_objects = ProductionCountry.get_or_create(
                *production_country)
            [
                movie.produced_in.connect(production_country)
                for production_country in production_country_objects
            ]
コード例 #7
0
def edit_artist(artist_name):
    artist = Artist.objects(name=artist_name).first_or_404()
    if current_user not in artist.members:
        flash('You are not authorized to edit {}\'s information'.format(
            artist.name))
        return redirect(url_for('main.artist', artist_name=artist.name))
    form = EditArtistForm()
    form.location.choices = [(location.id,
                              location.city + ', ' + location.state)
                             for location in Location.objects()]
    form.genre.choices = [(genre.id, genre.name)
                          for genre in Genre.objects.order_by('name')]
    if form.validate_on_submit():
        artist.name = form.name.data
        artist.description = form.description.data
        artist.location = Location.objects(id=form.location.data).first()
        artist.genre = [
            Genre.objects(id=genre).first() for genre in form.genre.data
        ]
        artist.save(cascade=True)
        flash('{} Edits Complete'.format(artist.name))
        return redirect(url_for('main.artist', artist_name=artist.name))
    elif request.method == 'GET':
        form.name.data = artist.name
        form.description.data = artist.description
        form.genre.data = [genre.id for genre in artist.genre]
        form.location.data = artist.location.id
    return render_template('edit_artist.html',
                           form=form,
                           title='Edit {}'.format(artist.name))
コード例 #8
0
def create_genre(db: SQLAlchemy, data: list):
    for name in data:
        genre = Genre.query.filter_by(name=name).first()

        if genre is None:
            genre = Genre(name=name)
            db.session.add(genre)

        yield genre
コード例 #9
0
def create_genre(name):
    genre = Genre.query.filter_by(name=name).first()
    if genre is None:
        genre = Genre(name=name)
        db.session.add(genre)
        db.session.commit()
        click.echo("The genre {} has been created!".format(name))
    else:
        click.echo("The genre {} was used!".format(name))
コード例 #10
0
ファイル: api.py プロジェクト: Riffstation/flaskutilsexample
    def post(self):
        try:
            serializer = PostGenreSerializer(request=request)
            genre = Genre(serializer=serializer)
            genre.add()
            Session.commit()
            genre = Genre.objects.get(genre.id)
            app.logger.info(
                'genre with id {} has been created'.format(genre.id))
            return self.json_response(status=201, data={'id': genre.id})

        except ValidationError as e:
            Session.rollback()
            return self.json_response(status=200, data={'msg': str(e)})

        except Exception as e:
            app.logger.error(e)
            Session.rollback()
            return self.json_response(status=500)
コード例 #11
0
ファイル: crud.py プロジェクト: ShahrukhAfzal/fynd_task
def create_genre(db, genres, new_movie):
    for genre_name in genres:
        genre = db.query(Genre).filter(
            Genre.name == genre_name).first()

        if not genre:
            genre = Genre(name=genre_name)
            db.add(genre)
            db.commit()

        genre.movies.append(new_movie)
        db.commit()
コード例 #12
0
def index():
	register_form = RegistrationForm()
	login_form = LoginForm()
	if login_form.login_submit.data:
		if login_form.validate_on_submit():
			user = User.query.filter_by(email=login_form.login_email.data).first()
			if user is None or not user.check_password(login_form.login_password.data):
				flash('Invalid email or password')
				return redirect(url_for('index'))
			login_user(user, remember=login_form.remember_me.data)
			return redirect(url_for('index'))
	elif register_form.register_submit.data:
		if register_form.validate_on_submit():
			user = User(username=register_form.register_username.data, email=register_form.register_email.data)
			user.set_password(register_form.register_password.data)
			db.session.add(user)
			db.session.commit()
			flash('Thank you for registering')
			return redirect(url_for('index'))
	form = CreateProjectForm()
	if form.validate_on_submit():
		genres = form.genre.data
		genre_list = genres.split(',')
		proj = Project(title=form.title.data, synopsis=form.synopsis.data, user_id=current_user.id)
		if form.cover_pic_link.data:
			#cover_pic_filename = photos.save(form.cover_pic.data)
			#proj.cover_pic = photos.url(cover_pic_filename)
			proj.cover_pic_link = form.cover_pic_link.data
		if form.cover_pic_credit.data:
			proj.cover_pic_credit = form.cover_pic_credit.data
		db.session.add(proj)
		db.session.commit()
		for g in genre_list:
			g_query = Genre.query.filter_by(name=g).first()
			if g_query is None:
				gname = Genre(name=g)
				db.session.add(gname)
				proj.genre.append(gname)
				db.session.commit()
			else:
				proj.genre.append(g_query)
				db.session.commit()
		return redirect(url_for('project', id=proj.id, title=proj.title))
	page = request.args.get('page', 1, type=int)
	projects = Project.query.order_by(Project.date_published.desc()).filter(Project.date_published.isnot(None)).filter_by(date_quarantined=None).paginate(
		page, app.config['POSTS_PER_PAGE'], False)
	next_url = url_for('index', page=projects.next_num) \
		if projects.has_next else None
	prev_url = url_for('index', page=projects.prev_num) \
		if projects.has_prev else None
	return render_template('index.html', title='Explore', projects=projects.items, next_url=next_url, prev_url=prev_url, form=form, register_form=register_form, login_form=login_form)
コード例 #13
0
ファイル: importer.py プロジェクト: seppaleinen/worldinmovies
def import_genres():
    print("Importing genres")
    api_key = os.getenv('TMDB_API', 'test')
    url = "https://api.themoviedb.org/3/genre/movie/list?api_key={api_key}&language=en-US".format(
        api_key=api_key)
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        genres_from_json = json.loads(response.content)['genres']
        for genre in __log_progress(genres_from_json, "TMDB Genres"):
            Genre(id=genre['id'], name=genre['name']).save()
        return "Imported: %s genres" % len(genres_from_json)
    else:
        return "Request failed with status: %s, and message: %s" % (
            response.status_code, response.content)
コード例 #14
0
ファイル: routes.py プロジェクト: oconda90/anime-watching-app
def create_genre():
    '''Create a Genre Route'''
    form = GenreForm()
    if form.validate_on_submit():
        new_genre = Genre(
            name=form.name.data
        )
        db.session.add(new_genre)
        db.session.commit()

        flash('New genre created successfully.')
        return redirect(url_for('main.home'))
    
    # if form was not valid, or was not submitted yet
    return render_template('create_genre.html', form=form)
コード例 #15
0
ファイル: routes.py プロジェクト: duckling747/titanic_movies
def genre():
    genres = Genre.query.order_by(Genre.name.asc()).all()
    form = GenreForm()
    if form.validate_on_submit():
        g = Genre(name=form.name.data)
        db.session.add(g)
        db.session.commit()
        flash('Genre added to db')
        return redirect(url_for('admin.genre'))
    return render_template('admin_movie_friend.html',
                           title='admin.movie_friend',
                           collection=genres,
                           collection_name='genres',
                           header='Genre',
                           form=form)
コード例 #16
0
    def setUp(self):
        # Called before every test
        db.create_all()

        # create test data
        self.user_musician = Profile(
            profile_id='2',
            email='*****@*****.**',
            username='******',
            profile_name=None,
            profile_description='Lorem ipsum dolor sit amet, '
            'consectetur adipiscing elit. '
            'Maecenas ac metus a erat facilisis dignissim.',
            location='London',
            rating=None,
            profile_image=None,
            block='0')
        self.user_venue = Profile(profile_id='1',
                                  email='*****@*****.**',
                                  username='******',
                                  profile_name=None,
                                  profile_description=None,
                                  location=None,
                                  rating=None,
                                  profile_image=None,
                                  block='0')
        self.genre = Genre(genre_id='1', genre_name='Rock')
        self.genre_profile = Profile_Genre(profile_id='2', genre_id='1')
        self.venue = Venue(venue_id='1',
                           venue_capacity=None,
                           venue_type=None,
                           profile_id='1')
        self.musician = Musician(musician_id='1',
                                 gender='1',
                                 profile_id='2',
                                 birthdate=None,
                                 availability=None,
                                 sc_id=None)
        self.user_venue.set_password('vizon')
        self.user_musician.set_password('bryan')
        db.session.add(self.user_musician)
        db.session.add(self.genre)
        db.session.add(self.genre_profile)
        db.session.add(self.user_venue)
        db.session.add(self.venue)
        db.session.add(self.musician)
        db.session.commit()
コード例 #17
0
ファイル: populate_db.py プロジェクト: samousli/ikiru
def populate_movie_table(app):
    movie_path = '/home/avail/workspace/ikiru/resources/movie_metadata.csv'
    # os.path.join(basedir, 'resources', 'movie_metadata.csv')
    movies = []
    with open(movie_path) as f:
        rdr = csv.reader(f)
        cols = next(rdr)
        title = cols.index('movie_title')
        language = cols.index('language')
        genres = cols.index('genres')
        movie_imdb_link = cols.index('movie_imdb_link')
        title_year = cols.index('title_year')
        for r in rdr:
            movies.append(
                _Movie(
                    title=r[title].strip(),
                    language=r[language].strip(),
                    genres=[x.strip().lower() for x in r[genres].split('|')],
                    release_year=r[title_year],
                    imdb_id=r[movie_imdb_link].split('/')[4]))

        genres = {g for m in movies for g in m.genres}

        with app.app_context():

            for g in genres:
                db.session.add(Genre(name=g))
            db.session.commit()

            cats_ii = {c.name: c.id for c in Genre.query.all()}

            mappings = defaultdict(list)
            for m in movies:
                md = m._asdict()
                del md['genres']
                db_movie = Movie(**md)
                db.session.add(db_movie)
                db.session.flush([db_movie])

                for g in m.genres:
                    mappings[cats_ii[g]].append(db_movie.id)
            db.session.commit()

            for g_id, m_ids in mappings.items():
                for m_id in m_ids:
                    db.session.add(MovieGenre(movie_id=m_id, genre_id=g_id))
            db.session.commit()
コード例 #18
0
def seed_genres():

    Rock = Genre(name='Rock')
    Pop = Genre(name='Pop')
    Hip = Genre(name='Hip hop')
    Jazz = Genre(name='Jazz')
    Country = Genre(name='Country')
    Metal = Genre(name='Metal')
    World = Genre(name='World music')
    Reggae = Genre(name='Reggae')
    Punk = Genre(name='Punk')

    db.session.add(Rock)
    db.session.add(Pop)
    db.session.add(Hip)
    db.session.add(Jazz)
    db.session.add(Country)
    db.session.add(Metal)
    db.session.add(World)
    db.session.add(Reggae)
    db.session.add(Punk)

    db.session.commit()
コード例 #19
0
def create_anime():
    a1 = Studio(name='Mappa')
    g1 = Genre(name='Shounen')
    p1 = Watchlist(name='Shounens')
    s1 = Anime(
        title='Jujutsu Kaisen',
        photo_url=
        "https://static.wikia.nocookie.net/jujutsu-kaisen/images/8/88/Anime_Key_Visual_2.png/revision/latest?cb=20201212034001",
        date=date(2020, 9, 19),
        studio=a1,
        genres=g1,
        watchlists=p1)
    db.session.add(s1)

    a2 = Studio(name='Bones')
    s2 = Anime(title='My Hero Academia', studio=a2)
    db.session.add(s2)
    db.session.commit()
コード例 #20
0
    def insert(self, data):
        session = self.__thread_safe_session_factory()
        i_game = 1
        i_genres = 1

        for title, infos in data.items():

            if len(title) > 128:
                continue

            # Adding game
            session.add(
                Game(id=i_game,
                     title=title,
                     publication_year=infos["publication_year"],
                     min_players=infos["min_players"],
                     max_players=infos["max_players"],
                     min_playtime=infos["min_playtime"],
                     image=infos["images"]["original"]))

            # Adding note
            session.add(
                Note(note=round(infos["average_rating"]),
                     message=self.__default_message,
                     user_id=1,
                     game_id=i_game))

            for genre in infos["type"]:
                # Adding genre
                if genre not in self.__genres_dict:
                    self.__genres_dict[genre] = i_genres
                    session.add(Genre(id=i_genres, name=genre))
                    i_genres += 1

                # Adding classification
                session.add(
                    Classification(game_id=i_game,
                                   genre_id=self.__genres_dict[genre]))

            i_game += 1

        session.commit()
        self.__thread_safe_session_factory.remove()
コード例 #21
0
ファイル: views.py プロジェクト: MaistrenkoAnton/project
def AddFolder(request, pk):
    form = dict()
    form['form'] = AddFolderForm()
    form['note_name'] = Note.objects.all()
    form['directory'] = Genre.objects.get(id=pk)
    form['users'] = User.objects.all()
    form['tree'] = Genre.objects.filter(parent_id=pk)

    if request.POST:
        new_folder = Genre()
        new_folder.name = request.POST['name']
        new_folder.user = User.objects.get(username=auth.get_user(request).username)
        new_folder.parent_id = pk
        new_folder.save()

    return render(request, 'app/addfolder.html', form)
コード例 #22
0
    def _sync_book_with_goodreads(self, book):
        book_id = self._get_id_for_isbn(book.isbn13)

        if book_id is None:
            return

        book_data = self._get_book_data(book_id)

        if book_data is None:
            return

        decoded_book_data = self._parse_XML(book_data)

        # make sure all genres exit in our database bevor adding them to the book
        genres = []
        genre_title_blacklist = ['book', 'read', 'shelf', 'own']
        for genre_title in decoded_book_data['genres']:
            is_blacklisted = False
            for blacklisted_title in genre_title_blacklist:
                is_blacklisted = is_blacklisted or (blacklisted_title in genre_title.lower())
            if not is_blacklisted:
                genre = Genre.query.filter_by(title=genre_title).first()
                if genre is None:
                    genre = Genre(genre_title)
                    db.session.add(genre)
                    db.session.commit()
                genres.append(genre)
        
        book.title = decoded_book_data['title']
        book.author = decoded_book_data['author']
        book.rating = decoded_book_data['rating']
        book.description = decoded_book_data['description']
        if (book.cover_image_url is None) or ('goodreads' in book.cover_image_url):
            book.cover_image_url = decoded_book_data['cover_image_url']
        book.goodreads_url = decoded_book_data['goodreads_url']
        book.goodreads_author_url = decoded_book_data['goodreads_author_url']

        book.genres = genres
        
        db.session.commit()
コード例 #23
0
    def post(self):
        data = parser.parse_args()
        required = ["name", "url"]
        if any(val is None for key, val in data.items() if key in required):
            api.abort(400,
                      "Values of required keys are missing",
                      required=required)
            #return {"error": "name and url are required"}, 400

        data = clean_data(data)

        try:
            genre = Genre(**data)
            db.session.add(genre)
            db.session.commit()
        except:
            api.abort(409, "Genre already exists")
            #return {"error": f"Genre {data['name']} already exists"}, 409
        return api.marshal(genre,
                           serializer,
                           skip_none=True,
                           mask="id,name,url"), 201
コード例 #24
0
    def on_submit_form(form):
        survey = Survey.get_by_id(form.survey_id.data)
        if survey is None:
            flash("Sondaggio non trovato")
            return False

        genres_liked = form.genres_liked.data

        user = User.get_by_id(current_user.id)
        for genre_id in genres_liked:
            genre = Genre.get_by_id(genre_id)
            if genre is None:
                continue

            user.genres_liked.append(genre)

        survey.users_done.append(user)
        survey.save()

        user.save()
        flash(
            "Sondaggio completato correttamente. Grazie per la tua attenzione!"
        )
        return True
コード例 #25
0
def create_artist():
    form = CreateArtistForm()
    form.location.choices = [(location.id,
                              location.city + ', ' + location.state)
                             for location in Location.objects()]
    form.genre.choices = [(genre.id, genre.name)
                          for genre in Genre.objects.order_by('name')]
    if form.validate_on_submit():
        user = User.objects(username=current_user.username).first()
        location = Location.objects(id=form.location.data).first()
        genres = []
        for genre_id in form.genre.data:
            genres.append(Genre.objects(id=genre_id).first())
        artist = Artist(name=form.name.data,
                        description=form.description.data,
                        location=location,
                        genre=genres)
        artist.save(cascade=True)
        add_member(user, artist)
        flash('Artist {} was created'.format(artist.name))
        return redirect(url_for('main.artist', artist_name=artist.name))
    return render_template('create_artist.html',
                           form=form,
                           title='Create Artist')
コード例 #26
0
ファイル: utils.py プロジェクト: fossabot/ManaZeak
def populateDB():
    if FileType.objects.all().count() == 0:
        print("Created files types")
        FileType(name="mp3").save()
        FileType(name="ogg").save()
        FileType(name="flac").save()
        FileType(name="wav").save()
    if Artist.objects.all().count() == 0:
        print("Created default artist")
        Artist(name=None).save()
    if Album.objects.all().count() == 0:
        print("Created default album")
        Album(title=None).save()
    if Genre.objects.all().count() == 0:
        print("Created default genre")
        Genre(name=None).save()
    if Permissions.objects.all().count() == 0:
        print("Creating default permissions")
        Permissions(name="Login", code="LOGI").save()
        Permissions(name="Music listening", code="PLAY").save()
        Permissions(name="Playlist management", code="PLST").save()
        Permissions(name="Download", code="DOWN").save()
        Permissions(name="Wish creation", code="WISH").save()
        Permissions(name="Tag submission", code="TAGS").save()
        Permissions(name="Upload file", code='UPLD').save()
        Permissions(name="Sponsor right", code='SPON').save()
        Permissions(name="Stats access", code='STAT').save()
        Permissions(name="Child stats access", code="STCH").save()
        Permissions(name="Family stat access", code="STFA").save()
        Permissions(name="Wish review", code="WISR").save()
        Permissions(name="Access to library stats", code="STAL").save()
        Permissions(name="Change genre description", code="DESC").save()
        Permissions(name="Tag edition", code="TAGE").save()
        Permissions(name="Upload aproval", code="UPAP").save()
        Permissions(name="All stats", code="STAA").save()
        Permissions(name="Access to adminView", code="ADMV").save()
        Permissions(name="Edit user group", code="GRPE").save()
        Permissions(name="Access to whole family tree", code="FTAL").save()
        Permissions(name="Library management", code="LIBR").save()
        Permissions(name="Grant admin privileges", code="GAPR").save()
        Permissions(name="Coin gift", code="COIN").save()

    if TransactionType.objects.all().count() == 0:
        print("Creating default transaction types")
        TransactionType(name="Listening",
                        code="PLAY",
                        coinGain=100,
                        coinLoss=0,
                        streakGain=0,
                        streakLoss=0,
                        bubbles=False).save()
        TransactionType(name="Edit tag",
                        code="TAGE",
                        coinGain=100,
                        coinLoss=300,
                        streakGain=2,
                        streakLoss=10,
                        bubbles=True).save()
        TransactionType(name="Upload",
                        code="UPLD",
                        coinGain=300,
                        coinLoss=100,
                        streakGain=5,
                        streakLoss=6,
                        bubbles=True).save()
        TransactionType(name="Wish",
                        code="WISH",
                        coinGain=50,
                        coinLoss=20,
                        streakGain=1,
                        streakLoss=10,
                        bubbles=True).save()
        TransactionType(name="Gift",
                        code="GIFT",
                        coinGain=1,
                        coinLoss=0,
                        streakGain=0,
                        streakLoss=0,
                        bubbles=False).save()
        TransactionType(name="Bubble",
                        code="BUBL",
                        coinGain=0,
                        coinLoss=0,
                        streakGain=0,
                        streakLoss=0,
                        bubbles=False).save()

    if Groups.objects.all().count() == 0:
        Groups(name="Banned", rank=0).save()
        print("Creating the defaults groups")
        Groups(name="Naab", rank=1).save()
        Groups(name="User", rank=2).save()
        Groups(name="Moderator", rank=3).save()
        Groups(name="Admin", rank=4).save()
        Groups(name="Root", rank=5).save()
        for group in Groups.objects.all():
            fillDefaultPermission(group)

    print("zobare")
    # Creating and updating achivements
    setCronJobs()
    refreshAchievements()
コード例 #27
0
sample.drop(columns='genre', inplace=True)
albums = pd.read_csv('albums.csv')

joined = pd.merge(sample, albums, on='album_id', how='left')
removed = joined[~joined['remove'].isna()]
joined = joined[joined['remove'].isna()]

# Check that the database contains all 8 expected genres
genres = Genre.query.all()
genre_names = [g.name for g in genres]
all_genres = [
    'country', 'electronic', 'folk', 'indie', 'metal', 'pop', 'rap', 'rock'
]
for g in all_genres:
    if g not in genre_names:
        db.session.add(Genre(name=g))

# Create mapping of genre name to id to assign albums a proper genre id
genres = Genre.query.all()
genre_map = {g.name: g.genre_id for g in genres}

for album in joined.itertuples():
    db.session.merge(
        Album(album_id=album.album_id,
              genre_id=genre_map.get(album.genre),
              prediction_id=list(genre_map.values())[random.randint(0, 7)],
              confidence=random.random() * 0.4,
              name=album.album[:60],
              artist=album.artist))

db.session.commit()
コード例 #28
0
def upload_track(artist_name):
    artist = Artist.objects(name=artist_name).first_or_404()
    if current_user not in artist.members:
        flash('You are not authorized to upload tracks for {}'.format(
            artist.name))
        return redirect(url_for('main.artist', artist_name=artist.name))
    form = UploadTrackForm()
    form.genre.choices = [(genre.id, genre.name)
                          for genre in Genre.objects.order_by('name')]
    if form.validate_on_submit():
        file = form.track.data
        if not allowed_file(file.filename):
            flash('Only music files are allowed')
            return render_template('upload_track.html',
                                   form=form,
                                   artist=artist,
                                   title='Upload Track')
        file.filename = secure_filename(file.filename)
        s3_filepath, cloudfront_filepath = upload_file_to_s3(
            file, current_app.config['S3_BUCKET'])
        track_exists = Track.objects(s3_filepath=s3_filepath,
                                     cloudfront_filepath=cloudfront_filepath
                                     ).first() is not None  # 1 if track exists
        if s3_filepath is not None and cloudfront_filepath is not None and not track_exists:
            new_track = Track(track_name=form.track_name.data,
                              artist=artist,
                              duration=0,
                              genre=[
                                  Genre.objects(id=genre).first()
                                  for genre in form.genre.data
                              ],
                              s3_filepath=s3_filepath,
                              cloudfront_filepath=cloudfront_filepath)
            new_track.save(cascade=True)  # Saves the track in the mongoDB

            # filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], file.filename)
            # new_track = Track(track_name=form.track_name.data, artist=artist, duration=0,
            #                   genre=[Genre.objects(id=genre).first() for genre in form.genre.data], filepath=filepath)
            # new_track.save(cascade=True)  # Saves the track in the mongoDB
            # file.save(filepath)
            artist.tracks.append(new_track)
            artist.save(cascade=True)  # Save artist with new track
            flash('Track successfully uploaded')
            return redirect(url_for('main.artist', artist_name=artist_name))
        else:
            if track_exists:
                flash('Track already exists!')
                return render_template('upload_track.html',
                                       form=form,
                                       artist=artist,
                                       title='Upload Track')
            else:
                flash('Error uploading file')
                return render_template('upload_track.html',
                                       form=form,
                                       artist=artist,
                                       title='Upload Track')
    return render_template('upload_track.html',
                           form=form,
                           artist=artist,
                           title='Upload Track')
コード例 #29
0
def updateDBInfo(response, track):
    tags = Information()
    # Changing tags in the database
    if 'TITLE' in response and response['TITLE'] != '':
        tags.trackTitle = strip_tags(response['TITLE']).lstrip().rstrip()
        track.title = tags.trackTitle

    if 'ARTISTS' in response and response['ARTISTS'] != '':
        tags.trackArtist = strip_tags(
            response['ARTISTS']).lstrip().rstrip().split(',')
        artists = []
        for artist in tags.trackArtist:
            if Artist.objects.filter(name=artist).count() == 0:
                newArtist = Artist()
                newArtist.name = artist
                newArtist.save()
            artists.append(Artist.objects.get(name=artist))
        track.artist.clear()
        for artist in artists:
            track.artist.add(artist)

    if 'PERFORMER' in response and response['PERFORMER'] != '':
        tags.trackPerformer = strip_tags(
            response['PERFORMER']).lstrip().rstrip()
        track.performer = tags.trackPerformer

    if 'COMPOSER' in response and response['COMPOSER'] != '':
        tags.trackComposer = strip_tags(response['COMPOSER']).lstrip().rstrip()
        track.composer = tags.trackComposer

    if 'YEAR' in response and response['YEAR'] != '':
        tags.trackYear = checkIntValueError(response['YEAR'])
        track.year = tags.trackYear

    if 'TRACK_NUMBER' in response and response['TRACK_NUMBER'] != '':
        tags.trackNumber = checkIntValueError(response['TRACK_NUMBER'])
        track.number = tags.trackNumber

    if 'BPM' in response and response['BPM'] != '':
        track.bpm = checkIntValueError(response['BPM'])

    if 'LYRICS' in response and response['LYRICS'] != '':
        tags.lyrics = strip_tags(response['LYRICS']).lstrip().rstrip()
        track.lyrics = tags.lyrics

    if 'COMMENT' in response and response['COMMENT'] != '':
        tags.comment = strip_tags(response['COMMENT']).lstrip().rstrip()
        track.comment = tags.comment

    if 'GENRE' in response and response['GENRE'] != '':
        tags.trackGenre = strip_tags(response['GENRE']).lstrip().rstrip()
        if Genre.objects.filter(name=tags.trackGenre).count() == 0:
            genre = Genre()
            genre.name = tags.trackGenre
            genre.save()
        genre = Genre.objects.get(name=tags.trackGenre)
        track.genre = genre

    if 'COVER' in response:
        md5Name = hashlib.md5()
        if str(response['COVER'].split(",")[0]) == "image/png":
            extension = "png"
        else:
            extension = "jpg"
        md5Name.update(base64.b64decode(str(response['COVER'].split(",")[1])))
        # Check if the folder exists
        filePath = "/ManaZeak/static/img/covers/"
        if not os.path.isdir(filePath):
            os.mkdir(filePath)  # Create the folder
        filePath += +md5Name.hexdigest() + extension

        # if the filePath is the same, then the md5 hash of the image is
        # the same, therefore the images are the same, therefore do nothing
        if not os.path.isfile(filePath):
            with open(filePath, 'wb+') as destination:
                # Split the header with MIME type
                tags.cover = base64.b64decode(
                    str(response['COVER'].split(",")[1]))
                destination.write(tags.cover)
                track.coverLocation = md5Name.hexdigest() + extension

    if 'ALBUM_TITLE' in response and 'ALBUM_ARTISTS' in response and response['ALBUM_TITLE'] != '' \
            and response['ALBUM_ARTISTS'] != '':
        tags.albumTitle = strip_tags(response['ALBUM_TITLE']).lstrip().rstrip()
        tags.albumArtist = strip_tags(
            response['ALBUM_ARTISTS']).lstrip().rstrip().split(',')
        if Album.objects.filter(title=tags.albumTitle).count() == 0:
            album = Album()
            album.title = tags.albumTitle
            album.save()
        album = Album.objects.get(title=tags.albumTitle)
        album.artist.clear()
        for artist in tags.albumArtist:
            if Artist.objects.filter(name=artist).count() == 0:
                newArtist = Artist()
                newArtist.name = artist
                newArtist.save()
            album.artist.add(Artist.objects.get(name=artist))

        if 'ALBUM_TOTAL_DISC' in response and response[
                'ALBUM_TOTAL_DISC'] != '':
            tags.albumTotalDisc = checkIntValueError(
                response['ALBUM_TOTAL_DISC'])
            album.totalDisc = tags.albumTotalDisc

        if 'DISC_NUMBER' in response and response['DISC_NUMBER'] != '':
            tags.albumDiscNumber = checkIntValueError(response['DISC_NUMBER'])
            track.discNumber = tags.albumDiscNumber

        if 'ALBUM_TOTAL_TRACK' in response and response[
                'ALBUM_TOTAL_TRACK'] != '':
            tags.albumTotalTrack = checkIntValueError(
                response['ALBUM_TOTAL_TRACK'])
            album.totalTrack = tags.albumTotalTrack
        album.save()
        track.album = album
    track.save()
    return tags
コード例 #30
0
from app import db
from app.models import User, Game, Genre

db.create_all()

action = Genre('Action')
action.description = 'Fast paced and invigorating'
db.session.add(action)

adventure = Genre('Adventure')
adventure.description = 'Find your way, or die.'
db.session.add(adventure)

arcade = Genre('Arcade')
arcade.description = 'Oldschool games for casual gamers'
db.session.add(arcade)

fighting = Genre('Fighting')
fighting.description = 'Hand-to-hand combat.'
db.session.add(fighting)

fps = Genre('FPS')
fps.description = 'First-person shooter'
db.session.add(fps)

puzzle = Genre('Puzzle')
puzzle.description = 'Mind-boggling games for the braniacs'
db.session.add(puzzle)

sim = Genre('Simulation')
sim.description = 'From flight to city, this is real life.'
コード例 #31
0
def seed_restaurants():
    genre1 = Genre(
        name="Cakes",
        img_src=
        "https://icons-for-free.com/iconfiles/png/512/flat+version+svg+slice+of+cake-1319964486387545161.png"
    )
    genre2 = Genre(name="Cupcakes",
                   img_src="https://img.icons8.com/plasticine/2x/cupcake.png")
    genre3 = Genre(
        name="Pies",
        img_src="https://iconarchive.com/download/i99743/sonya/swarm/Pie.ico")
    genre4 = Genre(
        name="Chocolate",
        img_src=
        "https://icons-for-free.com/iconfiles/png/512/Chocolate-1320568040315110190.png"
    )
    genre5 = Genre(
        name="Candy",
        img_src=
        "https://icons-for-free.com/iconfiles/png/512/flat+version+svg+candy-1319964483174784523.png"
    )
    genre6 = Genre(
        name="Ice Cream",
        img_src=
        "https://icons-for-free.com/iconfiles/png/512/flat+version+svg+ice+cream-1319964483943937255.png"
    )
    genre7 = Genre(
        name="Donuts",
        img_src=
        "https://freepngimg.com/download/grocery/55063-3-pink-donut-photos-download-hd-png.png"
    )
    genre8 = Genre(
        name="Pastries",
        img_src=
        "https://iconarchive.com/download/i107463/google/noto-emoji-food-drink/32372-croissant.ico"
    )
    genre9 = Genre(
        name="Gelato",
        img_src=
        "https://icons-for-free.com/iconfiles/png/512/linecolor+version+svg+ice+cream-1319964494028526965.png"
    )
    genre10 = Genre(
        name="Vegan",
        img_src="https://img.icons8.com/plasticine/2x/vegan-symbol.png")
    genre11 = Genre(
        name="Cookies",
        img_src=
        "https://icons-for-free.com/iconfiles/png/512/cookie-1319971784454690183.png"
    )

    restaurant1 = Restaurant(
        name="Nothing Bundt Cakes",
        description=
        "Bakery chain with bundt cakes ranging from bite-sized to tiered, plus platters, candles & cards.",
        address=" 2785 Bee Cave Rd",
        city="Austin",
        state="TX",
        zip_code="78746",
        lat=30.274082967865112,
        lng=-97.78770001461015,
        hours="9:00AM - 6:00PM",
        price="$$",
        rating=4.8,
    )
    restaurant2 = Restaurant(
        name="Paper Route Bakery",
        description=
        "Small batch artisanal bakery homegrown here in Austin! Homemade delicacies, organic & local ingredients.",
        address="1835 W Alambama St",
        city="Austin",
        state="TX",
        zip_code="78702",
        lat=30.261396556115916,
        lng=-97.73375683068825,
        hours="8:00AM - 4:00PM",
        price="$",
        rating=4.9,
    )
    restaurant3 = Restaurant(
        name="Sugar Mama's Bakeshop",
        description=
        "Well-known bakery offering cupcakes, cookies, bars & mini-pies in a vintage space with a few seats.",
        address="1905 S 1st St",
        city="Austin",
        state="TX",
        zip_code="78704",
        lat=30.24722791833769,
        lng=-97.75662594603243,
        hours="10:00AM - 7:00PM",
        price="$",
        rating=4.3,
    )
    restaurant4 = Restaurant(
        name="Capital City Bakery",
        description=
        "Local bakery preparing all-vegan treats including cupcakes, brownies & special-occasion cakes.",
        address="2211 E Cesar Chavez St",
        city="Austin",
        state="TX",
        zip_code="78702",
        lat=30.25627587968311,
        lng=-97.72009946137655,
        hours="10:00AM - 6:00PM",
        price="$",
        rating=4.7,
    )
    restaurant5 = Restaurant(
        name="Word of Mouth Bakery",
        description=
        "Word of Mouth Bakery is an Austin Bakery with a cafe menu that features breakfast sandwiches, pastries, muffins, cookies, cake by the slice, cupcakes, salads, sandwiches, and a catering to go menu. Let us do the cooking!",
        address="917 W 12th St",
        city="Austin",
        state="TX",
        zip_code="78703",
        lat=30.27756356269626,
        lng=-97.7507719,
        hours="10:00AM - 4:00PM",
        price="$$",
        rating=4.7,
    )
    restaurant6 = Restaurant(
        name="Hayleycakes and Cookies",
        description=
        "Petite stop-in for sweet treats, from inventive cupcakes to cookies, plus special-occasion cakes.",
        address="1700 S Lamar Blvd",
        city="Austin",
        state="TX",
        zip_code="78704",
        lat=30.251858996097788,
        lng=-97.76640427672069,
        hours="7:00AM - 7:00PM",
        price="$$",
        rating=4.3,
    )
    restaurant7 = Restaurant(
        name="Manolis Ice Cream Pastries & Cakes",
        description=
        "Housemade ice cream, popsicles & pastries are doled out at this busy food truck with outdoor tables",
        address="603 W Live Oak St",
        city="Austin",
        state="TX",
        zip_code="78704",
        lat=30.245213622657094,
        lng=-97.75797916931172,
        hours="2:00PM - 11:00PM",
        price="$",
        rating=4.9,
    )
    restaurant8 = Restaurant(
        name="Whole Foods",
        description=
        "We believe in the best, from our kitchens to your table. From our cult-favorite Berry Chantilly Cake to wholesome Seeduction Bread, our baked goods are made with unbleached, unbromated flour and cage-free or better eggs — and we don’t use hydrogenated fats or high-fructose corn syrup.",
        address="525 N Lamar Blvd",
        city="Austin",
        state="TX",
        zip_code="78703",
        lat=30.270744292416065,
        lng=-97.75320356423829,
        hours="7:00AM - 9:00PM",
        price="$$$",
        rating=4.5,
    )
    restaurant9 = Restaurant(
        name="Polkadots Cupcake Factory",
        description=
        "Cheery bakery crafting cupcakes in creative flavors, plus made-to-order cakes & hand-iced cookies.",
        address="2826 Rio Grande St",
        city="Austin",
        state="TX",
        zip_code="78705",
        lat=30.296683931389214,
        lng=-97.74425971534413,
        hours="7:00AM - 9:00PM",
        price="$",
        rating=4.3,
    )
    restaurant10 = Restaurant(
        name="Hey Cupcake!",
        description=
        "Cupcakes are the draw at this whimsical shop operating out of a parked trailer with outdoor seating.",
        address="1511 S Congress Ave",
        city="Austin",
        state="TX",
        zip_code="78704",
        lat=30.24935067782933,
        lng=-97.74942885396759,
        hours="11:00AM - 9:00PM",
        price="$",
        rating=4.1,
    )
    restaurant11 = Restaurant(
        name="Zucchini Kill Bakery",
        description=
        "Punk rock, female-led bakery serving vegan sweet & savory goods that are also soy & gluten-free.",
        address="701 E 53rd S",
        city="Austin",
        state="TX",
        zip_code="78751",
        lat=30.316314014490814,
        lng=-97.71660398465573,
        hours="3:00PM - 8:00PM",
        price="$$",
        rating=4.8,
    )
    restaurant12 = Restaurant(
        name="Tiny Pies",
        description=
        "Handmade by Scratch Daily Using Traditional Baking Methods and Natural Ingredients. Made fresh Daily!",
        address="2032 S Lamar Blvd",
        city="Austin",
        state="TX",
        zip_code="78704",
        lat=30.250212425241358,
        lng=-97.7687649,
        hours="8:00AM - 8:00PM",
        price="$$",
        rating=4.5,
    )
    # restaurant13 = Restaurant(name="Quack's 43rd Street Bakery",
    #                     description="Quack’s line of bakery products grew out of a need to provide freshly baked goods for our customers. All the baked items sold here are made here from scratch. We use high quality, natural ingredients. We do not use frozen dough or mixes. Our bakery products contain no preservatives, high fructose corn syrups or additives. We provide service to many wholesale accounts that elect to serve their customers better quality baked goods in lieu of more commonly available, less expensive commercial products",
    #                     address="411 E 43rd St",
    #                     city="Austin",
    #                     state="TX",
    #                     zip_code="78751",
    #                     lat=30.30534896953304,
    #                     lng=-97.72654048465586,
    #                     hours="7:00AM - 9:00PM",
    #                     price="$",
    #                     rating=4.6,
    #                     )
    restaurant13 = Restaurant(
        name="The Cake and Spoon",
        description=
        "The Cake and Spoon is a wholesale and special order bakery concentrating on English, American, and European desserts and pastries.",
        address="3008 Gonzales St",
        city="Austin",
        state="TX",
        zip_code="78702",
        lat=30.250212425241358,
        lng=-97.7687649,
        hours="8:00AM - 1:00PM",
        price="$",
        rating=4.6,
    )
    restaurant14 = Restaurant(
        name="Upper Crust Bakery",
        description=
        "Well-known bakery with a cozy ambiance selling made-from-scratch pastries, bread & lunch fare.",
        address="4508 Burnet Rd",
        city="Austin",
        state="TX",
        zip_code="78756",
        lat=30.31652058929442,
        lng=-97.7415639,
        hours="7:00AM - 3:00PM",
        price="$",
        rating=4.6,
    )
    # restaurant16 = Restaurant(name="Big Top",
    #                     description="Colorful, circus-themed sweets store featuring old-school confections & a soda fountain.",
    #                     address="1706 S Congress Ave",
    #                     city="Austin",
    #                     state="TX",
    #                     zip_code="78704",
    #                     lat=30.247915810809495,
    #                     lng=-97.7508139232793,
    #                     hours="11:00AM - 6:00PM",
    #                     price="$$",
    #                     rating=4.6,
    #                     )
    restaurant15 = Restaurant(
        name="Edis Chocolates",
        description=
        "Locally owned shop creating specialty chocolates, cakes, cookies, pastries & other confections.",
        address="3808 Spicewood Springs Rd",
        city="Austin",
        state="TX",
        zip_code="78759",
        lat=30.365796276705574,
        lng=-97.74900098465586,
        hours="10:00AM - 5:00PM",
        price="$$",
        rating=4.8,
    )
    # restaurant18 = Restaurant(name="Delysia Chocolatier",
    #                     description="Our chocolates are handcrafted in Austin, Texas at our Culinary Center & Chocolate Boutique. Many include unique, local ingredients that are not available anywhere else. Relish in our passion for creating the finest quality and most unique chocolates available.",
    #                     address="2000 Windy Terrace",
    #                     city="Austin",
    #                     state="TX",
    #                     zip_code="78726",
    #                     lat=30.461966325891236,
    #                     lng=-97.83330320740897,
    #                     hours="12:00PM - 4:00PM",
    #                     price="$",
    #                     rating=4.7,
    #                     )
    # restaurant19 = Restaurant(name="Yummi Joy",
    #                     description="Craft sodas, mix-and-match candy, & coffee, plus vegan ice cream in playful, cartoon-ish surrounds.",
    #                     address="409 W 2nd St",
    #                     city="Austin",
    #                     state="TX",
    #                     zip_code="78701",
    #                     lat=30.265914420466785,
    #                     lng=-97.74820453068827,
    #                     hours="11:00AM - 7:00PM",
    #                     price="$",
    #                     rating=4.6,
    #                     )
    restaurant16 = Restaurant(
        name="Madhu Chocolate",
        description=
        "Austin made small batch chocolate bars with an emphasis on unique Indian flavors.",
        address="6814 Northeast Dr",
        city="Austin",
        state="TX",
        zip_code="78723",
        lat=30.31936931469751,
        lng=-97.6804175,
        hours="10:00AM - 2:00PM",
        price="$",
        rating=5.0,
    )
    restaurant17 = Restaurant(
        name="Lammes Candies",
        description=
        "Austin's hometown candy store and home of the world-famous Texas Chewie® Pecan Praline. ",
        address="2927 W Anderson Ln",
        city="Austin",
        state="TX",
        zip_code="78757",
        lat=30.359302551025714,
        lng=-97.73851866983784,
        hours="11:00AM - 5:30PM",
        price="$",
        rating=4.6,
    )
    restaurant18 = Restaurant(
        name="IT'SUGAR",
        description=
        "IT'SUGAR is a trendy candy store specializing in innovative sweets, fun novelty gifts, and giant candy.",
        address="11621 Rock Rose Ave",
        city="Austin",
        state="TX",
        zip_code="78758",
        lat=30.40295485903219,
        lng=-97.72194801177815,
        hours="12:00PM - 8:00PM",
        price="$",
        rating=4.2,
    )
    restaurant19 = Restaurant(
        name="See's Candies",
        description=
        "Candies & chocolates are sold by the piece or box at this old-school chain, in business since 1921.",
        address="10710 Research Blvd",
        city="Austin",
        state="TX",
        zip_code="78759",
        lat=30.399847844610722,
        lng=-97.74799219259104,
        hours="9:00AM - 7:30PM",
        price="$",
        rating=4.9,
    )
    # restaurant24 = Restaurant(name="Amy's Ice Creams",
    #                     description="Local chain serving inventive ice creams, milkshakes, ices & frozen yogurts with clever fixings.",
    #                     address="1301 S Congress Ave",
    #                     city="Austin",
    #                     state="TX",
    #                     zip_code="78704",
    #                     lat=30.25218564971291,
    #                     lng=-97.74876643862343,
    #                     hours="11:00AM - 11:00PM",
    #                     price="$",
    #                     rating=4.5,
    #                     )
    restaurant20 = Restaurant(
        name="Jeni's Splendid Ice Creams",
        description=
        "Chain scooping creative flavors of ice cream & frozen yogurt made from local ingredients.",
        address="1208 S Congress Ave",
        city="Austin",
        state="TX",
        zip_code="78704",
        lat=30.252835459387956,
        lng=-97.74918206137656,
        hours="12:00PM - 10:00PM",
        price="$$",
        rating=4.6,
    )
    restaurant21 = Restaurant(
        name="Dolce Neve Gelato",
        description=
        "Busy gelato shop whipping up various inventive flavors of ice cream in a pint-sized setting.",
        address="1713 S 1st St",
        city="Austin",
        state="TX",
        zip_code="78704",
        lat=30.248419896043455,
        lng=-97.75562374603243,
        hours="12:00PM - 9:00PM",
        price="$",
        rating=4.7,
    )
    restaurant22 = Restaurant(
        name="Lick Honest Ice Creams",
        description=
        "This hip ice creamery churns out offbeat flavors made from local, natural & sustainable ingredients.",
        address="1100 S Lamar Blvd",
        city="Austin",
        state="TX",
        zip_code="78704",
        lat=30.256305291156544,
        lng=-97.76265934603252,
        hours="12:00PM - 10:00PM",
        price="$$",
        rating=4.6,
    )
    restaurant23 = Restaurant(
        name="NadaMoo! Scoop Shop",
        description=
        "Festive counter-serve featuring homemade, dairy-free ice cream in traditional & seasonal flavors.",
        address="1701 S Lamar Blvd",
        city="Austin",
        state="TX",
        zip_code="78704",
        lat=30.25144088571262,
        lng=-97.76563339206633,
        hours="2:00PM - 10:00PM",
        price="$",
        rating=4.6,
    )
    restaurant24 = Restaurant(
        name="Sweet Ritual",
        description=
        "Colorful ice cream parlor serving gluten-free & vegan scoops in cups, cones, shakes & sundaes.",
        address="4631 Airport Blvd",
        city="Austin",
        state="TX",
        zip_code="78751",
        lat=30.30738290616657,
        lng=-97.71527361534415,
        hours="12:00PM - 10:00PM",
        price="$",
        rating=4.7,
    )
    restaurant25 = Restaurant(
        name="Voodoo Doughnut",
        description=
        "This counter-serve bakeshop serves creative donuts in colorful, quirky environs.",
        address="212 E 6th St",
        city="Austin",
        state="TX",
        zip_code="78701",
        lat=30.268674458003204,
        lng=-97.74110379206493,
        hours="8:00AM - 12:00AM",
        price="$",
        rating=4.4,
    )
    # restaurant31 = Restaurant(name="Little Lucy's",
    #                     description="Colorful, late-night food truck making mini-donuts with creative flavors, toppings & dipping sauces.",
    #                     address="75 1/2 Rainey St",
    #                     city="Austin",
    #                     state="TX",
    #                     zip_code="78701",
    #                     lat=30.25933696827229,
    #                     lng=-97.73863651534413,
    #                     hours="5:00PM - 2:00AM",
    #                     price="$",
    #                     rating=4.4,
    #                     )
    restaurant26 = Restaurant(
        name="Gourdough's Big. Fat. Donuts.",
        description=
        "Gourdough's Big. Fat. Donuts. is housed in a vintage Airstream Trailer located on South Lamar and doles out the most delectable and crazy donut concoctions your mind and taste buds will allow.",
        address="1503 S 1st St",
        city="Austin",
        state="TX",
        zip_code="78704",
        lat=30.25056331384392,
        lng=-97.75472767114883,
        hours="10:00AM - 12:00AM",
        price="$",
        rating=4.7,
    )
    restaurant27 = Restaurant(
        name="Julie Myrtille Bakery",
        description=
        "Authentic French bakery and fine pastry in Austin founded by French pastry chef Julie Myrtille. Bake the world a better place.",
        address="1023 Springdale Rd",
        city="Austin",
        state="TX",
        zip_code="78721",
        lat=30.26853112905222,
        lng=-97.69396151534413,
        hours="8:30AM - 2:00PM",
        price="$$",
        rating=4.7,
    )
    restaurant28 = Restaurant(
        name="Milky Way Shakes",
        description=
        "Milky Way Shakes, a vegan milkshake trailer located in Austin, TX.",
        address="2324 E Cesar Chavez St",
        city="Austin",
        state="TX",
        zip_code="78702",
        lat=30.255831594732026,
        lng=-97.71826961534413,
        hours="5:00PM - 10:00PM",
        price="$",
        rating=4.9,
    )
    restaurant29 = Restaurant(
        name="Tiff's Treats",
        description=
        "Fresh-baked cookies for pre-order & pickup, or delivery, with a limited selection for walk-ins.",
        address="1700 E Oltorf St",
        city="Austin",
        state="TX",
        zip_code="78741",
        lat=30.234797164809567,
        lng=-97.73945371534413,
        hours="9:00AM - 10:00PM",
        price="$",
        rating=4.0,
    )
    # restaurant36 = Restaurant(name="Tinys Milk & Cookies",
    #                     description="Milk & Cookies is a walk up coffee shop serving homemade ice cream, pastries, and of course, our cookie.",
    #                     address="1515 W 35th St",
    #                     city="Austin",
    #                     state="TX",
    #                     zip_code="78703",
    #                     lat=30.307501456412382,
    #                     lng=-97.7503918,
    #                     hours="7:00AM - 9:00PM",
    #                     price="$",
    #                     rating=4.7,
    #                     )
    restaurant30 = Restaurant(
        name="Insomnia Cookies",
        description=
        "Bakery chain known for late-night deliveries, with some locations selling ice cream.",
        address="2323 San Antonio St",
        city="Austin",
        state="TX",
        zip_code="78705",
        lat=30.288449263565315,
        lng=-97.7425249,
        hours="11:00AM - 12:00AM",
        price="$$",
        rating=3.7,
    )
    restaurant31 = Restaurant(
        name="Crumbl Cookies",
        description=
        "Each week, our menu rotates to give you 4 different specialty flavors to taste and enjoy. Don’t worry, our famous milk chocolate chip and chilled sugar cookie are always available.",
        address="5207 Brodie Ln",
        city="Austin",
        state="TX",
        zip_code="78745",
        lat=30.230633408810952,
        lng=-97.81658836137646,
        hours="8:00AM - 10:00PM",
        price="$$",
        rating=4.8,
    )
    restaurant32 = Restaurant(
        name="The Baked Bear",
        description=
        "Decadent build-your-own custom ice cream sandwiches with artisanal ice cream & house-made cookies.",
        address="211 Walter Seaholm Dr",
        city="Austin",
        state="TX",
        zip_code="78701",
        lat=30.268031906876974,
        lng=-97.75267155396759,
        hours="12:00PM - 11:00PM",
        price="$",
        rating=4.7,
    )
    ## add restaurants
    db.session.add(restaurant1)
    db.session.add(restaurant2)
    db.session.add(restaurant3)
    db.session.add(restaurant4)
    db.session.add(restaurant5)
    db.session.add(restaurant6)
    db.session.add(restaurant7)
    db.session.add(restaurant8)
    db.session.add(restaurant9)
    db.session.add(restaurant10)
    db.session.add(restaurant11)
    db.session.add(restaurant12)
    db.session.add(restaurant13)
    db.session.add(restaurant14)
    db.session.add(restaurant15)
    db.session.add(restaurant16)
    db.session.add(restaurant17)
    db.session.add(restaurant18)
    db.session.add(restaurant19)
    db.session.add(restaurant20)
    db.session.add(restaurant21)
    db.session.add(restaurant22)
    db.session.add(restaurant23)
    db.session.add(restaurant24)
    db.session.add(restaurant25)
    db.session.add(restaurant26)
    db.session.add(restaurant27)
    db.session.add(restaurant28)
    db.session.add(restaurant29)
    db.session.add(restaurant30)
    db.session.add(restaurant31)
    db.session.add(restaurant32)

    ## append cake
    genre1.restaurants.append(restaurant1)
    genre1.restaurants.append(restaurant3)
    genre1.restaurants.append(restaurant5)
    genre1.restaurants.append(restaurant6)
    genre1.restaurants.append(restaurant7)
    genre1.restaurants.append(restaurant8)
    genre1.restaurants.append(restaurant11)
    genre1.restaurants.append(restaurant13)
    genre1.restaurants.append(restaurant27)
    ##append cupcake
    genre2.restaurants.append(restaurant3)
    genre2.restaurants.append(restaurant6)
    genre2.restaurants.append(restaurant8)
    genre2.restaurants.append(restaurant11)
    genre2.restaurants.append(restaurant2)
    genre2.restaurants.append(restaurant4)
    genre2.restaurants.append(restaurant9)
    genre2.restaurants.append(restaurant10)
    # append pie
    genre3.restaurants.append(restaurant3)
    genre3.restaurants.append(restaurant13)
    genre3.restaurants.append(restaurant12)
    genre3.restaurants.append(restaurant14)
    #append chocolate
    genre4.restaurants.append(restaurant15)
    genre4.restaurants.append(restaurant17)
    genre4.restaurants.append(restaurant18)
    genre4.restaurants.append(restaurant19)
    genre4.restaurants.append(restaurant16)
    #append candy
    genre5.restaurants.append(restaurant17)
    genre5.restaurants.append(restaurant18)
    genre5.restaurants.append(restaurant19)
    # append ice cream
    genre6.restaurants.append(restaurant20)
    genre6.restaurants.append(restaurant21)
    genre6.restaurants.append(restaurant22)
    genre6.restaurants.append(restaurant23)
    genre6.restaurants.append(restaurant24)
    genre6.restaurants.append(restaurant28)
    genre6.restaurants.append(restaurant29)
    genre6.restaurants.append(restaurant30)
    genre6.restaurants.append(restaurant31)
    genre6.restaurants.append(restaurant32)
    # append Doughnuts
    genre7.restaurants.append(restaurant25)
    genre7.restaurants.append(restaurant26)
    genre7.restaurants.append(restaurant11)
    #append Pastries
    genre8.restaurants.append(restaurant5)
    genre8.restaurants.append(restaurant6)
    genre8.restaurants.append(restaurant8)
    genre8.restaurants.append(restaurant13)
    genre8.restaurants.append(restaurant27)
    genre8.restaurants.append(restaurant2)
    genre8.restaurants.append(restaurant4)
    genre8.restaurants.append(restaurant14)
    genre8.restaurants.append(restaurant15)

    #append gelato
    genre9.restaurants.append(restaurant21)

    # append vegan
    genre10.restaurants.append(restaurant8)
    genre10.restaurants.append(restaurant11)
    genre10.restaurants.append(restaurant4)
    genre10.restaurants.append(restaurant23)
    genre10.restaurants.append(restaurant24)
    genre10.restaurants.append(restaurant28)
    genre10.restaurants.append(restaurant25)
    #append cookies
    genre11.restaurants.append(restaurant3)
    genre11.restaurants.append(restaurant5)
    genre11.restaurants.append(restaurant8)
    genre11.restaurants.append(restaurant11)
    genre11.restaurants.append(restaurant13)
    genre11.restaurants.append(restaurant2)
    genre11.restaurants.append(restaurant4)
    genre11.restaurants.append(restaurant14)
    genre11.restaurants.append(restaurant29)
    genre11.restaurants.append(restaurant30)
    genre11.restaurants.append(restaurant31)
    genre11.restaurants.append(restaurant32)

    ## add genres
    db.session.add(genre1)
    db.session.add(genre2)
    db.session.add(genre3)
    db.session.add(genre4)
    db.session.add(genre5)
    db.session.add(genre6)
    db.session.add(genre7)
    db.session.add(genre8)
    db.session.add(genre9)
    db.session.add(genre10)

    db.session.add(genre11)

    db.session.commit()
コード例 #32
0
def init():

    # create artists
    artists = [
        'Mickey Mouse',
        'Goofy',
        'Bart Simpson',
        'Homer',
        'Bruce Lee',
    ]

    for name in artists:
        artist = Artist.query.filter_by(name=name).first()
        if artist is None:
            artist = Artist(name=name)
        db.session.add(artist)

    try:
        db.session.commit()
    except:
        db.session.rollback()

    # create genre
    genres = [
        'Rock',
        'Pop',
        'Hip-hop',
        'Rap',
        'R & R',
        'Classical',
        'Techno',
        'Jazz',
        'Folk',
        'Country',
    ]

    for name in genres:
        genre = Genre.query.filter_by(name=name).first()
        if genre is None:
            genre = Genre(name=name)
        db.session.add(genre)

    try:
        db.session.commit()
    except:
        db.session.rollback()

    # create albums
    albums = [
        ('Becon and Eggs', 2, 4,
         '/shutify/app/static/images/artwork/clearday.jpg',
         '/static/images/artwork/clearday.jpg'),
        ('Pizza head', 5, 10, '/shutify/app/static/images/artwork/energy.jpg',
         '/static/images/artwork/energy.jpg'),
        ('Summer Hits', 3, 1,
         '/shutify/app/static/images/artwork/goinghigher.jpg',
         '/static/images/artwork/goinghigher.jpg'),
        ('The movie soundtrack', 2, 9,
         '/shutify/app/static/images/artwork/funkyelement.jpg',
         '/static/images/artwork/funkyelement.jpg'),
        ('Best of the Worst', 1, 3,
         '/shutify/app/static/images/artwork/popdance.jpg',
         '/static/images/artwork/popdance.jpg'),
        ('Hello World', 3, 6, '/shutify/app/static/images/artwork/ukulele.jpg',
         '/static/images/artwork/ukulele.jpg'),
        ('Best beats', 4, 7, '/shutify/app/static/images/artwork/sweet.jpg',
         '/static/images/artwork/sweet.jpg'),
    ]

    for item in albums:
        album = Album.query.filter_by(title=item[0]).first()
        if album is None:
            album = Album(
                title=item[0],
                artist_id=item[1],
                genre_id=item[2],
                artwork_path=item[3],
                artwork_url=item[4],
            )
        db.session.add(album)

    try:
        db.session.commit()
    except:
        db.session.rollback()

    # songs

    songs = [
        ('Acoustic Breeze', 1, 5, 8, timedelta(minutes=2, seconds=37),
         '/shutify/app/static/music/bensound-acousticbreeze.mp3',
         '/static/music/bensound-acousticbreeze.mp3', 1, 10),
        ('A new beginning', 1, 5, 1, timedelta(minutes=2, seconds=35),
         '/shutify/app/static/music/bensound-anewbeginning.mp3',
         '/static/music/bensound-anewbeginning.mp3', 2, 4),
        ('Better Days', 1, 5, 2, timedelta(minutes=2, seconds=33),
         '/shutify/app/static/music/bensound-betterdays.mp3',
         '/static/music/bensound-betterdays.mp3', 3, 10),
        ('Buddy', 1, 5, 3, timedelta(minutes=2, seconds=2),
         '/shutify/app/static/music/bensound-buddy.mp3',
         '/static/music/bensound-buddy.mp3', 4, 13),
        ('Clear Day', 1, 5, 4, timedelta(minutes=1, seconds=29),
         '/shutify/app/static/music/bensound-clearday.mp3',
         '/static/music/bensound-clearday.mp3', 5, 8),
        ('Going Higher', 2, 1, 1, timedelta(minutes=4, seconds=4),
         '/shutify/app/static/music/bensound-goinghigher.mp3',
         '/static/music/bensound-goinghigher.mp3', 1, 34),
        ('Funny Song', 2, 4, 2, timedelta(minutes=3, seconds=7),
         '/shutify/app/static/music/bensound-funnysong.mp3',
         '/static/music/bensound-funnysong.mp3', 2, 12),
        ('Funky Element', 2, 1, 3, timedelta(minutes=3, seconds=8),
         '/shutify/app/static/music/bensound-funkyelement.mp3',
         '/static/music/bensound-funkyelement.mp3', 2, 26),
        ('Extreme Action', 2, 1, 4, timedelta(minutes=8, seconds=3),
         '/shutify/app/static/music/bensound-extremeaction.mp3',
         '/static/music/bensound-extremeaction.mp3', 3, 29),
        ('Epic', 2, 4, 5, timedelta(minutes=2, seconds=58),
         '/shutify/app/static/music/bensound-epic.mp3',
         '/static/music/bensound-epic.mp3', 3, 17),
        ('Energy', 2, 1, 6, timedelta(minutes=2, seconds=59),
         '/shutify/app/static/music/bensound-energy.mp3',
         '/static/music/bensound-energy.mp3', 4, 26),
        ('Dubstep', 2, 1, 7, timedelta(minutes=2, seconds=3),
         '/shutify/app/static/music/bensound-dubstep.mp3',
         '/static/music/bensound-dubstep.mp3', 5, 22),
        ('Happiness', 3, 6, 8, timedelta(minutes=4, seconds=21),
         '/shutify/app/static/music/bensound-happiness.mp3',
         '/static/music/bensound-happiness.mp3', 5, 3),
        ('Happy Rock', 3, 6, 9, timedelta(minutes=1, seconds=45),
         '/shutify/app/static/music/bensound-happyrock.mp3',
         '/static/music/bensound-happyrock.mp3', 4, 8),
        ('Jazzy Frenchy', 3, 6, 10, timedelta(minutes=1, seconds=44),
         '/shutify/app/static/music/bensound-jazzyfrenchy.mp3',
         '/static/music/bensound-jazzyfrenchy.mp3', 3, 11),
        ('Little Idea', 3, 6, 1, timedelta(minutes=2, seconds=49),
         '/shutify/app/static/music/bensound-littleidea.mp3',
         '/static/music/bensound-littleidea.mp3', 2, 12),
        ('Memories', 3, 6, 2, timedelta(minutes=3, seconds=50),
         '/shutify/app/static/music/bensound-memories.mp3',
         '/static/music/bensound-memories.mp3', 1, 6),
        ('Moose', 4, 7, 1, timedelta(minutes=2, seconds=43),
         '/shutify/app/static/music/bensound-moose.mp3',
         '/static/music/bensound-moose.mp3', 5, 2),
        ('November', 4, 7, 2, timedelta(minutes=3, seconds=32),
         '/shutify/app/static/music/bensound-november.mp3',
         '/static/music/bensound-november.mp3', 4, 5),
        ('Of Elias Dream', 4, 7, 3, timedelta(minutes=4, seconds=58),
         '/shutify/app/static/music/bensound-ofeliasdream.mp3',
         '/static/music/bensound-ofeliasdream.mp3', 3, 5),
        ('Pop Dance', 4, 7, 2, timedelta(minutes=2, seconds=42),
         '/shutify/app/static/music/bensound-popdance.mp3',
         '/static/music/bensound-popdance.mp3', 2, 11),
        ('Retro Soul', 4, 7, 5, timedelta(minutes=3, seconds=36),
         '/shutify/app/static/music/bensound-retrosoul.mp3',
         '/static/music/bensound-retrosoul.mp3', 1, 11),
        ('Sad Day', 5, 2, 1, timedelta(minutes=2, seconds=28),
         '/shutify/app/static/music/bensound-sadday.mp3',
         '/static/music/bensound-sadday.mp3', 1, 9),
        ('Sci-fi', 5, 2, 2, timedelta(minutes=4, seconds=44),
         '/shutify/app/static/music/bensound-scifi.mp3',
         '/static/music/bensound-scifi.mp3', 2, 9),
        ('Slow Motion', 5, 2, 3, timedelta(minutes=3, seconds=26),
         '/shutify/app/static/music/bensound-slowmotion.mp3',
         '/static/music/bensound-slowmotion.mp3', 3, 4),
        ('Sunny', 5, 2, 4, timedelta(minutes=2, seconds=20),
         '/shutify/app/static/music/bensound-sunny.mp3',
         '/static/music/bensound-sunny.mp3', 4, 19),
        ('Sweet', 5, 2, 5, timedelta(minutes=5, seconds=7),
         '/shutify/app/static/music/bensound-sweet.mp3',
         '/static/music/bensound-sweet.mp3', 5, 17),
        ('Tenderness ', 3, 3, 7, timedelta(minutes=2, seconds=3),
         '/shutify/app/static/music/bensound-tenderness.mp3',
         '/static/music/bensound-tenderness.mp3', 4, 13),
        ('The Lounge', 3, 3, 8, timedelta(minutes=4, seconds=16),
         '/shutify/app/static/music/bensound-thelounge.mp3',
         '/static/music/bensound-thelounge.mp3', 3, 7),
        ('Ukulele', 3, 3, 9, timedelta(minutes=2, seconds=26),
         '/shutify/app/static/music/bensound-ukulele.mp3',
         '/static/music/bensound-ukulele.mp3', 2, 22),
        ('Tomorrow', 3, 3, 1, timedelta(minutes=4, seconds=54),
         '/shutify/app/static/music/bensound-tomorrow.mp3 ',
         '/static/music/bensound-tomorrow.mp3', 1, 15),
    ]

    for item in songs:
        song = Song.query.filter_by(title=item[0]).first()
        if song is None:
            song = Song(
                title=item[0],
                artist_id=item[1],
                album_id=item[2],
                genre_id=item[3],
                duration=item[4],
                file_path=item[5],
                file_url=item[6],
                track=item[7],
                num_plays=item[8],
            )

        db.session.add(song)

    try:
        db.session.commit()
    except:
        db.session.rollback()
コード例 #33
0
    def handle(self, *args, **options):
        start_time = time()
        Author.objects.all().delete()
        User.objects.all().delete()
        Book.objects.all().delete()
        UserRating.objects.all().delete()
        Genre.objects.all().delete()
        print("deletes done", time() - start_time)

        first_names = [
            'Lacy',
            'Alaine'
            'Marylin',
            'Tula',
            'Roberta',
            'Tania',
            'Gary',
            'Kristal',
            'Jeannine',
            'Shela',
            'Kyra',
            'Bo',
            'Mozelle',
            'Tyron',
            'Mai',
            'Oda',
            'Kerry',
            'Lorretta',
            'Laureen',
            'Aretha',
            'Bobette',
            'Whitley',
            'Angelique',
            'Mario',
            'Asia',
            'Sharlene',
            'Johnette',
            'Rod',
            'Erasmo',
            'Marlyn',
            'Yvette',
            'Elizabeth',
            'Tawanda',
            'Ivory',
            'Tyisha',
            'Emmaline',
            'Randall',
            'Odette',
            'Isabelle',
            'Granville',
            'Jay',
            'Darleen',
            'Arlean',
            'Un',
            'Louanne',
            'Devora',
            'Rodney',
            'Sixta',
            'Martine',
            'Hollie',
            'Raul',
            'Anette',
            'Yolande',
            'Monserrate',
            'Kellye',
            'Casimira',
            'Karlene',
            'Donya',
            'Nelda',
            'Joesph',
            'Tyrone',
            'Dorothea',
            'Lesli',
            'Rozanne',
            'Mirian',
            'Jae',
            'Gavin',
            'Vita',
            'Corrinne',
            'Roscoe',
            'Veola',
            'Wynona',
            'Dorcas',
            'Cristin',
            'Faith',
            'Erin',
            'Linda',
            'Debi',
            'Marquitta',
            'Kathi',
            'Shasta',
            'Britni',
            'Rina',
            'Emelda',
            'Evalyn',
            'Sal',
            'Lawerence',
            'Verena',
            'Tennille',
            'Ben',
            'Elouise',
            'Sook',
            'Kiyoko',
            'Roselyn',
            'Pia',
            'Delaine',
            'Mirtha',
            'Bianca',
            'Risa',
            'Mila',
            'Taisha',
            'Karyl',
            'Cary',
            'Jani',
            'Chad',
            'Nigel',
            'Danny',
            'Azucena',
            'Marti',
            'Fannie',
            'Cassy',
            'Hyman',
            'Glinda',
            'Percy',
            'Joanna',
            'Jeromy',
            'Simonne',
            'Diane',
            'Shantel',
            'Tom',
            'Lang',
        ]

        last_names = [
            'Snellgrove',
            'Gilliland',
            'Wellington',
            'Panzer',
            'Gittens',
            'Czajkowski',
            'Bloomquist',
            'Abramson',
            'Keating',
            'Valenzuela',
            'Moritz',
            'Blasko',
            'Arceneaux',
            'Stotz',
            'Ospina',
            'Bushnell',
            'Buonocore',
            'Husain',
            'Koons',
            'Mash',
            'Alvarez',
            'Moudy',
            'Brownlow',
            'Rothenberg',
            'Tope',
            'Andreas',
            'Remer',
            'Decarlo',
            'Savoy',
            'Armstead',
            'Snook',
            'Barthel',
            'Sheehan',
            'Gebhardt',
            'Gaut',
            'Erickson',
            'Widell',
            'Swilley',
            'Dodge',
            'Benedict',
            'Debonis',
            'Byfield',
            'Brisco',
            'Spatz',
            'Neifert',
            'Mcmunn',
            'Keller',
            'Boulay',
            'Rolling',
            'Toothaker',
            'Jock',
            'Fullmer',
            'Schoepp',
            'Lasker',
            'Dow',
            'Wingerter',
            'Fortman',
            'Crowe',
            'Rhodes',
            'Mckee',
            'Hoop',
            'Hales',
            'Sandell',
            'Murnane',
            'Sirmans',
            'Fry',
            'Avitia',
            'Wittmer',
            'Criado',
            'Zelinski',
            'Berumen',
            'Kennett',
            'Brayboy',
            'Providence',
            'Reddick',
            'Spinney',
            'Organ',
            'Middlebrook',
            'Brownell',
            'Kimmel',
            'Sorensen',
            'Brossard',
            'Temple',
            'Mayes',
            'Gade',
            'Kary',
            'Firkins',
            'Porcaro',
            'Moschella',
            'Aquilino',
            'Soule',
            'Glenn',
            'Dandrea',
            'Woolston',
            'Ewald',
            'Junior',
            'Nanez',
            'Berlanga',
            'Eppinger',
            'Payton',
            'Linke',
            'Roache',
            'Overall',
            'Pitre',
            'Kirtley',
            'Seeman',
            'Belliveau',
            'Lathrop',
            'Barrington',
            'Dargie',
            'Sauers',
            'Carpentier',
            'Peavey',
            'Bocanegra',
            'Albers',
            'Searfoss',
            'Worthen',
            'Demps',
            'Orchard',
            'Kromer',
            'Gauthier',
        ]

        print("len first", len(first_names))
        print("len las", len(last_names))

        authors = [
            Author(first_name=element[0],
                   last_name=element[1]) for element in islice(
                       zip(cycle(first_names), cycle(last_names)), 10000)
        ]

        Author.objects.bulk_create(authors)
        print("authors created", time() - start_time)

        genres_names = [
            'Sci-Fi', 'Fantasy', 'Romance', 'Western', 'Thriller', 'Mystery',
            'Detective', 'Dystopia', 'Memoir', 'Biography', 'Play', 'Musical',
            'Satire', 'Haiku', 'Horror', 'Do It Yourself'
        ]

        genres = [Genre(name=name) for name in genres_names]
        Genre.objects.bulk_create(genres)

        users = [User(username=f'username {n}') for n in range(100000)]
        User.objects.bulk_create(users)
        print("users created", time() - start_time)

        articles = ['The', 'A']
        adjectives = [
            'able',
            'bad',
            'best',
            'better',
            'big',
            'black',
            'certain',
            'clear',
            'different',
            'early',
            'easy',
            'economic',
            'federal',
            'free',
            'full',
            'good',
            'great',
            'hard',
            'high',
            'human',
            'important',
            'international',
            'large',
            'late',
            'little',
            'local',
            'long',
            'low',
            'major',
            'military',
            'national',
            'new',
            'old',
            'only',
            'other',
            'political',
            'possible',
            'public',
            'real',
            'recent',
            'right',
            'small',
            'social',
            'special',
            'strong',
            'sure',
            'true',
            'white',
            'whole',
            'young',
        ]
        nouns = [
            'area',
            'book',
            'business',
            'case',
            'child',
            'company',
            'country',
            'day',
            'eye',
            'fact',
            'family',
            'government',
            'group',
            'hand',
            'home',
            'job',
            'life',
            'lot',
            'man',
            'money',
            'month',
            'mother',
            'Mr',
            'night',
            'number',
            'part',
            'people',
            'place',
            'point',
            'problem',
            'program',
            'question',
            'right',
            'room',
            'school',
            'state',
            'story',
            'student',
            'study',
            'system',
            'thing',
            'time',
            'water',
            'way',
            'week',
            'woman',
            'word',
            'work',
            'world',
            'year',
        ]

        book_titles = set()

        vowels = {'a', 'e', 'i', 'o', 'u'}

        def word_with_article(word):
            article = random.choice(articles)
            if word[0].lower() in vowels and article.lower() == 'a':
                article += 'n'

            return f'{article} {word}'

        def generate_book_title():
            title = f'{word_with_article(random.choice(adjectives))} {random.choice(nouns)}'

            if title in book_titles:
                title += f' and {word_with_article(random.choice(adjectives))} {random.choice(nouns)}'

            return title

        print("generating book titles:", time() - start_time)
        for _ in range(20000):
            book_titles.add(generate_book_title())

        books = [Book(title=title) for title in book_titles]
        Book.objects.bulk_create(books)

        print("making author and genre lists", time() - start_time)
        all_authors = list(Author.objects.all())
        all_genres = list(Genre.objects.all())
        print("getting user list", time() - start_time)
        all_users = list(User.objects.all())

        print("assigning authors and genres", time() - start_time)
        count = 0
        for book in Book.objects.all():
            authors = [random.choice(all_authors)]
            while random.randint(1, 10) > 9:
                authors.append(random.choice(all_authors))

            book.authors.add(*authors)

            genres = [random.choice(all_genres)]
            while random.randint(1, 20) > 10:
                genres.append(random.choice(all_genres))

            book.genres.add(*genres)

            rating_count = abs(int(random.gauss(100, 50)))
            users = random.sample(all_users, rating_count)
            user_ratings = [
                UserRating(user=user, book=book, rating=random.randint(1, 5))
                for user in users
            ]
            UserRating.objects.bulk_create(user_ratings)

            count += 1
            if count % 1000 == 0:
                print("count", count, "time:", time() - start_time)