Пример #1
0
    def add_movie():

        # Check that there is request
        if not request.get_json():
            abort(400)

        # Check if title and release_date exists
        if ('title' not in request.get_json()) or (
                'release_date' not in request.get_json()) or (
                    'actors' not in request.get_json()):
            abort(400)

        title = request.get_json()['title']
        release_date = request.get_json()['release_date']
        actors = request.get_json()['actors']

        # Check the data type
        if not (isinstance(title, str)
           and isinstance(release_date, str)
           and isinstance(actors, list)):
            abort(400)

        # Setup actors objects
        actors_obj = [
            Actor.query.get(actor)
            for actor in actors
            if Actor.query.get(actor) is not None
        ]

        # Check that there is at least one actor exists
        if not actors_obj:
            abort(400)

        # Convert datetime to datetime object | Global format: d/m/y
        day, month, year = convert_date(release_date)

        # Year, month, day
        try:
            datetime_obj = datetime.datetime(year, month, day)
        except Exception as e:
            abort(400)

        # Create movie object
        movie = Movie(title.strip(), datetime_obj)

        try:
            movie.insert()
            movie.insert_actors(actors_obj)
            return jsonify({
                'movie_id': movie.id,
                'success': True,
                'status_code': 201
            })
        except Exception as e:
            print(e)
            abort(422)