class TestNoteApi(APITestCase): def setUp(self): # create movie self.movie = Movie(name="The Space Between Us", year_of_release=2017) self.movie.save() def test_movie_creation(self): response = self.client.post(reverse('movies'), { 'name': 'Bee Movie', 'year_of_release': 2007 }) # assert new movie was added self.assertEqual(Movie.objects.count(), 2) # assert a created status code was returned self.assertEqual(201, response.status_code) def test_getting_movies(self): response = self.client.get(reverse('movies'), format="json") self.assertEqual(len(response.data), 1) def test_updating_movie(self): response = self.client.put(reverse('detail', kwargs={'pk': 1}), { 'name': 'The Space Between Us updated', 'year_of_release': 2017 }, format="json") # check info returned has the update self.assertEqual('The Space Between Us updated', response.data['name']) def test_deleting_movie(self): response = self.client.delete(reverse('detail', kwargs={'pk': 1})) self.assertEqual(204, response.status_code)
class TestMovieModel(TestCase): def setUp(self): self.movie = Movie(name="Split", year_of_release=2016) self.movie.save() def test_movie_creation(self): self.assertEqual(Movie.objects.count(), 1) def test_movie_representation(self): self.assertEqual(self.movie.name, str(self.movie))
def create(self, request, *args, **kwargs): """Create movie entry based on sent title. Handle POST on /movies This method calls `get_omdb_movie` which requests external API. """ movie_request = MovieRequestSerializer(data=request.data) def movie_exists_response(): return Response( {'title': ['Movie with given title already exists.']}, status=status.HTTP_409_CONFLICT) if not movie_request.is_valid(): return Response(movie_request.errors, status=status.HTTP_400_BAD_REQUEST) # get title from request title = movie_request.validated_data['title'] # slugify title and try to validate it's existence if Movie.objects.filter(slug=slugify(title)).exists(): return movie_exists_response() # try to get movie from omdbapi and notify if it's not possible try: details = get_omdb_movie(title) except HTTPError as e: logging.error('omdabpi http error: %s - %r', e.errno, e.strerror) return Response({ 'OMDB API': [ e.strerror, ], }, status=status.HTTP_503_SERVICE_UNAVAILABLE) except RequestException as e: logging.error('omdbapi raised exception: %r', e) return Response( { 'OMDB API': [ 'External service is unavailable. Please try again later.', ], }, status=status.HTTP_503_SERVICE_UNAVAILABLE) title = details['Title'] movie = Movie(title=title, details=details, slug=slugify(title)) # it should throw error when slugified title exists in database # and couldn't be verfied earlier (eg. incomplete title) try: movie.save() except IntegrityError: return movie_exists_response() logger.info('Created new movie: %s', movie.title) # return new movie in response return Response(MovieSerializer(movie).data, status=status.HTTP_201_CREATED)
def handle(self, *args, **kwargs): theaters = [ "METROPOLE XXI", "ONE BELPARK XXI", "PGC XXI", "PLAZA INDONESIA XXI", "PLUIT JUNCTION XXI" ] movies = [ "Batman", "Superman", "Spiderman", "Marvel", "Aquaman", "Fantastic Four" ] from api.models import Movie, Theater, Showtime list_of_movies = [] # Iterate to Movies self.stdout.write("===== Adding Movies =====") for movies_name in movies: self.stdout.write(">{}".format(movies_name)) # create movie current_movie = Movie(name=movies_name) current_movie.save() list_of_movies.append(current_movie) self.stdout.write("===== Adding Theater =====") for theater_name in theaters: self.stdout.write(">{}".format(theater_name)) # create theater current_theater = Theater(name=theater_name) current_theater.save() # adding showtime to each movie in one theater for movie in list_of_movies: self.stdout.write(">{}'showtime added".format(movie.name)) current_theater.showtime.create(theater=current_theater,movie=movie) self.stdout.write("Done")
def create_bulk_data(self, n): fake = Faker(["en-US"]) directors = list(Director.objects.all()) for _ in range(n): title = fake.paragraph() year = fake.year() director = random.choice(directors) yield Movie(title=title, year=year, director=director)
def movies(request): if request.method == 'GET': id = request.GET.get('id', request.GET.get('movie_id', None)) title = request.GET.get('title', None) # cnt = int(request.GET.get('cnt')) # print(cnt) movies = Movie.objects.all() # pprint.pprint(movies) if id: movies = movies.filter(pk=id) if title: movies = movies.filter(title__icontains=title) # else: # movies = Movie.objects.all()[cnt-10:cnt] num = request.GET.get('num', None) canmore = True if len(movies) >= 12: if num: num = int(num) movies = movies[num * 12:(num + 1) * 12] if len(movies) < 12: canmore = False else: movies = movies[:12] else: canmore = False serializer = MovieSerializer(movies, many=True) return Response(data=[serializer.data, canmore], status=status.HTTP_200_OK) if request.method == 'DELETE': movie = Movie.objects.all() movie.delete() return Response(status=status.HTTP_200_OK) if request.method == 'POST': movies = request.data.get('movies', None) for movie in movies: id = movie.get('id', None) title = movie.get('title', None) genres = movie.get('genres', None) if not (id and title and genres): continue if Movie.objects.filter(id=id).count() > 0 or Movie.objects.filter( title=title).count() > 0: continue Movie(id=id, title=title, genres='|'.join(genres)).save() return Response(status=status.HTTP_200_OK)
def _insert_movies_from_dataset(dataset: pd.DataFrame): """Inserts merged dataset into database. Args: dataset: merged datasheets from movie lens dataset """ # Store movies in a list to bulk create them # Storing genres as an attribute will allow # later to create them in bulk year_re = re.compile(r"\s\((\d\d\d\d)\)") movies_to_create = [] for row in dataset.itertuples(index=False): title = year_re.sub("", row.title) year = year_re.search(row.title) if year: year = year.group(1) movie = Movie( id=row.movieId, title=title, year=year, score=row.rating, link=IMDB_URL.format(row.imdbId), ) movie._genres = row.genres movies_to_create.append(movie) Movie.objects.bulk_create(movies_to_create) # Bulk create M2M to improve performance # See https://stackoverflow.com/a/10116452/9682496 for reference ThroughModel = Movie.genres.through genres = {} genres_to_add = [] with transaction.atomic(): for movie in movies_to_create: for genre in movie._genres.split("|"): if not genre in genres: genres[genre] = Genre.objects.create(name=genre) genres_to_add.append( ThroughModel(movie_id=movie.id, genre_id=genres[genre].id)) ThroughModel.objects.bulk_create(genres_to_add)
def new_movie(request): title = request.data.get('title') genres = request.data.get('genres') plot = request.data.get('plot', None) url = request.data.get('url', None) director = request.data.get('director', None) casting = request.data.get('casting', None) Movie(title=title, genres='|'.join(genres), plot=plot, url=url, director=director, casting='|'.join(casting)).save()
def movies(request): if request.method == 'GET': id = request.GET.get('id', request.GET.get('movie_id', None)) title = request.GET.get('title', None) genre = request.GET.get('genre', None) movies = Movie.objects.all() if id: movies = movies.filter(pk=id) if title: movies = movies.filter(title__icontains=title) if genre: movies = movies.filter(genres__icontains=genre) serializer = MovieSerializer(movies, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'DELETE': movie = Movie.objects.all() movie.delete() return Response(status=status.HTTP_200_OK) if request.method == 'POST': movies = request.data.get('movies', None) for movie in movies: id = movie.get('id', None) title = movie.get('title', None) genres = movie.get('genres', None) if not (id and title and genres): continue if Movie.objects.filter(id=id).count() > 0 or Movie.objects.filter( title=title).count() > 0: continue Movie(id=id, title=title, genres='|'.join(genres)).save() return Response(status=status.HTTP_200_OK) if request.method == 'PUT': movie = Movie.objects.get(id=request.data.get('id')) serializer = MovieSerializer(movie, data=request.data) if serializer.is_valid(): serializer.update(movie, request.data) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def movies(request): if request.method == 'GET': # Search Movies By Title if request.GET.get('key') == 'title': id = request.GET.get('id', request.GET.get('movie_id', None)) title = request.GET.get('title', None) movies = Movie.objects.all() if id: movies = movies.filter(pk=id) if title: movies = movies.filter(title__icontains=title) # Search Movies By Genres else: genre = request.GET.get('genre', 'All') if genre != 'All': movies = Movie.objects.all().filter(genres__icontains=genre) else: movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'POST': movies = request.data.get('movies', None) for movie in movies: id = movie.get('id', None) title = movie.get('title', None) genres = movie.get('genres', None) if not (id and title and genres): continue if Movie.objects.filter(id=id).count() > 0 or Movie.objects.filter( title=title).count() > 0: continue Movie(id=id, title=title, genres='|'.join(genres)).save() return Response(status=status.HTTP_200_OK) if request.method == 'DELETE': movie = Movie.objects.all() movie.delete() return Response(status=status.HTTP_200_OK)
def movie_list(request): if request.method == 'GET': movies = Movie.objects.all() total = len(movies) # recommend by age, occupation, gender age = request.GET.get("age", None) username = request.GET.get("username", None) occupation = request.GET.get("occupation", None) gender = request.GET.get("gender", None) limit = int(request.GET.get("limit", 10)) start = int(request.GET.get("start", 0)) regex = request.GET.get("regex", None) if regex: movies = Movie.objects.filter(title__contains=regex)[:5] serializer = MovieSerializer(movies, many=True) data = {"data": serializer.data} return Response(data=data, status=status.HTTP_200_OK)\ if username: movies = [] user = get_object_or_404(User, username=username) for rating in user.ratings.all().order_by("-rating")[start:limit]: movies.append(rating.movie) serializer = MovieSerializer(movies, many=True) data = { "data": serializer.data, "total": total, "start": start, "limit": limit } return Response(data=data, status=status.HTTP_200_OK) elif age: rec = get_object_or_404(Recommendation, type="age", value=age) total = len(rec.movies.all()) movies = rec.movies.all()[start:start + limit] serializer = MovieSerializer(movies, many=True) data = { "data": serializer.data, "total": total, "start": start, "limit": limit, "value": age } return Response(data=data, status=status.HTTP_200_OK) elif occupation: rec = get_object_or_404(Recommendation, type="occupation", value=occupation) total = len(rec.movies.all()) movies = rec.movies.all()[start:start + limit] serializer = MovieSerializer(movies, many=True) data = { "data": serializer.data, "total": total, "start": start, "limit": limit, "value": occupation } return Response(data=data, status=status.HTTP_200_OK) elif gender: rec = get_object_or_404(Recommendation, type="gender", value=gender) total = len(rec.movies.all()) movies = rec.movies.all()[start:start + limit] serializer = MovieSerializer(movies, many=True) data = { "data": serializer.data, "total": total, "start": start, "limit": limit, "value": gender } return Response(data=data, status=status.HTTP_200_OK) else: # filter movies id = request.GET.get('id', request.GET.get('movie_id', None)) title = request.GET.get('title', None) genres = request.GET.get("genres", None) if id: movies = movies.filter(pk=id) if title: movies = movies.filter(title__icontains=title) if genres: genres = genres.split(",") for genre in genres: movies = movies.filter(genres__icontains=genre) # sort by ratings, views sort_ratings = request.GET.get("sort_ratings", None) sort_views = request.GET.get("sort_views", None) if sort_ratings: if sort_ratings == "1": movies = movies.order_by("-avg_rating") else: movies = movies.order_by("avg_rating") if sort_views: if sort_views == "1": movies = movies.order_by("-rating_count") else: movies = movies.order_by("rating_count") serializer = MovieSerializer(movies, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'POST': movies = request.data.get('movies', []) for movie in movies: id = movie.get('id', None) title = movie.get('title', None) genres = movie.get('genres', None) if not (id and title and genres): continue if Movie.objects.filter(id=id).count() > 0 or Movie.objects.filter( title=title).count() > 0: continue Movie(id=id, title=title, genres='|'.join(genres)).save() story = request.data.get("story", None) if story: for s in story: movie_id = s.get("movie_id", None) st = s.get("story", None) movie = get_object_or_404(Movie, id=movie_id) movie.story = st movie.save() return Response(status=status.HTTP_200_OK)
def add_movies(): for movie in movies: temp_movie = Movie() temp_movie.title = movie.get('title') temp_movie.release_date = movie.get('release_date') temp_movie.cast = movie.get('cast') temp_movie.background = movie.get('background') temp_movie.poster = movie.get('poster') temp_movie.director = movie.get('director') temp_movie.synopsis = movie.get('synopsis') new_page = CommentPage() new_page.save() temp_movie.comment_page = new_page temp_movie.save() for genre in movie.get('genres'): try: temp_genre = Genre.objects.get(name=genre) temp_genre.movies.add(temp_movie) except Genre.DoesNotExist: print(genre)
def movies(request): ''' 영화를 CRUD할 수 있는 URL ''' try: if request.method == 'GET': movie_id = request.GET.get('id', request.GET.get('movie_id', None)) title = request.GET.get('title', None) category = request.GET.get('category', None) keyword = request.GET.get('keyword', None) sort = request.GET.get('sort', 1) page = request.GET.get('page', 1) movie_all = Movie.objects.all() # querySet 으로 반환됨 if movie_id: movie_all = movie_all.filter(pk=movie_id) if title: movie_all = movie_all.filter(title__icontains=title) if category == 'genre': if keyword != 'Total': genre_obj = Genre.objects.get(name=keyword) movie_all = movie_all.filter(genres=genre_obj) # 정렬방식 if sort: if int(sort) == 1: # 평균평점 순(높은순) default movie_all = movie_all.order_by( F('vote_average').desc(nulls_first=False)) elif int(sort) == 2: # 조회순 movie_all = movie_all.order_by( F('view_cnt').desc(nulls_first=False)) elif int(sort) == 3: # 최신순 movie_all = movie_all.order_by( F('release_date').desc(nulls_first=False)) # 페이지 별로 나눠서 영화 정보 받아오기 if page: # 한페이지에 10개씩. 1페이지 0~9, 2페이지 10~19, ... start= 10*(page-1), end=start+10 # 10페이지 100 1 0~99 2 100~199 # 영화 총개수: 3883. page=39이면 3800:3900 인덱스 에러. page = int(page) start = 50 * (page - 1) end = start + 50 if len(movie_all[start:]) < 50: movie_all = movie_all[start:] movie_all = movie_all[start:end] serializer = MovieSerializer(movie_all, many=True) return JsonResponse( { 'status': status.HTTP_200_OK, 'result': serializer.data }, safe=False) if request.method == 'DELETE': movie = Movie.objects.all() movie.delete() return JsonResponse({'status': status.HTTP_200_OK}) if request.method == 'POST': movie_all = request.data.get('movies', None) for movie in movie_all: movie_id = movie.get('id', None) movie_id = int(movie_id) title = movie.get('title', None) genres = movie.get('genres', None) try: if title[-1] == '"': only_title = title[1:len(title) - 7] year = int(title[len(title) - 6:len(title) - 2]) elif title[-1] == " ": only_title = title[:len(title) - 8] year = int(title[len(title) - 6:len(title) - 2]) else: only_title = title[:len(title) - 6] year = int(title[len(title) - 5:len(title) - 1]) except ValueError: only_title = title year = 0 if not (movie_id and title and genres): continue # if Movie.objects.filter(id=id).count() > 0 or Movie.objects.filter(title=title).count() > 0: # continue Movie(id=movie_id, title=only_title, year=year, genres='|'.join(genres)).save() return JsonResponse({'status': status.HTTP_200_OK}) except Exception: return JsonResponse({ 'status': status.HTTP_500_BAD_REQUEST, 'msg': str(Exception) }) return JsonResponse({ 'status': status.HTTP_400_BAD_REQUEST, 'msg': 'Invalid Request Method' })
def movies(request): if request.method == 'GET': id = request.GET.get('id', request.GET.get('movie_id', None)) title = request.GET.get('title', None) genres = request.GET.get('genres',None) sort = request.GET.get('sort',None) sel = request.GET.get('sel',None) selGender = request.GET.get('selGender',None) selAge = request.GET.get('selAge',None) selOccupation = request.GET.get('selOccupation',None) counting = request.GET.get('counting', None) movies = Movie.objects.all() ratings = Rating.objects.all() if id: #### 알고리즘 - 유사 영화 #### li = list() mlist = '' idx1 = 0 for m in movies : gen = m.genres.split('|') tmp = ' ' for s in gen : tmp += s + ' ' tmp = tmp.strip() li.append({'title' : m.title, 'idx' : idx1, 'genres' : tmp}) idx1 += 1 df = pd.DataFrame(li) cv = CountVectorizer() count_matrix = cv.fit_transform(df['genres']) cosine_sim = cosine_similarity(count_matrix) #### 클릭한 영화의 제목 찾기 #### ms = Movie.objects.all().filter(id=id) mtitle = '' for m in ms : mtitle = m.title movie_user_likes = mtitle movie_index = get_index_from_title(df, movie_user_likes) similar_movies = list(enumerate(cosine_sim[movie_index])) sorted_similar_movies = sorted(similar_movies, key=lambda x:x[1],reverse=True)[1:] i=0 for element in sorted_similar_movies: i = i+1 if i != 5 : mlist += get_title_from_index(df, element[0]) + "|" else : mlist += get_title_from_index(df, element[0]) if i>=5: break ############################ movies = movies.filter(pk=id) movies.update( mlist=mlist ) if title: movies = movies.filter(title__icontains=title) if genres: movies = movies.filter(genres__icontains=genres) # 성별 검색 if sel == '1' : obj = usermovieGender_sql(selGender, int(counting)) size = 0 repeat = 0 if( len(obj) > 5 ) : repeat = 5 elif len(obj) == 0 : repeat = 1 else : repeat = len(obj) for idx in range( repeat ) : if( len(obj) == 0 ) : movies = [] break if size == 0: movies = movies.filter( pk=obj[0]['m_id'] ) movies.update( counting=obj[idx]['cnt'] ) size = size + 1 else : m = Movie.objects.filter(pk=obj[idx]['m_id']) m.update(counting=obj[idx]['cnt']) movies = movies.union(m) movies = sorted(movies, key=lambda movie: movie.counting, reverse=True) # 나이 검색 if sel == '2' : obj = usermovieAge_sql(selAge, int(counting)) size = 0 repeat = 0 if( len(obj) > 5 ) : repeat = 5 elif len(obj) == 0 : repeat = 1 else : repeat = len(obj) for idx in range( repeat ) : if( len(obj) == 0 ) : movies = [] break if size == 0: movies = movies.filter( pk=obj[0]['m_id'] ) movies.update( counting=obj[idx]['cnt'] ) size = size + 1 else : m = Movie.objects.filter(pk=obj[idx]['m_id']) m.update(counting=obj[idx]['cnt']) movies = movies.union(m) movies = sorted(movies, key=lambda movie: movie.counting, reverse=True) # 직업 검색 if sel == '3' : obj = usermovieOccupation_sql(selOccupation, int(counting)) size = 0 repeat = 0 if( len(obj) > 5 ) : repeat = 5 elif len(obj) == 0 : repeat = 1 else : repeat = len(obj) for idx in range( repeat ) : if( len(obj) == 0 ) : movies = [] break if size == 0: movies = movies.filter( pk=obj[0]['m_id'] ) movies.update( counting=obj[idx]['cnt'] ) size = size + 1 else : m = Movie.objects.filter(pk=obj[idx]['m_id']) m.update(counting=obj[idx]['cnt']) movies = movies.union(m) movies = sorted(movies, key=lambda movie: movie.counting, reverse=True) #rating 순 if(sort == '1'): movies = sorted(movies, key=lambda movie: movie.ratings / movie.viewCnt if movie.viewCnt != 0 else 0,reverse=True) if(sort == '2'): movies = sorted(movies, key=lambda movie: movie.viewCnt,reverse=True) serializer = MovieSerializer(movies, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'DELETE': movie = Movie.objects.all() movie.delete() return Response(status=status.HTTP_200_OK) if request.method == 'POST': movieDb = Movie.objects.all() movieDb.delete() movies = request.data.get('movies', None) for movie in movies: id = movie.get('id', None) title = movie.get('title', None) genres = movie.get('genres', None) ratings = movie.get('ratings', None) viewCnt = movie.get('viewCnt', None) imgpath = movie.get('imgpath', None) overview = movie.get('overview', None) production_companies = movie.get('production_companies', None) production_countries = movie.get('production_countries', None) runtime = movie.get('runtime', None) Movie(id=id, title=title, ratings=ratings, viewCnt=viewCnt, genres='|'.join(genres), counting=0, mlist='', imgpath=imgpath, overview= overview,production_companies=production_companies, production_countries=production_countries ,runtime=runtime).save() return Response(status=status.HTTP_200_OK)
def movies(request): if request.method == 'GET': # movie detail로 respon함. id = request.GET.get('id') if id: movie = get_object_or_404(Movie, pk=id) serializer = MovieDetailSerializer(movie) return Response(data=serializer.data, status=status.HTTP_200_OK) title = request.GET.get('title', None) genre = request.GET.get('genre', None) movies = Movie.objects.all() # profile에 있는 유저정보에서 나이, 성별, 직업을 가져오기 age = request.GET.get('age', None) gender = request.GET.get('gender', None) occupation = request.GET.get('occupation', None) ratings = Rating.objects.all() if title: movies = movies.filter(title__icontains=title) if genre: movies = movies.filter(genres__icontains=genre) # rating에서 user와 movie 오브젝트를 가져와서 리스트로 만든 후 중복제거 && id 순으로 정렬 if age: movies = sorted(list( set([ rate.movie for rate in ratings if (rate.user.profile.age == int(age)) ])), key=lambda x: x.id) if gender: movies = sorted(list( set([ rate.movie for rate in ratings if (rate.user.profile.gender == gender) ])), key=lambda x: x.id) if occupation: movies = sorted(list( set([ rate.movie for rate in ratings if (rate.user.profile.occupation == occupation) ])), key=lambda x: x.id) serializer = MovieListSerializer(movies, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'DELETE': movie = Movie.objects.all() movie.delete() return Response(status=status.HTTP_200_OK) if request.method == 'POST': # ID로 접근하면 UPDATE id = request.data.get('id') movies = request.data.get('movies', None) for movie in movies: id = movie.get('id', None) title = movie.get('title', None) genres = movie.get('genres', None) poster_url = movie.get('poster_url') # if not (id and title and genres): # continue # if Movie.objects.filter(id=id).count() > 0 or Movie.objects.filter(title=title).count() > 0: # continue Movie(id=id, title=title, genres='|'.join(genres), poster_url=poster_url).save() return Response(status=status.HTTP_200_OK)
def save_movie_from_row(movie_row): movie = Movie() movie.id = movie_row[0] movie.title = movie_row[1] movie.save()
def movie(): return Movie(name='movie', year=1999, country='USA')
def movies(request): if request.method == 'GET': id = request.GET.get('id', request.GET.get('movie_id', None)) title = request.GET.get('title', None) genre = request.GET.get('genre', None) occupation = request.GET.get('occupation', None) gender = request.GET.get('gender', None) age = request.GET.get('age', None) year = request.GET.get('year', None) overview = request.GET.get('overview', None) poster_path = request.GET.get('poster_path', None) movies = Movie.objects.all() if id: movies = movies.filter(pk=id) if title: movies = movies.filter(title__icontains=title) if genre: genres = genre.split(',') print(genres) for i in range(len(genres) - 1): movies = movies.filter(genres__icontains=genres[i]) if occupation: movies = movies.filter( rating__user__profile__occupation=occupation ).distinct().annotate(count=Count( Case(When(rating__user__profile__occupation=occupation, then=1)))).order_by('-count') # if gender : # movies = movies.annotate( # mcount= Count( # Case( # When ( # rating__user__profile__gender = 'M', # then=1 # ) # ) # ), # fcount = Count( # Case( # When ( # rating__user__profile__gender = 'F', # then=1 # ) # ) # ), # diff = F('mcount')-F('fcount') # ) # if gender == 'M' : # movies = movies.filter(diff__gt = 0).order_by('-diff') # if gender == 'F' : # movies = movies.filter(diff__lt = 0).order_by('diff') # if age : # movies = movies.annotate( # ageCount = Count( # Case( # When( # rating__user__profile__age = age, # then = 1 # ) # ) # ) # ).filter(ageCount__gt = 0).order_by('-ageCount') # movies = movies serializer = MovieSerializer(movies, many=True) data = serializer.data return Response(data=data, status=status.HTTP_200_OK) if request.method == 'DELETE': id = request.GET.get('id', None) selected_movies = request.GET.getlist('selected[]', None) movie = Movie.objects.all() if id: movie = movie.get(id=id) if selected_movies: query = Q() for selected_movie in selected_movies: query = query | Q(id=selected_movie) movie = movie.filter(query) movie.delete() return Response(status=status.HTTP_200_OK) if request.method == 'POST': movies = request.data.get('movies', None) for key in movies: id = movies[key].get('id', None) title = movies[key].get('title', None) genres = movies[key].get('genres', None) rusercount = movies[key].get('rusercount', None) rrating = movies[key].get('rrating', None) rgender = movies[key].get('rgender', None) academiceducatorcount = movies[key].get('academiceducatorcount', None) artistcount = movies[key].get('artistcount', None) clericaladmincount = movies[key].get('clericaladmincount', None) collegegradstudentcount = movies[key].get( 'collegegradstudentcount', None) customerservicecount = movies[key].get('customerservicecount', None) doctorhealthcarecount = movies[key].get('doctorhealthcarecount', None) executivemanagerialcount = movies[key].get( 'executivemanagerialcount', None) farmercount = movies[key].get('farmercount', None) homemakercount = movies[key].get('homemakercount', None) K12studentcount = movies[key].get('K12studentcount', None) lawyercount = movies[key].get('lawyercount', None) programmercount = movies[key].get('programmercount', None) retiredcount = movies[key].get('retiredcount', None) salesmarketingcount = movies[key].get('salesmarketingcount', None) scientistcount = movies[key].get('scientistcount', None) selfemployedcount = movies[key].get('selfemployedcount', None) technicianengineercount = movies[key].get( 'technicianengineercount', None) tradesmancraftsmancount = movies[key].get( 'tradesmancraftsmancount', None) unemployedcount = movies[key].get('unemployedcount', None) writercount = movies[key].get('writercount', None) age1count = movies[key].get('age1count', None) age18count = movies[key].get('age18count', None) age25count = movies[key].get('age25count', None) age35count = movies[key].get('age35count', None) age45count = movies[key].get('age45count', None) age50count = movies[key].get('age50count', None) age56count = movies[key].get('age56count', None) othercount = movies[key].get('othercount', None) if not (id and title and genres): continue if Movie.objects.filter(id=id).count() > 0 or Movie.objects.filter( title=title).count() > 0: continue n = len(title) year = title[n - 5:n - 1] # 괄호 검색 title = title[:-6] if '(' in title: title = title.split('(')[0] if '.' in title: title = title.split('.')[0] # , 검색 if ',' in title: title = title.split(',')[0] tmurl = "https://api.themoviedb.org/3/search/movie?api_key=8f03cc345840b05e82681223f1ff0d74&language=en-US&query={}&page=1&year={}".format( title, year) results = requests.get(tmurl).json() # 만약 total_result 가 0이라면 제목으로만 다시검색 if results['total_results'] == 0: tmurl = "https://api.themoviedb.org/3/search/movie?api_key=8f03cc345840b05e82681223f1ff0d74&language=en-US&query={}&page=1".format( title) results = requests.get(tmurl).json() # 그래도 없다면 패스 if results['total_results'] == 0: movie = Movie(id=id, title=title, genres='|'.join(genres), tmdb_id=1, overview='', year=year, poster_path='').save() continue # results 에 결과 저장 results = results['results'][0] overview = results['overview'] # https://developers.themoviedb.org/3/search/search-movies # https://developers.themoviedb.org/3/movies/get-movie-details # api_key=8f03cc345840b05e82681223f1ff0d74 tmdb_id = results['id'] if results['poster_path'] == None: results['poster_path'] = "" poster_path = 'https://image.tmdb.org/t/p/original' + results[ 'poster_path'] # example # model -> Movie -> item 필드추가하면됨 # item = results['item'] # movie=Movie(id=id, item = item) movie = Movie(id=id, title=title, genres='|'.join(genres), rusercount=rusercount, rrating=rrating, rgender=rgender, othercount=othercount, academiceducatorcount=academiceducatorcount, artistcount=artistcount, clericaladmincount=clericaladmincount, collegegradstudentcount=collegegradstudentcount, customerservicecount=customerservicecount, doctorhealthcarecount=doctorhealthcarecount, executivemanagerialcount=executivemanagerialcount, farmercount=farmercount, homemakercount=homemakercount, K12studentcount=K12studentcount, lawyercount=lawyercount, programmercount=programmercount, retiredcount=retiredcount, salesmarketingcount=salesmarketingcount, scientistcount=scientistcount, selfemployedcount=selfemployedcount, technicianengineercount=technicianengineercount, tradesmancraftsmancount=tradesmancraftsmancount, unemployedcount=unemployedcount, writercount=writercount, age1count=age1count, age18count=age18count, age25count=age25count, age35count=age35count, age45count=age45count, age50count=age50count, age56count=age56count, tmdb_id=tmdb_id, overview=overview, year=year, poster_path=poster_path).save() return Response(status=status.HTTP_200_OK)
def movies(request): if request.method == 'GET': id = request.GET.get('id', request.GET.get('movie_id', None)) isUpdateRating = request.GET.get('isUpdateRating', None) title = request.GET.get('title', None) genres = request.GET.get('genres', None) sortBy = request.GET.get('sortBy', None) sortingBy = request.GET.get('sortingBy', None) agesItems = ["-ㅤ", "0~19", "20~29", "30~39", "40~"] genderItems = ["-ㅤㅤ", "Male", "Female"] movies = Movie.objects.all() if id and isUpdateRating: movies = movies.filter(pk=id) serializer = MovieDetailSerializer(movies, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if id: movies = movies.filter(pk=id) update_movie_view_count(movie_id=id) serializer = MovieDetailSerializer(movies, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if title: movies = movies.filter(title__icontains=title) if genres: if genres == "All": genres = "" movies = movies.filter(genres__icontains=genres) if sortBy: if sortBy == "조회순": movies = movies.order_by('-views_count') elif sortBy == "평점순": movies = movies.order_by('-average_rating') if sortingBy: if sortingBy in agesItems: if sortingBy == "0~19": movies = sorted(movies, key=lambda i: i.age10 / (i.total_rater if i.total_rater != 0 else 1), reverse=True) elif sortingBy == "20~29": movies = sorted(movies, key=lambda i: i.age20 / (i.total_rater if i.total_rater != 0 else 1), reverse=True) elif sortingBy == "30~39": movies = sorted(movies, key=lambda i: i.age30 / (i.total_rater if i.total_rater != 0 else 1), reverse=True) elif sortingBy == "40~": movies = sorted(movies, key=lambda i: i.age40 / (i.total_rater if i.total_rater != 0 else 1), reverse=True) else: movies = Movie.objects.all() elif sortingBy in genderItems: if sortingBy == "Male": movies = sorted(movies, key=lambda i: i.male / (i.total_rater if i.total_rater != 0 else 1), reverse=True) elif sortingBy == "Female": movies = sorted(movies, key=lambda i: i.female / (i.total_rater if i.total_rater != 0 else 1), reverse=True) else: occupation_map = { 'other': 0, 'academic/educator': 1, 'artist': 2, 'clerical/admin': 3, 'college/grad student': 4, 'customer service': 5, 'doctor/health care': 6, 'executive/managerial': 7, 'farmer': 8, 'homemaker': 9, 'K-12 student': 10, 'lawyer': 11, 'programmer': 12, 'retired': 13, 'sales/marketing': 14, 'scientist': 15, 'self-employed': 16, 'technician/engineer': 17, 'tradesman/craftsman': 18, 'unemployed': 19, 'writer': 20 } index = "job" + (str(occupation_map[sortingBy]) if len(str(occupation_map[sortingBy])) != 1 else "0" + str(occupation_map[sortingBy])) movies = sorted(movies, key=lambda i: getattr(i, index) / (i.total_rater if i.total_rater != 0 else 1), reverse=True) serializer = MovieSerializer(movies, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'DELETE': movie = Movie.objects.all() movie.delete() return Response(status=status.HTTP_200_OK) if request.method == 'POST': movies = request.data.get('movies', None) for movie in movies: id = movie.get('id', None) title = movie.get('title', None) genres = movie.get('genres', None) if not (id and title and genres): continue if Movie.objects.filter(id=id).count() > 0 or Movie.objects.filter( title=title).count() > 0: continue Movie(id=id, title=title, genres='|'.join(genres)).save() return Response(status=status.HTTP_200_OK)
def movies(request): if request.method == 'GET': id = request.GET.get('id', request.GET.get('movie_id', None)) title = request.GET.get('title', None) genre = request.GET.get('genre', None) order = request.GET.get('order', None) age = request.GET.get('age', None) gender = request.GET.get('gender', None) occupation = request.GET.get('occupation', None) movies = Movie.objects.all() if age or gender or occupation: profile = Profile.objects.all() profile = profile.values('id') if age: if age == '10': profile = profile.filter(age__lt=18) elif age == '20': profile = profile.filter(age__range=(19, 28)) elif age == '30': profile = profile.filter(age__range=(39, 48)) elif age == '40': profile = profile.filter(age__range=(39, 48)) elif age == '50': profile = profile.filter(age__gt=49) if gender: if gender == 'M': profile = profile.filter(gender='M') elif gender == 'F': profile = profile.filter(gender='F') if occupation: profile = profile.filter(occupation__icontains=occupation) movies = movies.filter(rating__userid__in=profile) if not (id or title or genre or order or age or gender or occupation): movienum = [] for movie in movies: movienum.append(movie.id) rand = random.sample(movienum, 10) movies = movies.filter(pk__in=rand) movies = movies.annotate(view_cnt=Count('rating')).annotate(average_rating=Avg('rating__rating')) if id: movies = movies.filter(pk=id) if title: movies = movies.filter(title__icontains=title) if genre: movies = movies.filter(genres__icontains=genre) if order: if order == 'avgrating': movies = movies.order_by('-average_rating') elif order == 'countrating': movies = movies.order_by('-view_cnt') serializer = MovieSerializer(movies, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'DELETE': movieid = request.GET.get('id', None) if movieid: movie = Movie.objects.get(pk=movieid) movie.delete() return Response(status=status.HTTP_200_OK) if request.method == 'PUT': id = request.GET.get('id', None) title = request.GET.get('title', None) genres = request.GET.get('genres', None) movies = request.data.get('movies', None) for movie in movies: id = movie.get('id', None) title = movie.get('title', None) genres = movie.get('genres', None) Movie.objects.filter(pk=id).update(title=title, genres='|'.join(genres)) if id: Movie.objects.filter(pk=id).update(title=title, genres=genres) return Response(status=status.HTTP_200_OK) if request.method == 'POST': movies = request.data.get('movies', None) for movie in movies: id = movie.get('id', None) title = movie.get('title', None) genres = movie.get('genres', None) if not (id and title and genres): continue if Movie.objects.filter(id=id).count() > 0 or Movie.objects.filter(title=title).count() > 0: continue Movie(id=id, title=title, genres='|'.join(genres)).save() return Response(status=status.HTTP_200_OK)
def setUp(self): # create movie self.movie = Movie(name="The Space Between Us", year_of_release=2017) self.movie.save()
def setUp(self): self.movie = Movie(name="Split", year_of_release=2016) self.movie.save()
def movies(request): if request.method == 'GET': id = request.GET.get('id', request.GET.get('movie_id', None)) title = request.GET.get('title', None) viewcnt = request.GET.get('viewcnt', None) rating = request.GET.get('rating', None) genres = request.GET.get('select', None) movie_content = request.GET.get('moviecontent') if movie_content: cnx = sqlite3.connect('db.sqlite3') query = "Select * from api_moviecontent where id =" + movie_content result = pd.read_sql_query(query, cnx) request_data = [] src = result['posterUrl'][0] ImdbLink = result['ImdbLink'][0] Director = result['Director'][0] Writers = result['Writers'][0] Summary = result['Summary'][0] request_data.append({ "src": src, "ImdbLink": ImdbLink, "Director": Director, "Writers": Writers, "Summary": Summary }) return Response(data=request_data, status=status.HTTP_200_OK) movies = Movie.objects.all() if id: movies = movies.filter(pk=id) if title: movies = movies.filter(title__icontains=title) if genres: genres = genres.split(',') for genre in genres: movies = movies.filter(genres__icontains=genre) # movies = movies.filter(genre__icontains=genre) if viewcnt: if viewcnt == "asc": viewcnt = 'viewCnt' elif viewcnt == 'desc': viewcnt = '-viewCnt' if rating: if rating == "asc": rating = 'rating' elif rating == 'desc': rating = '-rating' if viewcnt or rating: if viewcnt and rating: movies = movies.order_by(viewcnt, rating) elif viewcnt: movies = movies.order_by(viewcnt) elif rating: movies = movies.order_by(rating) serializer = MovieSerializer(movies, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) if request.method == 'DELETE': movie = Movie.objects.all() movie.delete() return Response(status=status.HTTP_200_OK) if request.method == 'POST': movies = request.data.get('movies', None) for movie in movies: id = movie.get('id', None) title = movie.get('title', None) genres = movie.get('genres', None) if not (id and title and genres): continue if Movie.objects.filter(id=id).count() > 0 or Movie.objects.filter( title=title).count() > 0: continue ratings = Rating.objects.all() ratings = ratings.filter(movieid__exact=id) query_set = ratings.aggregate(Avg('rating')) rating = query_set['rating__avg'] if not rating: rating = 0 if rating: rating = round(rating, 1) Movie(id=id, title=title, genres='|'.join(genres), rating=rating).save() return Response(status=status.HTTP_200_OK) if request.method == 'PUT': movieid = request.GET.get('movieid', None) movie = Movie.objects.get(id=movieid) movie.viewCnt = movie.viewCnt + 1 movie.save() return Response(data=movie.viewCnt, status=status.HTTP_200_OK)