예제 #1
0
 def create_movie(jwt):
     """
         POST /movies
         it should create a new row in the movies table
         it should require the 'post:movies' permission
         it should contain the movie.long() data representation
     returns status code 200 and json {"success": True, "movies":
     movie} where
     drink an array containing only the newly created
      drink or appropriate status code indicating reason for failure
     """
     try:
         data = request.get_json()
         movie = Movies(title=data.get('title', None),
                        duration=data.get('duration', None),
                        release_year=data.get('release_year', None))
         movie.insert()
         movies = list(map(Movies.long, Movies.query.all()))
         return jsonify({
             'success': True,
             'movie': movies,
         }), 200
     except Exception:
         print(sys.exc_info())
         abort(422)
예제 #2
0
    def add_movie(payload):
        body = request.get_json()

        # get all the user's inputs
        new_title = body.get('title', None)
        new_date = body.get('date', None)

        # check the user's inputs
        if new_title == '' or new_date == '':
            # unprocessable error
            abort(422)

        try:
            movie = Movies(title=new_title, date=new_date)
            movie.insert()

            total = len(Movies.query.all())

            return jsonify({
                'success': True,
                'created': movie.id,
                'totalMovies': total
            })

        except BaseException:
            # unprocessable error
            abort(422)
    def add_movie(payload):
        body = request.get_json()

        movie_title = body.get('title', None)
        movie_release_date = body.get('release_date', None)

        if not movie_title:
            abort(422, {'message': 'Title of movie not provided'})

        if not movie_release_date:
            abort(422, {'message': 'Release date of movie not provided'})

        try:
            movie = Movies(title=movie_title, release_date=movie_release_date)

            movie.insert()

            movies = Movies.query.order_by(Movies.id).all()
            total_movies = len(movies)
            last_movie = movies[total_movies - 1].format()
            # movies_formatted = [movie.format() for movie in movies]

            return jsonify({'success': True, 'movie_added': last_movie})

        except BaseException:
            db.session.rollback()
            print(sys.exc_info())
            abort(422, {'message': 'Failed to add new movie to the database'})
        finally:
            db.session.close()
예제 #4
0
def loadMoviesJson(current_user):
    """
    **Access to admin only**
    Will Load movies in Bulk, pass JSON with array of movies and it will load all the movies in the DB.
    Takes:JSON
    Respond: Message with whether movies are added or not
    """
    moviesListJson = request.get_data()
    MoviesList = json.loads(moviesListJson)
    Result = ""
    for movie in MoviesList:
        popularity = movie["99popularity"]
        director = movie["director"]
        genres = movie["genre"]
        imdb_score = movie["imdb_score"]
        movieName = movie["name"]
        movieRecord = Movies(name=movieName,
                             imdb_score=imdb_score,
                             popularity99=popularity,
                             director=director)
        db.session.add(movieRecord)
        db.session.flush()
        print(movieRecord.id, movieRecord.name, movieRecord.director)
        db.session.commit()
        for genre in genres:
            movieGenre = MovieGenre(MovieID=movieRecord.id, Genre=genre)
            #print(genreRecord.id,genreRecord.Genre,movieGenre.id)
            db.session.add(movieGenre)
        db.session.commit()
        Result += (movieName + " added successful to Database # ")
    return jsonify({"result": Result})
예제 #5
0
    def create_movie():
        try:
            required_props = [
                'title',
                'release_date'
            ]

            optional_props = [
                'actors'
            ]

            movie_data = {}
            for prop in required_props:
                movie_data[prop] = request.get_json()[prop]

            for prop in optional_props:
                if prop in request.get_json():
                    movie_data[prop] = request.get_json()[prop]

            movie_data = validate_movie(**movie_data)

            movie = Movies(**movie_data)
            movie.insert()
            response = {
                'success': True,
                'movies': [movie.format()]
            }
        except UnprocessableEntity:
            raise
        except Exception:
            print(sys.exc_info())
            raise BadRequest

        return jsonify(response)
예제 #6
0
def add_movie():
    movie = Movies.query.all()
    keys = ("release_date", "title")
    data = request.get_json()
    if not set(keys).issubset(set(data)):
        return jsonify({
            'success': 'false',
            'message': 'fill in the missing fields'
        }), 400

    if 15 < len(data['title']) < 3 or not data['title'].isalnum() or \
            bool(Movies.query.filter_by(title=data['title']).first()):
        return jsonify({
            'success': 'false',
            'message': 'incorrect movie title'
        }), 400
    else:
        final_data = Movies(title=data['title'],
                            release_date=data['release_date'])
        db.session.add(final_data)
        db.session.commit()
        return jsonify({
            'success':
            True,
            'message':
            '{} movie created successfully'.format(data['title'])
        }), 200
예제 #7
0
def new_movies():

    title = request.args.get('title', '')
    rating = request.args.get('rating', '')
    if title == '' or rating == '':
        abort(400)
    if Movies.query.filter_by(title=title).first() is not None:

        return jsonify({"message": "movie alaredy exists"}), 200

    movie = Movies(title=title)
    movie.rating = rating
    db.session.add(movie)
    db.session.commit()

    #showtime_req = requests.post(showtime_post+'?'+'id='+str(movie.id))
    showtime_req = requests.post(showtime_post + '?' + 'id=' + str(movie.id) +
                                 '&title=' + str(title) + '&rating=' +
                                 str(rating))

    print(showtime_req.text)

    return jsonify({
        'Title': movie.title,
        'Raiting': movie.rating,
        'id': movie.id
    })
예제 #8
0
def init_movie_table(dataset_path):
    Session = sessionmaker(bind=db.engine)
    session = Session()
    if session.query(Movies).first():
        logger.info("Movie table has entries already, skipping population")
        session.close()
        return
    movies_file_path = os.path.join(dataset_path, 'movies.csv')
    with open(movies_file_path, newline='') as csvfile:
        reader = csv.DictReader(csvfile, delimiter=',')
        Session = sessionmaker(bind=db.engine)
        session = Session()
        for row in reader:
            title_with_year = row['title']
            iter = re.finditer(' \([0123456789]{4}\)', title_with_year)
            try:
                # get the last occurence of a 4 digit string within parenthesis
                *_, last_occurence = iter
                year = int(last_occurence.group()[2:6])
                title = title_with_year[:last_occurence.start()]
                new_movie = Movies(id=int(row['movieId']),
                                   description=row['genres'],
                                   title=title,
                                   year=year)
                session.add(new_movie)
                logger.info("Inserted movie with title " + title + " into db")
            except:
                pass
        session.commit()
        session.close()
예제 #9
0
    def add_movie():
        data = request.get_json()

        new_title = data.get('title', None)
        new_release_date = data.get('release_date', None)
        new_image_link = data.get('image_link', None)
        new_description = data.get('description', None)
        new_genres = data.get('genres', None)

        try:
            movie = Movies(title=new_title,
                           release_date=new_release_date,
                           description=new_description,
                           image_link=new_image_link,
                           genres=new_genres)
            movie.insert()

            selection = Movies.query.order_by('id').all()
            flash(movie.title + 'successfully added')
            return jsonify({
                'success': True,
                'message': 'Movie ' + movie.title + ' successfully added',
                'movies': len(selection)
            })

        except Exception:
            return json.dumps({
                'success': False,
                'error': 'Not able to add movie at this time',
            }), 422
예제 #10
0
def post_movie(token):
    post_data = request.get_json()
    if 'title' in post_data and 'release_date' in post_data:
        try:
            new_movie = Movies(title=post_data['title'],
                               release_date=post_data['release_date'])
            if 'actors' in post_data:
                actors_list = post_data['actors']
                for actor in actors_list:
                    actor_id = actor['id']
                    actor_data = Actors.query.get(actor_id)
                    if actor_data:
                        movie_set = Sets(movie_id=new_movie.id,
                                         actor_id=actor_id)
                        movie_set.insert()

            new_movie.insert()
            return jsonify({
                'id': new_movie.id,
                'success': True
            })
        except SQLAlchemyError:
            print(sys.exc_info())
            db.session.rollback()
            abort(400)
    abort(400)
예제 #11
0
def inset_db_from_local(movie_name, detail_path, photo_path):
    """
    将本地的电影摘要,插入到数据库内
    :param movie_name:
    :param detail_path:
    :param photo_path:
    :return:
    """

    movie = Movies.query.filter(Movies.detail_path == detail_path).first()
    if movie:
        if movie.name == movie_name and movie.photo_path == photo_path:
            return False
        else:
            movie.name = movie_name
            movie.photo_path = photo_path
            db.session.commit()
            return True
    else:
        movie = Movies(name=movie_name,
                       detail_path=detail_path,
                       photo_path=photo_path)
        db.session.add(movie)
        db.session.commit()
        return True
예제 #12
0
    def post_movie(token):
        data = request.get_json()
        new_movie = Movies(title=data['title'],
                           release_date=data['release_date'])
        new_movie.insert()

        return jsonify({'movie ': new_movie.format(), 'success': True})
def create_movie_submission():
    # TODO: insert form data as a new Movie record in the db, instead
    # TODO: modify data to be the data object returned from db insertion
    title = request.form['title']
    release_date = request.form['release_date']
    facebook_link = request.form['facebook_link']
    image_link = request.form['image_link']
    website = request.form['website']
    seeking_talent = request.form['seeking_talent']
    seeking_description = request.form['seeking_description']
    if (seeking_talent == "True"):
        seeking_talent = bool(seeking_talent)
    else:
        seeking_talent = bool()

    error = False
    try:
        movie = Movies(title=title, release_date=release_date)
        movie.insert()
    except:
        error = True
        print(sys.exc_info())
    if error:
        flash('An error occurred. Movie ' + movie.title +
              ' could not be listed.')
    else:
        flash('Movie ' + request.form['title'] + ' was successfully listed!')

    # on successful db insert, flash success
    # TODO: on unsuccessful db insert, flash an error instead.
    # e.g., flash('An error occurred. Venue ' + data.name + ' could not be listed.')
    # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/
    return render_template('pages/home.html')
예제 #14
0
 def create_movie(jwt):
     '''
     Create an endpoint to POST a new movie,
     which will require the title and
     release date
     '''
 
     # Get the request body
     body = request.get_json()
 
     new_title = body.get('title')
     new_release_date = body.get('release_date')
 
     if ((new_title is None) or (new_release_date is None)):
         abort(422)
 
     try:
         # create the new movie
         movie = Movies(title=new_title, release_date=new_release_date)
         movie.insert()
 
         # return the new created movie if successfully created
         return jsonify({
             'success': True,
             'movie': movie.format()
         })
 
     # raise exception for any error during deleting the movie
     except:
         db.session.rollback()
         print(sys.exc_info())
         abort(404)
예제 #15
0
    def add_movies(jwt):
        #---get json data--#
        body = request.get_json()
        if body is None:
            abort(401)

        try:
            new_title = body.get('title', '')
            new_release_date = body.get('release_date', '')

            if not (new_title and new_release_date):
                abort(400)
            movie = Movies(title=new_title, release_date=new_release_date)
            movie.insert()

            return jsonify(
                {
                    'success': True,
                    'title': new_title,
                    'message': new_title + " Added successfully",
                    'id': movie.id
                }, 200)

        except Exception as e:
            print(e)
            abort(422)
예제 #16
0
    def update_movie(self, id):

        try:
            movie = Movies.query.get(id)

            if not movie:
                print(sys.exc_info())
                abort(400)
                
            title = json_data_input('title')
            release_date = json_data_input('release_date')

            movie.title = title
            movie.release_date = release_date

            updated_movie = Movies(title, release_date)

            updated_movie.update()

            return jsonify({
                "success": True,
                "message": "update successfull",
                "movie details changed to ": updated_movie.format()
            })
        except Exception:
            print(sys.exc_info())
            abort(422)

        '''
예제 #17
0
  def create_movie(payload):
    # return 'auth implemented'
    # print(payload)

    body = request.get_json()
    # print(body)

    if not body:
      abort(400, {'message': 'request does not contain a valid JSON body.'})

    # Extract title and release_date value from request body
    title = body.get('title', None)
    release_year = body.get('release_year', None)
    # print(title,release_year)

    # abort if one of these are missing with appropiate error message
    if not title:
      abort(422, {'message': 'no title provided.'})

    if not release_year:
      abort(422, {'message': 'no "release_year" provided.'})

    new_movie = Movies(
      body['title'],
      body['release_year'],
      body['duration'],
      body['imdb_rating']
      )

    new_movie.add()

    return jsonify({
        'success': True,
        'created': new_movie.id
      }), 201
예제 #18
0
파일: app.py 프로젝트: NikolaiMe/capstone
    def create_movie(token):
        abort_code = None

        new_movie_name = None
        new_movie_releasedate = None

        body = request.get_json()

        if body is not None:
            new_movie_name = body.get('name', None)
            new_movie_releasedate = body.get('releasedate', None)

        try:
            if (new_movie_name is None
                    or new_movie_releasedate is None):
                abort_code = 422

            if abort_code is None:
                movie_to_insert = Movies(
                    name=new_movie_name,
                    releasedate=new_movie_releasedate)
                movie_to_insert.insert()
                return jsonify({
                    'success': True,
                    'created': movie_to_insert.id,
                })
        except BaseException:
            db.session.rollback()
            abort_code = 422
        finally:
            db.session.close

        if abort_code:
            abort(abort_code)
예제 #19
0
    def insert_movie(payload):
        # Get data
        new_title = request.get_json()['title']
        new_release_date = request.get_json()['release_date']

        # check movie title for duplicate
        check_movie_title = Movies.query.filter(
            Movies.title.ilike('%{}%'.format(new_title))).all()
        if len(check_movie_title) > 0:
            raise Exception("Sorry, no duplicate movie titles allowed")
            abort(409)
        else:
            try:
                # Prepare INSERT transaction
                new_movie = Movies(title=new_title,
                                   release_date=new_release_date)
                new_movie.insert()

                # Display latest data
                selection = Movies.query.filter(
                    Movies.title == new_title).first()
                return jsonify({
                    'id': selection.id,
                    'title': selection.title,
                    'release_date': selection.release_date,
                    'success': True
                }), 200

            except Exception:
                abort(422)
    def post_movie(payload):
        body = request.get_json()

        if not ('title' in body and 'release_date' in body):
            abort(422)

        new_title = body.get('title', None)
        new_release_date = body.get('release_date', None)

        if new_title is None or new_release_date is None:
            abort(400)

        try:
            movie = Movies(title=new_title, release_date=new_release_date)
            if Movies.query.filter_by(title=movie.title).count():
                abort(409)
            movie.insert()

            return jsonify({
                'success': True,
                'movie': movie.format(),
                'total_movies': len(Movies.query.all())
            })

        except AttributeError:
            abort(422)
예제 #21
0
    def add_movie():
        form = MovieUploadForm()
        form.category.choices = get_category_list()

        if form.validate_on_submit():
            movie = form.movie.data
            thumbnail = form.thumbnail.data
            if movie and thumbnail:
                movie_data = movie.read(MOBICLIP_HEADER_SIZE)
                thumbnail_data = thumbnail.read()

                if validate_mobiclip(movie_data):
                    # Get the Mobiclip's length from header.
                    length = get_mobiclip_length(movie_data)

                    # Read the remaining file data.
                    remaining = movie.read()
                    movie_data += remaining

                    # Insert this movie to the database.
                    # For right now, we will assume defaults.
                    db_movie = Movies(
                        title=form.title.data,
                        length=length,
                        aspect=False,
                        genre=0,
                        sp_page_id=0,
                        ds_dist=False,
                        staff=False,
                    )

                    db.session.add(db_movie)
                    db.session.commit()

                    db.session.add(
                        CategoryMovies(category_id=form.category.data,
                                       movie_id=db_movie.movie_id))
                    db.session.commit()

                    # Now that we've inserted the movie, we can properly move it.
                    save_movie_data(db_movie.movie_id, thumbnail_data,
                                    movie_data)

                    # Finally, allow it for indexing.
                    es.index(
                        index="tv_index",
                        body={
                            "title": form.title.data,
                            "movie_id": db_movie.movie_id
                        },
                    )

                    return redirect("/theunderground/movies")
                else:
                    flash("Invalid movie!")
            else:
                flash("Error uploading movie!")

        return render_template("add_movie.html", form=form)
예제 #22
0
파일: test_app.py 프로젝트: Onnys/Capstone
 def test_get_movies(self):
     movie = Movies(title='The Last Man Standing',
                    release_date='12-21-23 12:00 pm')
     movie.insert()
     response = self.client().get('/movies', headers=self.assistant)
     data = json.loads(response.data)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(data['success'], True)
예제 #23
0
    def create_movie(payload):
        body = request.get_json()
        new_movie = Movies(title=body.get('title', ''),
                           release_date=body.get('release_date', ''))

        new_movie.insert()

        return jsonify({'status': 'successful'}), 200
예제 #24
0
    def test_get_movies(self):
        movie = Movies(title='the walking dead', release_date='23-01-22')
        movie.insert()
        res = self.client().get(
            '/movies', headers={'Authorization': 'Bearer ' + ASS_TOKEN})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
예제 #25
0
def db_setup():
    with open("movie_plots.csv", newline='') as csvfile:
        movies = csv.reader(csvfile, delimiter=',')
        movies = list(movies)
        for movie in movies:
            newentery = Movies(movie[0], movie[1], movie[2], movie[3],
                               movie[4], movie[5], movie[6], movie[7])
            db.session.add(newentery)
            db.session.commit()
예제 #26
0
def add_movie(request, user):
    """
    Add new Movie
    :param request: API Request Details
    :param user: Admin User Details
    """
    try:
        movie_data = json.loads(request.data)
        name = movie_data['name']
        director = movie_data['director']
        popularity = movie_data['99popularity']
        genre = ','.join(movie_data['genre'])
        imdb_score = movie_data['imdb_score']

        if not db.session.query(Movies).filter_by(name=name, director=director).first():
            movie = Movies(
                name=name,
                director=director,
                popularity=popularity,
                genre=genre,
                imdb_score=imdb_score,
                created_by=user.id,
            )
            db.session.add(movie)
            db.session.commit()

            logging.info("Movie added to DB successfully")

            # Add Movie to Elasticsearch
            try:
                movie_data['id'] = str(movie.id)
                es = ESOperations("imdb")
                es.create_document(movie_data)
                logging.info("Movie added to ES successfully")
            except Exception as e:
                logging.error(str(e))
                pass

            response_object = {
                'status': 'success',
                'message': 'Movie added successfully.',
                'data': movie.serialize()
            }
            return make_response(jsonify(response_object)), 201
        else:
            response_object = {
                'status': 'error',
                'message': 'Movie already exists.'
            }
            return make_response(jsonify(response_object)), 201
    except Exception as e:
        logging.error(str(e))
        response_object = {
            'status': 'error',
            'message': str(e)
        }
        return make_response(jsonify(response_object)), 400
예제 #27
0
    def patch(self, user_type):
        """"
        Casting Assistants cannot edit actors nor movies
        """
        data = ['actors', 'movies']
        for entity_type in data:

            if entity_type == 'actors':
                actor_data = {"name": "Clarece", "gender": "f", "age": 88}
                actor = Actors(**actor_data)
                actor.insert()

                actors_response = self.user_patch(user_type, entity_type, 1,
                                                  {"name": "Amanda"})

                if user_type is 'CA':
                    self.assertEqual(actors_response.json['code'], 401)
                else:
                    self.assertEqual(
                        actors_response.json, {
                            f'{entity_type}': [{
                                'name': 'Amanda',
                                'gender': 'Female',
                                'id': 1,
                                'age': 88,
                                'movies': []
                            }],
                            'success':
                            True
                        })

            if entity_type == 'movies':
                movie_data = {
                    "title": "The Big One",
                    "release_date":
                    datetime.fromisoformat('2020-03-22 22:23:11')
                }
                movie = Movies(**movie_data)
                movie.insert()

                movies_response = self.user_patch(user_type, entity_type, 1,
                                                  {"title": "The Little One"})

                if user_type is 'CA':
                    self.assertEqual(movies_response.json['code'], 401)
                else:
                    self.assertEqual(
                        movies_response.json, {
                            'success':
                            True,
                            'movies': [{
                                'id': 1,
                                'title': "The Little One",
                                'release_date': 'Sun Mar 22 22:23:11 2020',
                                'actors': []
                            }]
                        })
예제 #28
0
def import_movies(request):
    f = open('data/movie_table.txt', "r")
    for lines in f:
        line = lines.strip().split("\t")
        movie = Movies(title=line[0],
                       num_stars=int(line[1]),
                       num_users=int(line[2]),
                       avg_rating=float(line[1]) / float(line[2]))
        movie.save()
    return HttpResponse('Done')
예제 #29
0
 def add_movies():
     try:
         data = request.get_json()
         title = data.get('title', None)
         release_date = data.get('release_date', None)
         movie = Movies(title=title, release_date=release_date)
         movie.add()
         return jsonify({'success': True, 'movies': [movie.format()]}), 200
     except:
         abort(422)
예제 #30
0
    def test_delete_movie(self):
        movie = Movies(title='the walking dead S4', release_date='23-07-22')
        movie.insert()
        res = self.client().delete(
            f'/movies/{movie.id}',
            headers={'Authorization': 'Bearer ' + EXE_TOKEN})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)