def patch(self, politician_id): json_data = request.get_json() data, errors = politician_schema.load(data=json_data, partial=True) if errors: return {'message': 'Validation errors', 'errors': errors}, HTTPStatus.BAD_REQUEST politician = Politician.get_by_id(politician_id=politician_id) if politician is None: return {'message': 'politician not found'}, HTTPStatus.NOT_FOUND current_user = get_jwt_identity() if current_user != politician.user_id: return {'message': 'Access is not allowed'}, HTTPStatus.FORBIDDEN politician.name = data.get('name') or politician.name politician.position = data.get('position') or politician.position politician.description = data.get('description') or politician.description politician.age = data.get('age') or politician.age politician.gender = data.get('gender') or politician.gender politician.bio_data = data.get('bio_data') or politician.bio_data politician.c_vitae = data.get('c_vitae') or politician.c_vitae politician.county = data.get('county') or politician.county politician.constituency = data.get('constituency') or politician.constituency politician.ward = data.get('ward') or politician.ward politician.save() clear_cache('/politicians') return politician_schema.dump(politician).data, HTTPStatus.OK
def importPoliticians(request, graph): f = request.files['file'] if not f: return jsonify({'error': 'No file'}) stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None) csv_input = csv.reader(stream, delimiter=";") next(csv_input) politiciansNum = 0 for row in csv_input: if (politiciansNum == 0): tx = graph.begin() politician_name = row[0] gender = 'male' if row[3] == 'Hombre' else 'female' political_party_name = row[1] charge = row[4] try: salary = float(row[8].replace(',', '.')) except ValueError: salary = 0.0 institution_name = row[6] region_name = row[7] if (politician_name and political_party_name and region_name and institution_name and charge): politician = Politician(politician_name, gender, political_party_name, region_name, institution_name, charge, salary) tx.create(politician) politiciansNum += 1 tx.commit() return jsonify(f'Imported {politiciansNum} records')
def post(self): json_data = request.get_json() current_user = get_jwt_identity() data, errors = politician_schema.load(data=json_data) if errors: return {'message': 'Validation errors', 'errors': errors}, HTTPStatus.BAD_REQUEST politician = Politician(**data) politician.user_id = current_user politician.save() return politician_schema.dump(politician).data, HTTPStatus.CREATED
def put(self, politician_id): file = request.files.get('cover') if not file: return {'message': 'Not a valid image'}, HTTPStatus.BAD_REQUEST if not image_set.file_allowed(file, file.filename): return {'message': 'File type not allowed'}, HTTPStatus.BAD_REQUEST politician = Politician.get_by_id(politician_id=politician_id) if politician is None: return {'message': 'Politician not found'}, HTTPStatus.NOT_FOUND current_user = get_jwt_identity() if current_user != politician.user_id: return {'message': 'Access is not allowed'}, HTTPStatus.FORBIDDEN if politician.cover_image: cover_path = image_set.path(folder='politicians', filename=politician.cover_image) if os.path.exists(cover_path): os.remove(cover_path) filename = save_image(image=file, folder='politicians') politician.cover_image = filename politician.save() clear_cache('/politicians') return politician_cover_schema.dump(politician).data, HTTPStatus.OK
def getPoliticians(request, graph): limit = int(request.args.get('limit', 50)) politicians = list(Politician.match(graph).limit(limit)) print(politicians) politiciansSerialize = list( map(lambda politician: politician.serialize(), politicians)) return jsonify(politiciansSerialize)
def get(self, q, page, per_page, sort, order): print('Querying database...') if sort not in['created_at', 'county', 'constituency']: sort = 'created_at' if order not in ['asc', 'desc']: order = 'desc' paginated_politicians = Politician.get_all_published(q, page, per_page, sort, order) return politician_pagination_schema.dump(paginated_politicians).data, HTTPStatus.OK
def updatePolitician(request, graph): politician_id = request.form.get('id') politician = Politician.match(graph).where( f"ID(_) = {politician_id}").first() if (not (politician)): return jsonify({'error': 'Politician not found'}) political_party_name = request.form.get('political_party') politician.belongs.clear() political_party = PoliticalParty(political_party_name) politician.belongs.add(political_party) graph.push(politician) return jsonify(politician.serialize())
def test_storing_politician_no_contributions(self): """ Test storing a single politician into the db """ data = {"name": "Bill Nelson"} #to_store = Politician(**data) successful = store_politician(data) self.assertTrue(successful) # Should now be able to find the politician in the db result = Politician.get_by_name("Bill Nelson") self.assertIsNotNone(result) # Only one should exist, politician object should be returned self.assertTrue(isinstance(result, Politician))
def get(self, politician_id): politician = Politician.get_by_id(politician_id=politician_id) if politician is None: return {'message': 'Politician not found'}, HTTPStatus.NOT_FOUND current_user = get_jwt_identity() if politician.is_publish == False and politician.user_id != current_user: return {'message': 'Access is not allowed'}, HTTPStatus.FORBIDDEN return politician_schema.dump(politician).data, HTTPStatus.OK
def createPolitician(request, graph): # Get required variables politician_name = request.form.get('name') political_party_name = request.form.get('political_party') gender = request.form.get('gender') charge = request.form.get('charge') salary = request.form.get('salary') salary = float(salary) if salary else 0.0 institution_name = request.form.get('institution') region_name = request.form.get('region') if ( not(politician_name) or not(political_party_name) or not(charge) or not(region_name) or not(institution_name) ): return jsonify({ 'error': 'name, political_party, institution and charge are required' }) # Create politician politician = Politician( politician_name, gender, political_party_name, region_name, institution_name, charge, salary ) graph.push(politician) return jsonify(politician.serialize())
def delete(self, politician_id): politician = Politician.get_by_id(politician_id=politician_id) if politician is None: return {'message': 'politician not found'}, HTTPStatus.NOT_FOUND current_user = get_jwt_identity() if current_user != politician.user_id: return {'message': 'Access is not allowed'}, HTTPStatus.FORBIDDEN politician.delete() clear_cache('/politicians') return {}, HTTPStatus.NO_CONTENT
def get(self, username, page, per_page, visibility): user = User.get_by_username(username=username) if user is None: return {'message': 'User not found'}, HTTPStatus.NOT_FOUND current_user = get_jwt_identity() if current_user == user.id and visibility in ['all', 'private']: pass else: visibility = 'public' paginated_politicians = Politician.get_all_by_user( user_id=user.id, page=page, per_page=per_page, visibility=visibility) return politician_pagination_schema.dump( paginated_politicians).data, HTTPStatus.OK
def test_storing_politician_one_contribution(self): """ Test storing a single politician with accompanying contribution """ contributions = [{'date': '08/13/2014', 'funder': 'NRA',}] data = {'name': 'Marco Rubio', 'contributions': contributions} successful = store_politician(data) self.assertTrue(successful) # Marco Rubio should now be a politician in our db result = Politician.get_by_name('Marco Rubio') self.assertIsNotNone(result) self.assertTrue(isinstance(result, Politician)) # Result should have one contribution and one funder self.assertEqual(len(result.contributions), 1) self.assertEqual(len(result.funders), 1) contribution = result.contributions[0] funder = result.funders[0] # TODO: These checks are silly. Add .to_dict functions to the models # and then use them to compare the results with what we stuck in (: self.assertTrue(isinstance(contribution, Contribution)) self.assertTrue(isinstance(funder, Funder))