def add_actor(payload): body = request.get_json() actor_name = body.get('name', None) actor_age = body.get('age', None) actor_gender = body.get('gender', None) if not actor_name: abort(422, {'message': 'Name of actor not provided'}) if not actor_age: abort(422, {'message': 'Age of actor not provided'}) if not actor_gender: abort(422, {'message': 'Gender of actor not provided'}) try: actor = Actors(name=actor_name, age=actor_age, gender=actor_gender) actor.insert() actors = Actors.query.order_by(Actors.id).all() total_actors = len(actors) last_actor = actors[total_actors - 1].format() # actors_formatted = [actor.format() for actor in actors] return jsonify({'success': True, 'actor_added': last_actor}) except BaseException: db.session.rollback() print(sys.exc_info()) abort(422, {'message': 'Failed to add new actor to the database'}) finally: db.session.close()
def post_actors(payload): """ POST api to create a new actor in db """ body = request.get_json() # Read post data name = body.get('name') age = body.get('age') gender = body.get('gender') if name is None or age is None or gender is None: abort(400) # Convert age to int age = int(age) try: # Create an actor actor = Actors(name=name, age=age, gender=gender) actor.insert() return jsonify({ 'success': True, 'created': actor.id }), 201 except Exception as err: print(err) db.session.rollback() abort(422) finally: db.session.close()
def add_actor(payload): body = request.get_json() # get all the user's inputs new_name = body.get('name', None) new_age = body.get('age', None) new_gender = body.get('gender', None) # check the user's inputs if new_name == '' or new_age == '' or new_gender == '': # unprocessable error abort(422) try: actor = Actors(name=new_name, age=new_age, gender=new_gender) actor.insert() total = len(Actors.query.all()) return jsonify({ 'success': True, 'created': actor.id, 'totalActors': total }) except BaseException: # unprocessable error abort(422)
def update_actor(token, actor_id): try: actor = Actors.query.get(actor_id) body = request.get_json() if 'name' in body: new_name = body.get('name') setattr(actor, 'name', new_name) if 'age' in body: new_age = body.get('age') setattr(actor, 'age', new_age) if 'gender' in body: new_gender = body.get('gender') setattr(actor, 'gender', new_gender) Actors.update(actor) actor_updated = Actors.query.get(actor_id) return jsonify({ 'success': True, 'actor_updated': Actors.format(actor_updated) }) except Exception: abort(404)
def post_actor(payload): body = request.get_json() if not ('name' in body and 'age' in body, 'gender' in body and 'movie' in body): abort(422) new_name = body.get('name', None) new_age = body.get('age', None) new_gender = body.get('gender', None) new_movie = body.get('movie', None) if new_name is None or new_age is None or new_gender is None: abort(400) try: actor = Actors(name=new_name, age=new_age, gender=new_gender, movie_id=new_movie) if Actors.query.filter_by(name=actor.name).count(): abort(409) actor.insert() return jsonify({ 'success': True, 'actor': actor.format(), 'total_actors': len(Actors.query.all()) }) except AttributeError: abort(422)
def create_actor(jwt): ''' Create an endpoint to POST a new actor, which will require the name, age and gender detals ''' # Get the request body body = request.get_json() new_name = body.get('name') new_age = body.get('age') new_gender = body.get('gender') if ((new_name is None) or (new_age is None) or (new_gender is None)): abort(422) try: # create the new actor actor = Actors(name=new_name, age=new_age, gender=new_gender) actor.insert() # return the new created actor if successfully created return jsonify({ 'success': True, 'actor': actor.format() }) # raise exception for any error during deleting the actor except: db.session.rollback() print(sys.exc_info()) abort(404)
def add_actors(jwt): #--Get request json body = request.get_json() if body is None: abort(400) #--does not contain valid json try: #--get form values to variables--# new_name = body.get('name', '') new_age = body.get('age', '') new_gender = body.get('gender', '') if not (new_gender and new_age and new_name): abort(422) #--no data provided--# new_actor = Actors(name=new_name, age=new_age, gender=new_gender) new_actor.insert() return jsonify( { 'success': True, 'id': new_actor.id, 'name': new_actor.name }, 200) except Exception as e: print(e) abort(422)
def edit_actor(payload, id): ans = Actors.query.filter(Actors.id == id).one_or_none() # print(ans) if ans is None: abort(404) try: name = "" age = "" gender = "" if 'name' in request.get_json(): name = request.get_json()['name'] ans.name = name if 'age' in request.get_json(): age = request.get_json()['age'] ans.age = age if 'gender' in request.get_json(): gender = request.get_json()['gender'] ans.gender = gender name = ans.name age = ans.age gender = ans.gender Actors.commit() except: Actors.rollback() abort(422) return jsonify({ "success": True, "name": name, "age": age, "gender": gender })
def test_get_actors(self): actor = Actors(name='Elsa Montanha', age=21, gender='Female') actor.insert() response = self.client().get('/actors', headers=self.assistant) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertEqual(data['success'], True)
def create_actor(f): body = request.get_json() if body is None: abort(422) required_params = ['name', 'age', 'gender'] for param in required_params: if param not in body: abort(422) name = body.get('name') age = body.get('age') gender = body.get('gender') if gender != "female" and gender != "male": abort(22) try: new_actor = Actors(name=name, age=age, gender=gender) new_actor.insert() except: abort(422) return jsonify({'success': True, 'created': new_actor.id})
def post_actors(payload): add_actor = request.get_json() actor_name = add_actor.get('name') actor_gender = add_actor.get('gender') actor_age = add_actor.get('age') if actor_name is None: abort(422) if actor_gender is None: abort(422) if actor_age is None: abort(422) try: new_actor = Actors(name=actor_name, gender=actor_gender, age=actor_age) new_actor.insert() return jsonify({ "success": True, "actor-added": new_actor.id }) except Exception: abort(422)
def delete_actor_by_id(payload, actor_id): queued_actor = Actors.query.filter(Actors.id == actor_id).one_or_none() if queued_actor is None: abort(404) else: Actors.delete(queued_actor) return jsonify({"success": True, "delete": actor_id})
def create_actors(payload): req = request.get_json() new_name = req.get('name') new_age = req.get('age') new_gender = req.get('gender') new_movie_id = req.get('movies_id') try: new_actor = Actors(name=new_name, age=new_age, gender=new_gender, movies_id=new_movie_id) new_actor.insert() return jsonify({ 'success': True, 'new_actor': [new_actor.format()] }), 200 except BaseException: abort(405) finally: db.session.close()
def add_actor(): error = False new_name = request.form['name'] new_age = request.form['age'] new_gender = request.form['gender'] new_image_link = request.form['image_link'] new_description = request.form['description'] try: actor = Actors(name=new_name, age=new_age, gender=new_gender, image_link=new_image_link, description=new_description) actor.insert() flash('Artist ' + request.form['name'] + ' successfully created 🚀') except Exception: rollback() error = True abort(400) flash('An error occurred. ' + actor.name + ' could not be listed.') return redirect(url_for('get_actors'))
def save_actor(jwt): #gets the body from request body = request.get_json() name = body['name'] #name is not given if name is None: abort(422) age = body['age'] #age is not given if age is None: abort(422) Gender = body['Gender'] #gender is not given if Gender is None: abort(422) actor = Actors(name=name, age=age, Gender=Gender) try: actor.insert() except: abort(500) return jsonify({'success': True, 'actor_id': actor.actor_id})
def delete_actor(token, actor_id): try: actor = Actors.query.get(actor_id) Actors.delete(actor) return jsonify({'success': True, 'actor_id_deleted': actor_id}) except Exception: abort(404)
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': [] }] })
def post_actor(jwt): # Gets the JSON body data = request.get_json() # print(data) # Checks that the JSON contains the complete details if 'firstname' not in data: abort(422) if 'lastname' not in data: abort(422) if 'gender' not in data: abort(422) if 'age' not in data: abort(422) # Checks that the age is an integer try: int(data.get('age')) except Exception: abort(400) # Gets each actor detail actor_firstname = data.get('firstname') actor_lastname = data.get('lastname') actor_age = int(data.get('age')) actor_gender = data.get('gender') # Checks that the details are not empty if actor_firstname is None: abort(400) if actor_lastname is None: abort(400) if actor_age is None: abort(400) if actor_gender is None: abort(400) # Initiates an instance of the Actors row new_actor = Actors( firstname=actor_firstname, lastname=actor_lastname, age=actor_age, gender=actor_gender ) try: # Insert the new actor details into the database new_actor.insert() except Exception: abort(422) actor = new_actor.details() return jsonify({ "success": True, "actor": actor }), 200
def add_actor(): data = request.get_json() new_name = data.get('name', None) new_age = data.get('age', None) new_gender = data.get('gender', None) new_actor = Actors(name=new_name, age=new_age, gender=new_gender) Actors.insert(new_actor) list_of_actors = Actors.query.all() return jsonify({'success': True, 'actors': list_of_actors})
def test_400_update_actor(self): actor = Actors(name='Elsa Montanha', age=21, gender='Female') actor.insert() actor_id = actor.id response = self.client().patch('/actors/' + str(actor_id) + '', headers=self.director) data = json.loads(response.data) self.assertEqual(response.status_code, 400) self.assertEqual(data['success'], False)
def post_actor_details(payload): body = request.get_json() name = body['name'] age = body['age'] gender = body['gender'] movie = body['movie'] new_actor = Actors(name=name, age=age, gender=gender, movie=movie) new_actor.insert() new_actor_data = Actors.query.order_by(-Actors.id).first().format() return jsonify({'success': True, 'actors': new_actor_data})
def test_delete_actor(self): actor = Actors(name='Elsa Montanha', age=21, gender='Female') actor.insert() actor_id = actor.id response = self.client().delete('/actors/' + str(actor_id) + '', headers=self.producer) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertEqual(data['success'], True)
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_name = "capstone_test" self.database_path = "postgres://{}/{}".\ format('localhost:5432', self.database_name) setup_db(self.app, self.database_path) self.headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer', 'Token': token} self.actor = Actors( name='Buzz', age='21', gender='male' ) self.movie = Movies( title='Hardy Bucks', release_date='21st' ) self.new_actor = { 'name': 'French Toast', 'age': '28', 'gender': 'Male' } self.new_movie = { 'title': 'French Toast', 'release_date': '28' } self.edit_actor = { 'name': 'Eddie', 'age': '23', 'gender': 'Female' } self.edit_movie = { 'title': 'Hardy Bucks 2', 'release_date': '22nd' } with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all() self.actor.insert() self.movie.insert()
def create_actor(payload): body = request.get_json() new_actor = Actors(name=body.get('name', ''), age=body.get('age', ''), gender=body.get('gender', '')) new_actor.insert() return jsonify({'status': 'successful'}), 200
def test_executive_delete_actors(self): test_actor = Actors(name="Marcos test", age=20, gender="male") test_actor.insert() headers = {'Authorization': 'Bearer {}'.format(TOKEN_EXECUTIVE)} res = self.client().delete('/actors/{}'.format(test_actor.id), headers=headers) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertTrue(data['deleted'])
def addActor(jwt): parser = request.get_json() newName = parser['Name'] newAge = parser['Age'] newGender = parser['Gender'] newActor = Actors(name=newName, age=newAge, gender=newGender) newActor.insert() return jsonify({ 'Success': True })
def add_actors(): try: data = request.get_json() print(data) name = data.get('name', None) age = data.get('age', None) gender = data.get('gender', None) actor = Actors(name=name, age=age, gender=gender) actor.add() return jsonify({'success': True, 'actors': [actor.format()]}), 200 except: abort(422)
def test_delete_actors(self): new_actor = Actors(name='Sara', age='35', gender='female') new_actor.insert() actor_id = new_actor.id res = self.client().delete( '/actors/{}'.format(actor_id), headers={'Authorization': 'Bearer ' + test_token}) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True)
def insert_Actors(payload): body = request.get_json() try: actor = Actors(name=body['name'], age=body['age'], email=body['email'], salary=body['salary']) #print(actor,flush=True) actor.insert() return jsonify({'success': True}) except Exception: abort(404)
def post_actors(payload): body = request.get_json() try: req_name = body.get("name", None) req_age = int(body.get('age', None)) req_gender = body.get('gender', None) actor = Actors(name=req_name, age=req_age, gender=req_gender) actor.insert() return jsonify({'success': True, 'actors': actor.id}), 200 except BaseException: abort(422)
def actors(request): sort_key = request.GET.get('sort', DEFAULT_SORT) sort = VALID_ACTORS_SORT.get(sort_key, DEFAULT_SORT) #TODO: Ordered by Bacon number instead of alphabetically. if sort == 'bacon': actors_all = Actors.all_ordered_alphabetically() else: actors_all = Actors.all_ordered_alphabetically() if 'search_query' in request.GET: return search_actors(request, actors_all) else: return render_to_response('tvmaniacs/actors.html', {'Actors': actors_all, 'page_limit': Actors.page_limit()}, context_instance=RequestContext(request))
def search_actors(request, actors_list): text_list = request.GET["search_query"].split() if len(text_list) == 0: found_actors = actors_list else: condition = Q(first_name__icontains=text_list[0]) condition |= Q(last_name__icontains=text_list[0]) if len(text_list) > 1: for string in text_list[1:]: condition |= Q(first_name__icontains=string) condition |= Q(last_name__icontains=string) found_actors = actors_list.filter(condition) message = "Results: " + str(len(found_actors)) return render_to_response('tvmaniacs/actors.html', {'Actors': found_actors, 'page_limit': Actors.page_limit(), 'search_message': message }, context_instance=RequestContext(request))