def check_in(self,qx): addmovie = self.parser.copy() # addmovieAction.remove_argument('flag') addmovie.remove_argument('limit') addmovie.add_argument('mId', type=int, required=True, help='必须提供电影id') addmovie.add_argument('showname', required=True, help='必须提供电影名') addmovie.add_argument('showname', required=True, help='必须提供电影名') addmovie.add_argument('shownameen', required=True, help='必须提供电影英文名') addmovie.add_argument('director', required=True, help='必须提供导演名') addmovie.add_argument('leadingRole', required=True, help='必须提供导主演') addmovie.add_argument('type', required=True, help='必须提供电影类型') addmovie.add_argument('country', required=True, help='必须提供国家') addmovie.add_argument('language', required=True, help='必须提供语言') addmovie.add_argument('duration', type=int, required=True, help='必须提供int类型的参数') addmovie.add_argument('screeningmodel', required=True, help='必须提供上映模式') addmovie.add_argument('openday', required=True, help='必须提供上映时间') addmovie.add_argument('backgroundpicture', required=True, help='必须提供背景图片') addmovie.add_argument('isdelete', default=0) addmovie.add_argument('opt', required=True, help='请指定操作') args=addmovie.parse_args() movie=dao.getById(Movies,args.get('mId')) if qx==QX.ADD_QX: if movie: return {'msg':'你添加的电影存在'} movie = Movies() elif qx==QX.EDIT_QX: if not movie: return {'msg':'你要修改的电影不存在'} for key,value in args.items(): if hasattr(movie,key): setattr(movie,key,value) dao.save(movie) return {'msg':('添加' if qx==QX.ADD_QX else '修改')+'成功'}
def add_movie(current_user): data = request.get_json() movie = Movies.query.filter_by(name=data['name']).first() if movie: return jsonify({'message': 'Movie already exist.'}), 409 genres = [] for x in data['genre']: raw_genre = x.lower().strip() genre = Genres.query.filter_by(name=raw_genre).first() if not genre: return jsonify( {'message': 'Genre (%s) does not exist.' % (raw_genre)}), 400 genres.append(genre) new_movie = Movies( name=data['name'], director=data['director'], popularity=data['99popularity'], imdb_score=data['imdb_score'], ) db.session.add(new_movie) db.session.flush() for genre in genres: movie_genre = MovieGenres(movie_id=new_movie.id, genre_id=genre.id) db.session.add(movie_genre) # db.session.flush() db.session.commit() return jsonify({ 'message': 'New movie added successfully.', 'movie': new_movie.serialized })
def add_movie(): if not request.json or not 'movie' in request.json: return u'No movie name defined', 400 movie_name = request.json['movie'] username = auth.username() existing_movie = Movies.query.filter_by(movie=movie_name).first() if not existing_movie: #search IMDB ia = IMDb() movie = ia.search_movie(str(movie_name)) if movie: movie_id = movie[0].movieID movie_object = ia.get_movie(movie_id) movie_imdbpage = f'https://www.imdb.com/title/tt{movie_id}/' else: return u'Could not find movie info on IMDB', 400 try: movie_year = movie_object['year'] except: movie_year = '????' try: movie_plot = movie_object['plot'][0].split('::')[0] except: movie_plot = '????' try: movie_rating = movie_object['rating'] except: movie_rating = '??' try: poster_url = movie_object['full-size cover url'] except: poster_url = "/static/images/no-movie-poster.png" try: movie_genres = movie_object['genres'] movie_genres = ','.join(movie_genres).replace(',',', ') #this fixes spacing between genres in the string except: movie_genres = '????' try: movie_director = movie_object['director'][0]['name'] except: movie_director = '????' #add movie to db new_movie = Movies(movie=movie_name, username=username, votes=0, year=movie_year, rating=movie_rating, plot=movie_plot, poster=poster_url, genres=movie_genres, director=movie_director, category='backlog', imdb_page=movie_imdbpage ) db.session.add(new_movie) db.session.commit() return jsonify({'poster':poster_url,'year':movie_year,'plot':movie_plot,'rating':movie_rating,'name':movie_name,'genres':movie_genres, 'director':movie_director, 'imdbpage':movie_imdbpage}) else: return u'Movie already exists', 400
def addMovie(request, moviedb_id): """responds to ajax route to add movie to collection""" if request.method == 'POST': current_user = request.user search = moviedbAPIInterface() result = search.getMovieById(moviedb_id) if not Movies.objects.filter(moviedb_id=moviedb_id).exists(): newMovie = Movies(moviedb_id=moviedb_id,title=result['title'], poster_path=result['poster_path'], details=result['details']) newMovie.save() newListNumber = UserMovieList.objects.filter(user_id=current_user.id).count() if newListNumber >= 10: return HttpResponse('You can only have 10 movies in your personal canon') currentMovie = Movies.objects.get(moviedb_id=moviedb_id) currentUser = User.objects.filter(pk=current_user.id) isMovieOnList = UserMovieList.objects.filter(movie=currentMovie) if not isMovieOnList: newMovieListItem = UserMovieList(user=current_user,movie=currentMovie,list_position=newListNumber) newMovieListItem.save() return HttpResponse('200')
def add_movies(*args, **kwargs): """ Requires post:movies permissions Endpoint for directors and executive producers to create new movies :return: Status code 200 and json {"success": True, "movie": movie} where movie is the details of the new movie that was added to the database """ data = dict(request.get_json()) if not all(key in data.keys() for key in ("title", "release_date")): abort(422) release_date = '' try: release_date = datetime.strptime( data.get("release_date"), standard_date_format ) except ValueError: abort(422) error = False try: new_movie = Movies( release_date=release_date, title=data.get("title") ) new_movie.insert() result = { "success": True, "movie": new_movie.details() } return jsonify(result) except Exception: error = True db.session.rollback() print(exc_info()) finally: db.session.close() if error: abort(500)
def edit_movie(id): movie = Movies.query.get(id) if movie is None: movie = Movies.from_json(request.json) movie.director = request.json.get('director', movie.director) movie.year = request.json.get('year', movie.year) movie.title = request.json.get('title', movie.title) movie.length = request.json.get('length', movie.length) movie.rating = request.json.get('rating', movie.rating) db_session.add(movie) db_session.commit() return (jsonify(movie.to_json()), 200, { 'Location': url_for('api.get_movie', id=movie.id, _external=True) })
def search(): form = SearchForm() if not form.validate(): return render_template('search.html', form=form) query = request.args.get('q') page = request.args.get('page', 1, int) per_page = request.args.get('per_page', 5, int) movies, total = Movies.search(query, page, per_page) next_url = url_for('search', page=page + 1, q=query) if page * per_page < total else None prev_url = url_for('search', page=page - 1, q=query) if page > 1 else None return render_template('results.html', movies=movies, next_url=next_url, prev_url=prev_url)
def migrate_movies(): data = Load_Movies(os.path.join(os.path.dirname(__file__), 'movies.csv')) existing_records = Movies.query.all() if existing_records is not None: for m in existing_records: db.session.delete(m) db.session.commit() for i in range(200): record = Movies(movieid=int(data.iloc[i, :][0]), moviename=data.iloc[i, :][1], genre=data.iloc[i, :][2], thumbnail=data.iloc[i, :][3], watchlink=data.iloc[i, :][4], avg_rating=data.iloc[i, :][5], N_ratings=int(data.iloc[i, :][6])) db.session.add(record) db.session.commit() return "Movies Migration complete"
def new_post(): movie = Movies.from_json(request.json) if movie.year > 2100: abort( make_response( jsonify({ "status": 400, "reason": "Field 'year' should be less then 2100" }), 400)) if movie.title is None: abort( make_response( jsonify({ "status": 400, "reason": "Field 'title' is required" }), 400)) db_session.add(movie) db_session.commit() return (jsonify(movie.to_json()), 200, { 'Location': url_for('api.get_movie', id=movie.id, _external=True) })
def addmovie(): selected_movie = request.form['selected_movie'] movie_year = request.form['movie_year'] movie_rating = request.form['movie_rating'] movie_plot = request.form['movie_plot'] movie_poster = request.form['movie_poster'] movie_genres = request.form['movie_genres'] current_user = request.form['current_user'] movie_director = request.form['movie_director'] movie_imdbpage = request.form['movie_imdbpage'] existing_movie = Movies.query.filter_by(movie=selected_movie).first() #user = User.query.filter_by(username=current_user).first() #points = user.points #check if movie is already in the database if existing_movie: return u'Movie already exists', 400 #check if user has enough points #elif points < 1: # return u'Not enough points', 500 else: #grab all the data from IMDB for it and put it into the db new_movie = Movies(movie=selected_movie, username=current_user, votes=0, year=movie_year, rating=movie_rating, plot=movie_plot, poster=movie_poster, genres=movie_genres, director=movie_director, category='backlog', imdb_page=movie_imdbpage ) db.session.add(new_movie) #user.remove_point() #remove 1 point db.session.commit() #commit the db changes #points = user.points # grab the new points print('Successfuly added movie to database') return jsonify({'movie':selected_movie})
def insert_Movies(payload): ''' This endpoint insert Movie information ''' body = request.get_json() name = body.get('name', None) genre = body.get('genre', None) length = body.get('length', None) actor_ID = body.get('actor_ID', None) actors = Actors.query.filter(Actors.id == actor_ID).one_or_none() try: new_movie = Movies(name=name, genre=genre, length=length) if actors: new_movie.Actors = [actors] new_movie.insert() else: new_movie.insert() return jsonify({'success': True}) except: abort(422)
# writing them to a list which can be given to the database movies = [] i = 0 film_t = ';' scr = open('screenings', 'r') for film_title in scr: if film_t in film_title: movie = film_title movie = movie.replace(';', '') movie = movie.replace('\n', '') #print(movie) movies.append(movie) if i <= int(len(movies)): red = Movies.query.filter_by(name=movie).count() if red == 0: title = Movies(name=movies[i]) db.session.add(title) db.session.commit() i = i + 1 df = pandas.read_csv('screenings', delimiter='/', lineterminator=',') i = 0 while i < len(movies): print(movies[i]) df = df.replace(movies[i], '', regex=True) i = i + 1 df = df.replace(' ', '', regex=True) #print(Movies.query.order_by().all()) # import the csv file and deleting the movie titles from it
def saving(): form = IndexForm() if form.validate_on_submit: # 1st API call url = "https://imdb8.p.rapidapi.com/title/find" # gets show from form entry show_to_search = request.values.get('movie_title') querystring = {"q": show_to_search} headers = { 'x-rapidapi-host': "imdb8.p.rapidapi.com", 'x-rapidapi-key': "5a64743a7bmsh79b17ce5d033775p102796jsneae2a4334407" } response = requests.request("GET", url, headers=headers, params=querystring).json() # Grabbing Tconst, title from API call tconst = response['results'][0]['id'].split('/')[2] title = response['results'][0]['title'] # Grab plot plot_url = "https://imdb8.p.rapidapi.com/title/get-plots" plot_querystring = {"tconst": tconst} plot_headers = { 'x-rapidapi-host': "imdb8.p.rapidapi.com", 'x-rapidapi-key': "5a64743a7bmsh79b17ce5d033775p102796jsneae2a4334407" } plot_response = requests.request("GET", plot_url, headers=plot_headers, params=plot_querystring).json() plot = plot_response['plots'][0]['text'] # check if show info is already in DB if not then add it name_exists = db.session.query( db.exists().where(Movies.tconst == tconst)).scalar() if not name_exists: movie_info = Movies(tconst=tconst, title=title, plot=plot) db.session.add(movie_info) db.session.commit() # 2nd API Call to "get similar show" tconst_url = "https://imdb8.p.rapidapi.com/title/get-more-like-this" tconst_querystring = { "currentCountry": "US", "purchaseCountry": "US", "tconst": tconst } tconst_headers = { 'x-rapidapi-host': "imdb8.p.rapidapi.com", 'x-rapidapi-key': "5a64743a7bmsh79b17ce5d033775p102796jsneae2a4334407" } tconst_response = requests.request("GET", tconst_url, headers=tconst_headers, params=tconst_querystring).json() # Gets responses, takes 1st element, splits and takes the tconstant # of show that is similar to initially searched show similar_show_tconst = tconst_response[0].split('/')[2] # if similar_show (tconst) is in DB # query info from DB instead of calling API name_exists = db.session.query( db.exists().where(Movies.tconst == similar_show_tconst)).scalar() if name_exists: title_name = Movies.query.filter_by( tconst=similar_show_tconst).first() similar_show = title_name.title similar_plot = title_name.plot return render_template('display.html', title1=similar_show, plot=similar_plot) else: # 3rd API call only if needed final_url = "https://imdb8.p.rapidapi.com/title/get-plots" final_querystring = {"tconst": similar_show_tconst} final_headers = { 'x-rapidapi-host': "imdb8.p.rapidapi.com", 'x-rapidapi-key': "5a64743a7bmsh79b17ce5d033775p102796jsneae2a4334407" } final_response = requests.request("GET", final_url, headers=final_headers, params=final_querystring).json() similar_show_title1 = final_response['base']['title'] similar_show_plot = final_response['plots'][0]['text'] # Save this similar show in DB too to reduce the amount of overall API calls used # check if show info is already in DB if not then add it name_exists = db.session.query(db.exists().where( Movies.tconst == similar_show_tconst)).scalar() if not name_exists: similar_show_info = Movies(tconst=similar_show_tconst, title=similar_show_title1, plot=similar_show_plot) db.session.add(similar_show_info) db.session.commit() return render_template('display.html', title1=similar_show_title1, plot=similar_show_plot)
def insert_movies(movie_id, title, imdb_code, like_count): movie = Movies(movie_id=movie_id, title=title,imdb_code=imdb_code,like_count=like_count) db.session.add(movie) db.session.commit()