def movies(request): if request.method == 'GET': movie_list = Movie.objects.order_by('-release_date').all() serializer = MovieSerializer(movie_list, many=True) return Response(serializer.data) # TODO: 관리자 확인 elif request.method == 'POST': # 영화 정보 생성 genres = Genre.objects.filter(id__in=request.data['genres']) movie = Movie() movie.original_title = request.data['original_title'] movie.title = request.data['title'] movie.description = request.data['description'] movie.poster_url = request.data['poster_url'] movie.release_date = request.data['release_date'] movie.trailer_url = request.data['trailer_url'] movie.save() for genre in genres: movie.genres.add(genre) serializer = MovieSerializer(movie, many=False) return Response(serializer.data)
def results(request): m = Movie() if request.GET.get('q') is not None: searchname = request.GET.get('q') movieData = m.getMovieData(searchname) return render(request, 'movie/home.html', {'movieData': movieData, 'search': True}) else: return render(request, 'movie/home.html')
def save_movie_in_db(self, movie_data): try: movie = Movie.objects.get(name = movie_data['movie_title']) except: movie = Movie(name = movie_data['movie_title'], imdb_rating = movie_data['imdb_rating'], summary_text = movie_data['summary_text']) movie.save()
def home(request): all_movies = get_movies_image( 'https://www.vmovier.com/apiv3/index/getBanner') all_images = [] for movie in all_movies: image = movie.get('image') images = str(image) all_images.append(images) movies = get_movies( 'https://www.vmovier.com/apiv3/post/getPostInCate?cateid=0&p=1') try: for movie in movies: m_movie = Movie() title = movie.get('title') m_movie.m_title = title ima = movie.get('image') m_movie.m_image = ima duration = movie.get('duration') m_movie.m_duration = duration appfutitle = movie.get('appfutitle') m_movie.m_appfutitle = appfutitle postid = movie.get("postid") m_movie.m_positid = postid m_movie.save() except Exception as e: a_movies = Movie.objects.all() return render(request, 'home.html', context=locals()) a_movies = Movie.objects.all() return render(request, 'home.html', context=locals())
def list_create_view(request): if request.method == "GET": movies = Movie.objects.all() response = HttpResponse(serializers.serialize("json", movies), content_type="application/json") return response elif request.method == "POST": data = json.loads(request.body.decode("utf-8")) movie = Movie(title=data["title"]) movie.save() return HttpResponse(serializers.serialize("json", [movie]), status=201, content_type="application/json")
def mutate(self, root, info, input=None): ok = True actors = [] for actor_input in input.actors: actor = Actor.objects.get(pk=actor_input.id) if actor is None: return CreateMovie(ok=False, movie=None) actors.append(actor) movie_instance = Movie(title=input.title, year=input.year) movie_instance.save() movie_instance.actors.set(actors) return CreateMovie(ok=ok, movie=movie_instance)
def list_create_view(request): if request.method == "GET": movies = Movie.objects.all() response = HttpResponse(serializers.serialize("json", movies), content_type="application/json") return response elif request.method == "POST": data = json.loads(request.body.decode("utf-8")) movie = Movie(title=data['title']) movie.save() return HttpResponse(serializers.serialize("json", [movie]), status=201, content_type="application/json")
def list_or_create_view(request): if request.method == 'GET': movies = Movie.objects.all() return HttpResponse(serializers.serialize('json', movies), content_type='applcation/json', status=200) elif request.method == 'POST': data = json.loads(request.body.decode("utf-8")) movie = Movie(title=data['title']) movie.save() return HttpResponse(serializers.serialize("json", [movie]), content_type="application/json", status=201) else: return HttpResponse(status=404)
def save_to_db(title, image, overview, popularity, vote_average, release_date, year, genre_list): movie = Movie(name=title, image=image, category=get_category(year), description=overview, vote_average=vote_average, popularity=popularity, release_date=release_date) movie.save() for x in genre_list: MovieGenre(movie=Movie.objects.get(id=movie.id), genre=Genre.objects.get(genre_pk=x)).save()
def save(self): try: movie = Movie( name=self.validated_data['name'], description=self.validated_data['description'], created_by=self.validated_data['created_by'], ) movie.save() return movie except KeyError: raise serializers.ValidationError({ "response": "You must have a name, some content, and created by." })
def pachong2(pachong): top250 = pachong() save_list = [] for i in top250: save_list.append(Movie(uid=i[0],name=i[1],info=i[2])) if Movie.objects.count()==0: Movie.objects.bulk_create(save_list)
def get_genre_based_recommendations(self, max_recommendations): """ Returns movie recommendations solely based on personality-genre associations. Returns the recommendations as well as the list of genres for this user. """ genres = get_genres_for_user(self, max_distance=2, max_genres=4) genre_ids = [ g['id'] for g in tmdb.Genres().movie_list()['genres'] if g['name'] in genres ] recommendations = [] args = { 'page': 1, 'vote_count_gte': 20, 'vote_average_gte': 7, 'sort_by': 'vote_average.desc' } # If at least one rule can be applied, predict movies of the associated genres with a high rating. # Otherwise, just predict movies of all genres with high ratings. if len(genres) > 0: args['with_genres'] = genre_ids recs = tmdb.Discover().movie(**args) recommendations += recs['results'] rated_movie_ids = [ r.movie.tmdb_id for r in Rating.objects.filter(rated_by=self) ] # Filter out movies that the user has already seen recommendations = [ r for r in recommendations if r['id'] not in rated_movie_ids ] while len(recommendations) < max_recommendations and recs[ 'page'] < recs['total_pages']: args['page'] += 1 recs = tmdb.Discover().movie(**args) recommendations += recs['results'] # Filter out movies that the user has already seen recommendations = [ r for r in recommendations if r['id'] not in rated_movie_ids ] if len(recommendations) > max_recommendations: recommendations = recommendations[:max_recommendations] # Save recommended Movies in DB for rec in recommendations: movie = Movie.objects.filter(tmdb_id=rec['id']) if not movie.exists(): Movie(tmdb_id=rec['id'], title=rec['title']).save() return recommendations, genres
def movies(request, arg0='', arg1=''): if request.method == "POST": # check if title is given if arg0 == '': response = {"response": False, "error": "search title is missing"} else: movie_data = fetch_movie_data(arg0.replace(" ", "+")) # if title is found if movie_data['Response'] == "True": # if title is not in local db yet if not Movie.objects.filter( imdbID=movie_data['imdbID']).exists(): # save to db save_movie_data(movie_data) response = {"response": True, "result": movie_data} # if title is not in omdb else: response = { "response": False, "error": "title is not found in OMDb" } elif request.method == "GET": if arg0 and arg1 == 'DESC' and Movie.model_field_exists(arg0): response = { "response": True, "result": list(Movie.objects.all().order_by("-" + arg0).values()) } elif arg0 and Movie.model_field_exists(arg0): response = { "response": True, "result": list(Movie.objects.all().order_by(arg0).values()) } else: response = { "response": True, "result": list(Movie.objects.all().values()) } return JsonResponse(response)
def forge(): '''Generate fake data.''' db.create_all() name = 'Han Star' movies = [ { 'title': 'My Neighbor Totoro', 'year': '1988' }, { 'title': 'Dead Poets Society', 'year': '1989' }, { 'title': 'A Perfect World', 'year': '1993' }, { 'title': 'Leon', 'year': '1994' }, { 'title': 'Mahjong', 'year': '1996' }, { 'title': 'Swallowtail Butterfly', 'year': '1996' }, { 'title': 'King of Comedy', 'year': '1999' }, { 'title': 'Devils on the Doorstep', 'year': '1999' }, { 'title': 'WALL-E', 'year': '2008' }, { 'title': 'The Pork of Music', 'year': '2012' }, ] user = User(name=name) db.session.add(user) for m in movies: movie = Movie(title=m['title'], year=m['year']) db.session.add(movie) db.session.commit() click.echo("Done....")
def save_movie(self): # """[summary] # """ homepage = (self.imdb_movie_url if not self.movie_data.get("homepage") else self.movie_data.get("homepage")) rating = (self.imdb_rating if self.imdb_rating else float( self.movie_data.get("vote_average", None))) try: Movie( **{ "title": self.movie_data.get("title", None), "release_date": self.movie_data.get("release_date", None), "runtime": self.movie_data.get("runtime", None), "poster_path": ( f"https://image.tmdb.org/t/p/w500" f"{self.movie_data.get('poster_path', None)}"), "overview": self.movie_data.get("overview", None), "imdb_id": self.movie_data.get("imdb_id", None), "imdb_rating": rating, "imdb_movie_url": self.imdb_movie_url, "homepage": homepage, # 'trailer': self. # 'geners: "resolution": self.get_resolution_from_filename(), "filename": self.filename, }).save() except Exception as err: if "UNIQUE constraint failed: movie_movie.imdb_id" in str(err): movie = Movie.objects.get(imdb_id=self.imdb_id) import ipdb ipdb.set_trace() if self.imdb_rating != movie.imdb_rating: Movie.objects.filter(imdb_id=self.imdb_id).update( **{"imdb_rating": self.imdb_rating}) print( f"{movie.title}'s rating was updated to {self.imdb_rating}" ) else: print( f"{movie.title}'s rating is till: {movie.imdb_rating}") else: raise Exception(err) else: print(f"Saved successfully.")
def setUp(self): self.movie = Movie( title='test', data={'test_data': 'test_value'} ) self.movies = [ Movie( title=f'title{index}', data={ 'test_data': 'other_value', 'special_filter': f'special_value{index}' } ) for index in range(6) ] self.example_get_movie_data = { 'Response': 'True', 'Title': 'Test-man 3 big testing', 'Rating': '5/7', }
def add(data, db_session, username): logger.info(LogMsg.START, username) schema_validate(data, MOVIE_ADD_SCHEMA_PATH) logger.debug(LogMsg.SCHEMA_CHECKED) model_instance = Movie() populate_basic_data(model_instance, username, data.get('tags')) logger.debug(LogMsg.POPULATING_BASIC_DATA) model_instance.description = data.get('description') model_instance.title = data.get('title') model_instance.images = data.get('images') model_instance.director = data.get('director') model_instance.producer = data.get('producer') model_instance.pub_year = data.get('pub_year') model_instance.genre = data.get('genre') model_instance.writer = data.get('writer') db_session.add(model_instance) logger.debug(LogMsg.DB_ADD) logger.info(LogMsg.END, model_to_dict(model_instance)) return model_instance
def get_movie(request): request = json.loads(request.body) global td u_id = request["u_id"] m_id = request["m_id"] title = request["title"] print(title) average_score = -1 expecting_score = -1 if m_id == -1: try: movie = Movie.objects.get(title=title) m_id = movie.m_id print("-----movie exist-----") except Movie.DoesNotExist: movie = Movie(title=title) movie.save() m_id = Movie.objects.get(title=title).m_id print("-----movie does not exist-----") try: rating = Rating.objects.get(movie=m_id, user=u_id) score = rating.rate except Rating.DoesNotExist: score = -1 if m_id <= td.movie_num: if u_id <= td.user_num: expecting_score = td.prediction_result[u_id][m_id] if td.movies.movie_list[m_id].total_rate_num != 0: average_score = td.movies.movie_list[m_id].total_rate / td.movies.movie_list[m_id].total_rate_num jsonData = OrderedDict() jsonData["m_id"] = m_id jsonData["title"] = title jsonData["averageScore"] = average_score jsonData["expectingScore"] = expecting_score jsonData["score"] = score return HttpResponse(json.dumps(jsonData, ensure_ascii=False, indent="\t"), content_type="application/json")
def addmovie(request): form = MovieForm() if request.method == 'POST': # If the form has been submitted... form = MovieForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass m = Movie() m.name = form.cleaned_data['name'] m.sourcefile = form.cleaned_data['url'] m.save() m.download_file() return HttpResponseRedirect('/movies/') # Redirect after POST< return render(request, 'movie/addmovie.html', {'form': form})
def get_movies(self, request, *args, **kwargs): movie = Movie(name="a", director='a', actors='a', types='a', country='a', language='a', date='a', length='a', rate='a', watcher='a', tags='a') movie_json = MovieSerializer(movie) return Response(movie_json.data)
def setUp(self): # 配置更新 app.config.update(TESTING=True, SQLALCHEMY_DATABASE_URI='sqlite:///:memory:') # 创建数据库和表 db.create_all() # 创建测试数据 user = User(name="Test", username='******') user.set_password('123') movie = Movie(title='Test Movie', year='2020') # 使用add_all放管服测试添加多个实例 db.session.add_all([user, movie]) db.session.commit() self.client = app.test_client() # 创建客户端测试 self.runner = app.test_cli_runner() # 创建测试命令运行器
def movie_add(): form = MovieForm() if form.validate_on_submit(): data = form.data file_logo = secure_filename(form.logo.data.filename) if not os.path.exists(app.config["UP_DIR"]): os.makedirs(app.config["UP_DIR"]) os.chmod(app.config["UP_DIR"], "rw") logo = change_filename(file_logo) form.logo.data.save(app.config["UP_DIR"] + logo) movies = Movie( title = data["title"], url = data["url"], description = data["info"], star = data["star"], logo = logo, tag_id = data["tag_id"], length = data["length"], area = data["area"], release_time = data["release_time"], play_num = 0, comment_num = 0 ) db.session.add(movies) db.session.commit() flash("添加电影成功", "OK") # 添加操作日志 operatelog = OperateLog( admin_id=session["admin_id"], ip=request.remote_addr, reason="添加电影:" + data["title"] ) db.session.add(operatelog) db.session.commit() return redirect(url_for("admin.movie_add")) return render_template("admin/movie_add.html", form=form)
def get_all(data, db_session, username): logger.info(LogMsg.START, username) if data.get('sort') is None: data['sort'] = ['creation_date-'] result = Movie.mongoquery( db_session.query(Movie)).query(**data).end().all() final_res = [] rated_movies = users_rated_movie_ids(username, db_session) for item in result: model_dict = model_to_dict(item) model_dict['rated_by_user'] = False if item.id in rated_movies: model_dict['rated_by_user'] = True final_res.append(model_dict) logger.debug(LogMsg.GET_SUCCESS, final_res) logger.info(LogMsg.END) return final_res
def index(): """首页 增加""" if request.method == 'POST': # post请求 获取表单 if not current_user.is_authenticated: # 未认证 return redirect(url_for('login')) title = request.form.get('title') # name值 year = request.form.get('year') # 验证数据 if not title or not year or len(year) > 4 or len(title) > 60: flash('Invalid input..') # 显示错误消息 return redirect(url_for('index')) # 重定向事业 # 保存数据表 movie = Movie(title=title, year=year) db.session.add(movie) db.session.commit() flash('Item create.') # 显示创建成功 return redirect(url_for('index')) movies = Movie.query.all() # 从数据库获取电影 return render_template('index.html', movies=movies) # 使用上下文模板函数
def get_movies(self, request, *args, **kwargs): token = request.GET["uid"] new_movies = [] movies = pick_movies(token) for movie in movies: if "summary" in movie: summary = movie["summary"] else: summary = "" movie = Movie( id=movie["movie_id"], name=movie["name"], directors=",".join(flatten(movie["directors"])) if movie["directors"] else "", actors=",".join(flatten(movie["actors"])) if movie["actors"] else "", language=",".join(flatten(movie["language"])) if movie["language"] else "", types=",".join(flatten(movie["types"])) if movie["types"] else "", countries=",".join(flatten(movie["countries"])) if movie["countries"] else "", year=movie["year"] if movie["year"] else "", length=movie["length"] if movie["length"] else "", rate=movie["rate"], editors=",".join(flatten(movie["editors"])) if movie["editors"] else "", people=movie["people"], tags=",".join(flatten(movie["tags"])) if movie["tags"] else "", cover_url="/photos/" + movie["movie_id"], summary=summary, ) print movie new_movies.append(movie) movie_json = MovieSerializer(new_movies) return Response(movie_json.data)
class MoviesViewSetTest(TestCase): def setUp(self): self.movie = Movie( title='test', data={'test_data': 'test_value'} ) self.movies = [ Movie( title=f'title{index}', data={ 'test_data': 'other_value', 'special_filter': f'special_value{index}' } ) for index in range(6) ] self.example_get_movie_data = { 'Response': 'True', 'Title': 'Test-man 3 big testing', 'Rating': '5/7', } def test_default_get_behavior(self): self.movie.save() request = factory.get('/', '', content_type='application/json') response = self.get_view(request) self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertListEqual( response.data, [ {'title': 'test', 'data': {'test_data': 'test_value'}} ] ) def test_get_no_results(self): request = factory.get('/', '', content_type='application/json') response = self.get_view(request) self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertListEqual(response.data, []) def test_get_many_results(self): Movie.objects.bulk_create(self.movies) request = factory.get('/', '', content_type='application/json') response = self.get_view(request) self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(len(response.data), len(self.movies)) def test_get_with_filter(self): Movie.objects.bulk_create([self.movie, *self.movies]) request = factory.get( '/', data={'test_data': 'test_value'}, content_type='application/json' ) response = self.get_view(request) self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertListEqual( response.data, [ {'title': 'test', 'data': {'test_data': 'test_value'}} ] ) def test_get_with_two_keywords_filter(self): Movie.objects.bulk_create([self.movie, *self.movies]) request = factory.get( '/', data={ 'test_data': 'test_value', 'special_filter': 'special_value1' }, content_type='application/json' ) response = self.get_view(request) self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertListEqual( response.data, [ {'title': 'test', 'data': {'test_data': 'test_value'}}, {'title': 'title1', 'data': { 'test_data': 'other_value', 'special_filter': 'special_value1' }}, ] ) @mock.patch('movie.views.get_movie_data') def test_default_post_behavior(self, mock_get_movie_data): mock_get_movie_data.return_value = self.example_get_movie_data request = factory.post( '/', data={'title': 'test-man 3'}, format='json' ) self.assertFalse(Movie.objects.all().exists()) response = self.post_view(request) self.assertEquals(response.status_code, status.HTTP_201_CREATED) self.assertEquals( Movie.objects.get().title, mock_get_movie_data.return_value['Title'] ) def test_no_title_in_post(self): request = factory.post('/', data={}, format='json') response = self.post_view(request) self.assertFalse(Movie.objects.all().exists()) self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertDictEqual( response.data, {'Error': 'Movie title not provided.'} ) @mock.patch('movie.views.get_movie_data') def test_post_movie_with_given_title_already_exists( self, mock_get_movie_data ): mock_get_movie_data.return_value = self.example_get_movie_data self.movie.title = mock_get_movie_data.return_value['Title'] self.movie.save() request = factory.post( '/', data={'title': 'test-man 3'}, format='json' ) response = self.post_view(request) self.assertEquals(Movie.objects.all().count(), 1) self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT) self.assertDictEqual( response.data, {'Error': 'Move with title already exists.'} ) @property def get_view(self): return MoviesView.as_view({'get': 'list'}) @property def post_view(self): return MoviesView.as_view({'post': 'create'})
def add(name, debug, log): if debug == 'y': debug = True else: debug = False name = re.sub(u"\s+", "%20", name) conn.request("GET", film.format(name), payload) res = conn.getresponse() data_movie = json.loads(res.read()) if not data_movie['total_results']: print("Could not find ", name) log.write(name + '\n') log.flush() else: movie_data = data_movie['results'][0] # populating movie database if Movie.objects.filter(name=movie_data['title']): movie_object = Movie.objects.filter(name=movie_data['title'])[0] else: if movie_data['poster_path']: movie_object = Movie(name=movie_data['title'], release=movie_data['release_date'], poster=str(poster_path + movie_data['poster_path'])) else: movie_object = Movie(name=movie_data['title'], release=movie_data['release_date']) movie_id = movie_data['id'] if debug: click.echo(u'Movie name, Release date: {}'.format(movie_object)) if debug: # print genres for debugging for j in movie_data['genre_ids']: click.echo(u'Genre: {}'.format(genre_dict[str(j)])) # getting movie credits to store crew and cast conn.request("GET", credit.format(movie_id), payload) res = conn.getresponse() crew_data = json.loads(res.read()) # print director for debugging if debug: for k in crew_data['crew']: if k['job'] == "Director": click.echo(u'Director: {}'.format(k["name"])) cast_range = min(10, len( crew_data['cast'])) # number of actors to be saved is less than 10 # print actors for debugging if debug: for m in range(0, cast_range): click.echo(u'Actor: {}'.format(crew_data['cast'][m]['name'])) # getting keywords for movie conn.request("GET", keywords.format(movie_id), payload) res = conn.getresponse() key_word_data = json.loads(res.read()) # print keywords for debugging if debug: for keyword in key_word_data["keywords"]: click.echo(u'Keyword: {}'.format(keyword["name"])) if debug: save = '' while save != 'y' and save != 'n': save = click.prompt( "\nDo you want to save the movie to database? \n(y) for \"yes\" and (n) for \"no\"" ) else: save = 'y' if save == 'y': movie_object.save() # populating genre database for j in movie_data['genre_ids']: if Genre.objects.filter(name=genre_dict[str(j)]): genre_object = Genre.objects.filter( name=genre_dict[str(j)])[0] genre_object.movie_name.add(movie_object) else: genre_object = Genre(name=genre_dict[str(j)]) genre_object.save() genre_object.movie_name.add(movie_object) # populating director database for k in crew_data['crew']: if k['job'] == "Director": if Director.objects.filter(name=k['name']): director_object = Director.objects.filter( name=k['name'])[0] director_object.movie_name.add(movie_object) break else: director_object = Director(name=k['name']) director_object.save() director_object.movie_name.add(movie_object) # populating actor database for m in range(0, cast_range): if Actor.objects.filter(name=crew_data['cast'][m]['name']): actor_object = Actor.objects.filter( name=crew_data['cast'][m]['name'])[0] actor_object.movie_name.add(movie_object) else: actor_object = Actor(name=crew_data['cast'][m]['name']) actor_object.save() actor_object.movie_name.add(movie_object) # populating keyword database for keyword in key_word_data["keywords"]: if Keyword.objects.filter(database_id=keyword["id"]): keyword_object = Keyword.objects.filter( database_id=keyword["id"])[0] keyword_object.movie_name.add(movie_object) else: keyword_object = Keyword(database_id=keyword["id"], name=keyword["name"]) keyword_object.save() keyword_object.movie_name.add(movie_object) print(u"stored: {} {}\n".format(movie_data['title'], movie_data['release_date'])) else: click.echo("Movie not stored in database")
def add_movie(request): """ POST: /api/movies/add/ Specify the name ,producer, director_name, music_by, writer, cast, release_date, runtime, budget, country, language cast: comma seperated value of the star cast release_date: date specified in dd-mm-yyyy format runtime: in minutes budget: in dollars/inr """ if request.method == "POST": movie_id = "" movie = Movie() try: movie.name = request.POST.get("name",) movie.producer = request.POST.get("producer") movie.director_name = request.POST.get("director_name") movie.writer = request.POST.get("writer") movie.music_by = request.POST.get("music_by") movie.cast = request.POST.get("cast") movie.release_date = datetime.strptime(request.POST.get("release_date"), '%d-%m-%Y') movie.runtime = int(request.POST.get("runtime")) movie.budget = int(request.POST.get("budget")) movie.country = request.POST.get("country") movie.language = request.POST.get("language") movie.save() except Exception,e: print e ####### Missing request parameters ########### response = HttpResponse(json.dumps({"status": "unsuccessful"}), content_type="application/json", status=404) response['Access-Control-Allow-Origin'] = '*' return response response = HttpResponse(json.dumps({"id": movie.id}), content_type="application/json", status=200) response['Access-Control-Allow-Origin'] = '*' return response
def test_movie_string_representation(self): movie = Movie(title="Movie title") self.assertEqual(str(movie), movie.title)
def create_movie_list_object(res_dic): if res_dic is not None and len(res_dic) != 0: movie_url = res_dic["story"][0]["link"] if movie_url != "": daum_code = movie_url.split("=")[1] movie = None try: movie = Movie.objects.get(daum_code=daum_code) except: title = res_dic["title"][0]["content"] genre = res_dic["genre"][0]["content"] story = res_dic["story"][0]["content"] movie_img = res_dic["thumbnail"][0]["content"] first_run_date = res_dic["open_info"][0]["content"] nation = res_dic["nation"][0]["content"] to_date = datetime.strptime(first_run_date.replace(".", "-"), "%Y-%m-%d") appear_dic = crawlingMixin.get_actor_director(movie_url) director_arr = [ Director.objects.get_or_create(daum_code=director["daum_id"], defaults={ "name": director["name"], "img": director["img"]})[0] for director in appear_dic["directors"] ] actor_arr = [ {"actor": Actor.objects.get_or_create(daum_code=actor["daum_id"], defaults={ "name": actor["name"], "img": actor["img"]})[0], "role": actor["role"]} for actor in appear_dic["actors"] ] movie = Movie(daum_code=daum_code, title=title, genre=genre, story=story, img=movie_img, nation_code=nation) if to_date != "": movie.first_run_date = to_date.date() movie.save() movie.director.add(*director_arr) stillcut_list = [ res_dic["photo"+str(i)]["content"].split("=")[1].replace("%3A", ":").replace("%2F","/") for i in range(1, 6) ] for img_url in stillcut_list: StillCut.objects.get_or_create(img=img_url, movie=movie) for actor in actor_arr: MovieActorDetail.objects.get_or_create(actor=actor["actor"], movie=movie, defaults={ "role": actor["role"] }) finally: return movie else: pass
def read_databases(): person_data = open("./databases/name.basics.tsv/data.tsv", "r") lines = person_data.readlines() for i in range(1, len(lines)): line = lines[i].strip().split("\t") try: person = Person.objects.get(imdb_id=line[0]) except: person = Person(imdb_id=line[0], name=line[1], birth_year=line[2], death_year=line[3], primary_profession=line[4], known_for_titles=line[5]) person.save() person_data.close() crew_data = open("./databases/title.crew.tsv/data.tsv", "r") lines = crew_data.readlines() for i in range(1, len(lines)): line = lines[i].strip().split("\t") try: movie = Movie.objects.get(imdb_id=line[0]) except: movie = Movie(imdb_id=line[0], directors=line[1], writers=line[2]) movie.save() crew_data.close() principals_data = open("./databases/title.principals.tsv/data.tsv", "r") lines = principals_data.readlines() for i in range(1, len(lines)): line = lines[i].strip().split("\t") try: movie = Movie.objects.get(imdb_id=line[0]) person = Person.objects.get(imdb_id=line[2]) except: movie = Movie(imdb_id=line[0]) person = Person(imdb_id=line[2]) movie.save() if line[3] == 'director': movie.directors = line[3] elif line[3] == 'writer': movie.writers = line[3] elif line[3] == 'actor' or line[3] == 'actress': movie.casts.add(person) movie.save() principals_data.close() rating_data = open("./databases/title.ratings.tsv/data.tsv", "r") lines = rating_data.readlines() for i in range(1, len(lines)): line = lines[i].strip().split("\t") try: movie = Movie.objects.get(imdb_id=line[0]) except: movie = Movie(imdb_id=line[0]) movie.save() movie.imdb_rating = float(line[1]) movie.imdb_num_votes = int(line[2]) movie.save() rating_data.close()
def download_movie(title): url = 'http://www.omdbapi.com/?{}={}&plot=full&apikey=4ae80ea6'.format( 's', title) response = requests.get(url) for i in response.json()['Search']: if not Movie.objects.filter(title=i['Title']).exists(): key = i['imdbID'] response_two = requests.get( 'http://www.omdbapi.com/?i={}&plot=full&apikey=4ae80ea6'. format(key)) model = Movie() Title = response_two.json()['Title'] model.title = response_two.json()['Title'] duration = response_two.json()['Runtime'] duration = duration.split() if duration[0] != 'N/A': model.duration = int(duration[0]) model.detail = response_two.json()['Plot'] gender = response_two.json()['Genre'] gender = gender.split(',') model.gender = gender[0] model.original_languaje = response_two.json()['Language'] model.country = response_two.json()['Country'] release_date = response_two.json()['Released'] if release_date != 'N/A': model.release_date = datetime.strptime(release_date, '%d %b %Y') # Image image_url = response_two.json()['Poster'] image_response = requests.get(image_url) image_response = image_response.content image = open(settings.MEDIA_ROOT + '/' + Title + '.jpg', 'wb') image.write(image_response) image.close() model.poster = Title + '.jpg' model.save() # Forey Key Actor Actors = response_two.json()['Actors'] Actors = Actors.split(', ') tem_actor = [] for actor in Actors: instance, get = Actor.objects.get_or_create(name=actor) tem_actor.append(instance) # Forey Key Director Directors = response_two.json()['Director'] Directors = Directors.split(', ') tem_director = [] for director in Directors: instance, get = Director.objects.get_or_create(name=director) tem_director.append(instance) model = Movie.objects.get(title=Title) for j in tem_actor: model.actors.add(j) for k in tem_director: model.directors.add(k) model.save() Suggest.objects.get(title=title).delete() return title
def save_movie_data(movie_data): movie_data.pop('Response') new_movie_data = Movie(**movie_data) new_movie_data.save()
from django.db.models import Q from movie.models import Movie, Actor, Act from .MngIMDB import MngIMDB, moviedata movie_list = [] mng = MngIMDB() movie_list = mng.load_data_from_csv() mng.setUpClass() for movie in movie_list: lookupsmovietitle = Q(title__icontains=movie.title) lookupsmovieid = Q(movieid__icontains=movie.movieid) movies = Movie.objects.filter(lookupsmovietitle | lookupsmovieid).distinct() if movies: continue newmovie = Movie() newmovie.title = movie.title newmovie.rate = movie.rate newmovie.year = movie.year genres = str(movie.genres) newmovie.genres = genres.replace(",", "|") newmovie.plot = movie.plot newmovie.length = movie.length results = mng.search_movie(movie.title) newmovie.poster = results[''] newmovie.trailer = results['trailer'] newmovie.movieid = results['movieid'] newmovie.poster = results['poto'] newmovie.rate = results['rateing'] newmovie.save() actors = str(movie.actors).split(',')