async def list(self, page_number: int, page_size: int) -> Tuple[int, List[Genre]]: """ Возвращает все жанры """ # получаем только ID жанров params = { "size": page_size, "from": page_size * (page_number - 1), "sort": "id" } genres_total, genre_ids = await self.storage.search(self._index, params=params) genres = OrderedDict.fromkeys(genre_ids, None) # проверяем есть ли полученные жанры в кеше по их ID for genre_id in genres.keys(): data = await self.cache.get(genre_id) if data: genres[genre_id] = Genre.parse_raw(data) # не найденные в кеше жанры запрашиваем в эластике и кладём в кеш not_found = [ genre_id for genre_id in genres.keys() if genres[genre_id] is None ] if not_found: docs = await self.storage.get_by_ids(self._index, not_found) for doc in docs: genre = Genre(**doc) await self.cache.put(genre.id, genre.json()) genres[genre.id] = genre return (genres_total, list(genres.values()))
def post(self): info = json.loads(request.data) parse = info['genre'] try: result = Genre( name=parse['name'], ) orm.commit() return jsonify(result.to_dict()) except Exception as exception: return exception
async def get_by_id(self, genre_id: UUID) -> Optional[Genre]: """ Возвращает объект жанра. Он опционален, так как жанр может отсутствовать в базе """ data = await self.cache.get(genre_id) if data: return Genre.parse_raw(data) docs = await self._es_get_by_ids([ genre_id, ]) if not docs: return None genre = Genre(**docs[0]) await self.cache.put(genre.id, genre.json())
def __parse_and_insert_genre(self, row) -> uuid: genre = row['Genre'] genre_id = self.genre_service.get_id(genre) if not genre_id: genre_id = self.genre_service.insert(Genre(genre)) return genre_id
def select(id): genre = None sql = "SELECT * FROM genres WHERE id = %s" values = [id] result = run_sql(sql, values)[0] if result is not None: genre = Genre(result['category'], result['id']) return genre
def select_all(): genres = [] sql = "SELECT * FROM genres ORDER BY category" results = run_sql(sql) for row in results: genre = Genre(row['category'], row['id']) genres.append(genre) return genres
def get(self, id): try: if not Genre.exists(lambda genre: genre.id == int(id)): return None, 404 return jsonify(Genre[int(id)].to_dict()) except Exception as exception: return exception, 404
def delete(self, id): try: if not Genre.exists(lambda genre: genre.id == int(id)): return None, 404 Genre[int(id)].delete() return None, 200 except Exception as exception: return exception
async def get_by_ids(self, genre_ids: List[UUID]) -> Optional[List[Genre]]: """ Возвращает жанры по списку id. """ genres = OrderedDict.fromkeys(genre_ids, None) # проверяем есть ли полученные жанры в кеше по их ID for genre_id in genres.keys(): data = await self.cache.get(genre_id) if data: genres[genre_id] = Genre.parse_raw(data) # не найденные в кеше жанры запрашиваем в эластике и кладём в кеш not_found = [ genre_id for genre_id in genres.keys() if genres[genre_id] is None ] if not_found: docs = await self.storage.get_by_ids(self._index, not_found) for doc in docs: genre = Genre(**doc) await self.cache.put(genre.id, genre.json()) genres[genre.id] = genre return list(genres.values())
def put(self, id): try: if not Genre.exists(lambda genre: genre.id == int(id)): return None, 404 info = json.loads(request.data) parse = info['genre'] result = Genre[int(id)] result.set(name=parse['name'], ) return jsonify(result.to_dict()) except Exception as exception: return exception
def post(self): info = json.loads(request.data) parse = info['book'] try: result = Book( name=parse['name'], description=parse['description'], pages=parse['pages'], author=Author[int(parse['author_id'])], genres=[ genre for genre in Genre.select( lambda g: g.id in parse['genres']) ], ) orm.commit() return jsonify(result.to_dict()) except Exception as exception: return exception
def put(self, id): try: if not Book.exists(lambda book: book.id == int(id)): return None, 404 info = json.loads(request.data) parse = info['book'] result = Book[int(id)] result.set( name=parse['name'], description=parse['description'], pages=parse['pages'], image=parse['image'], author=Author[int(parse['author_id'])], genres=[genre for genre in Genre.select(lambda g: g.id in parse['genres'])] ) return jsonify(result.to_dict()) except Exception as exception: return exception
def create_genre(): category = request.form['genre-category'] genre = Genre(category) genre_repository.save(genre) return redirect("/genres")
fat_cat = Label("Fat Cat Records") label_repository.save(fat_cat) fueled_by_ramen = Label("Fueled By Ramen") label_repository.save(fueled_by_ramen) island = Label("Island Records") label_repository.save(island) vertigo = Label("Vertigo") label_repository.save(vertigo) warner = Label("Warner Records") label_repository.save(warner) republic = Label("Republic Records") label_repository.save(republic) # GENRES alt_rock = Genre("Alternative Rock") genre_repository.save(alt_rock) rock = Genre("Rock") genre_repository.save(rock) pop = Genre("Pop") genre_repository.save(pop) pop_rock = Genre("Pop Rock") genre_repository.save(pop_rock) soft_rock = Genre("Soft Rock") genre_repository.save(soft_rock) folk = Genre("Folk")
james = User ( name = "James Bolton", username= "******", email="*****@*****.**", password="******" ) admin.save() sagal.save() becky.save() james.save() print('Users created') print('Age groups created!') genre_1 = Genre(genre='Education') genre_2 = Genre(genre='Fiction') genre_3 = Genre(genre='Poetry') genre_4 = Genre(genre='Activity Book') genre_5 = Genre(genre='Fantasy') genre_6 = Genre(genre='Science Fiction') genre_7 = Genre(genre='Picture Book') print('Genres created!') tracy_beaker = Book ( title= 'Starring Tracy Beaker', author= 'Jacqueline Wilson', description= 'Tracy is a orphan who lives in a Childrens Home which she calls in her point of view "The Dumping Ground". She plans on becoming an actress just like her Hollywood mum, and she plans to make a start with this great opportunity. She desperately wants her mum to come and watch her acting Scrooge.', image= 'https://d3ddkgxe55ca6c.cloudfront.net/assets/t1497975559/a/c3/44/113562-ml-53622.jpg', age= '10-16',
def seed_db(): genre_objs = [Genre(name=genre) for genre in genres] artist_objs = [Artist(**artist) for artist in artists] venue_objs = [Venue(**venue) for venue in venues] try: db.session.add_all(genre_objs) db.session.add_all(artist_objs) db.session.add_all(venue_objs) db.session.commit() # genre ids genre_ids = {} for genre in genre_objs: genre_ids.update({genre.name: genre.id}) # artist ids artist1_id = artist_objs[0].id artist2_id = artist_objs[1].id artist3_id = artist_objs[2].id # venue ids venue1_id = venue_objs[0].id venue2_id = venue_objs[1].id venue3_id = venue_objs[2].id # add artist genres artists_genres = [ ArtistGenre(artist_id=artist1_id, genre_id=genre_ids["Rock n Roll"]), ArtistGenre(artist_id=artist2_id, genre_id=genre_ids["Jazz"]), ArtistGenre(artist_id=artist3_id, genre_id=genre_ids["Jazz"]), ArtistGenre(artist_id=artist3_id, genre_id=genre_ids["Classical"]) ] db.session.add_all(artists_genres) # add venue genres venues_genres = [ VenueGenre(venue_id=venue1_id, genre_id=genre_ids["Jazz"]), VenueGenre(venue_id=venue1_id, genre_id=genre_ids["Reggae"]), VenueGenre(venue_id=venue1_id, genre_id=genre_ids["Swing"]), VenueGenre(venue_id=venue1_id, genre_id=genre_ids["Classical"]), VenueGenre(venue_id=venue1_id, genre_id=genre_ids["Folk"]), VenueGenre(venue_id=venue2_id, genre_id=genre_ids["Classical"]), VenueGenre(venue_id=venue2_id, genre_id=genre_ids["R&B"]), VenueGenre(venue_id=venue2_id, genre_id=genre_ids["Hip-Hop"]), VenueGenre(venue_id=venue3_id, genre_id=genre_ids["Rock n Roll"]), VenueGenre(venue_id=venue3_id, genre_id=genre_ids["Jazz"]), VenueGenre(venue_id=venue3_id, genre_id=genre_ids["Classical"]), VenueGenre(venue_id=venue3_id, genre_id=genre_ids["Folk"]), ] db.session.add_all(venues_genres) # add shows shows = [ {'artist_id': artist1_id, 'venue_id': venue3_id, 'start_time': '2019-06-15T23:00:00.000Z'}, {'artist_id': artist3_id, 'venue_id': venue3_id, 'start_time': '2035-04-01T20:00:00.000Z'}, {'artist_id': artist3_id, 'venue_id': venue3_id, 'start_time': '2035-04-08T20:00:00.000Z'}, {'artist_id': artist3_id, 'venue_id': venue3_id, 'start_time': '2035-04-15T20:00:00.000Z'}, {'venue_id': venue1_id, 'artist_id': artist1_id, 'start_time': '2019-05-21T21:30:00.000Z'}, {'venue_id': venue3_id, 'artist_id': artist2_id, 'start_time': '2019-06-15T23:00:00.000Z'}, {'venue_id': venue3_id, 'artist_id': artist3_id, 'start_time': '2035-04-01T20:00:00.000Z'}, {'venue_id': venue3_id, 'artist_id': artist3_id, 'start_time': '2035-04-08T20:00:00.000Z'}, {'venue_id': venue3_id, 'artist_id': artist3_id, 'start_time': '2035-04-15T20:00:00.000Z'}, ] show_objs = [Show(**show) for show in shows] db.session.add_all(show_objs) db.session.commit() except: db.session.rollback() print(sys.exc_info()) finally: db.session.close()
def genreResolver(_, info): genres = Genre.select() return genres
def setUp(self): self.genre = Genre("Indie Rock")
from app import app, db from models.user import User from models.comments import Comment, NestedComment from models.genre import Genre from models.video import Video with app.app_context(): db.drop_all() db.create_all() animation = Genre(name='Animation') writing = Genre(name='Writing') film_and_video = Genre(name='Film & Video') graphic_design = Genre(name='Graphic Design') art_illustration = Genre(name='Art & Illustration') music = Genre(name='Music') photography = Genre(name='Photography') ui_ux_design = Genre(name='UI/UX Design') web_development = Genre(name='Web Development') cooking = Genre(name='Cooking') lifestyle = Genre(name='Lifestyle') productivity = Genre(name='Productivity') db.session.add_all([ animation, writing, film_and_video, productivity, graphic_design, art_illustration, music, photography, ui_ux_design, web_development, cooking, lifestyle ]) print('Genres Created!')
def get(self): return jsonify([genre.to_dict() for genre in Genre.select()])