Пример #1
0
 def put(self, id):
     """send put request with json(fields: 'department_id','name', 'salary', 'birthday') and return
     json data(fields: 'dep', 'department_id','name', 'salary', 'id','birthday'.
     If department not exist algorithm creates new department in db.
     Every field must be filled"""
     employee = EmployeeService.fetch_employee_by_id(db.session, id)
     if not employee:
         return make_response(jsonify({"message": "Employee not found"}),
                              404)
     rq = request.json
     department_name = rq['department_name']
     department = DepartmentService.fetch_department_by_name(
         db.session, name=department_name)
     if not department:
         department = self.department_schema_without_id.load(
             dict(name=department_name), session=db.session)
         DepartmentService.create(department, db.session)
     rq['department_id'] = department.id
     del rq['department_name']
     try:
         employee = self.employee_schema.load(request.json,
                                              instance=employee,
                                              session=db.session)
     except ValidationError as e:
         logger.debug(f"Validation error in put Employee by Api is {e}")
         return make_response(jsonify({'message': str(e)}), 400)
     return self.employee_schema.dump(
         EmployeeService.create(employee, db.session)), 200
Пример #2
0
    def put(self, id):
        """send put request with json(fields: 'id','name') and return json data(fields: 'name', 'id')."""
        department = DepartmentService.fetch_department_by_id(db.session, id)
        if not department:
            return make_response(jsonify({"message": "Department not found"}),
                                 404)

        employees = EmployeeService.update_department_id(
            db.session, id=id, name=request.json['name'])
        logger.debug(employees)

        dep_by_name = DepartmentService.fetch_department_by_name(
            db.session, name=request.json['name'])

        if dep_by_name:
            return self.department_schema.dump(
                DepartmentService.delete(department, db.session)), 200

        try:
            department = self.department_schema.load(request.json,
                                                     instance=department,
                                                     session=db.session)
        except ValidationError as e:
            logger.debug(f"Validation error in put Department by Api is {e}")
            return make_response(jsonify({'message': str(e)}), 400)
        logger.debug(department)
        return self.department_schema.dump(
            DepartmentService.create(department, db.session)), 200
Пример #3
0
    def delete(self, id):
        """send delete request to db(table 'department') with json(fields: 'id','name')
        and return status code 204 or 404"""

        department = DepartmentService.fetch_department_by_id(db.session, id)
        if not department:
            return make_response(jsonify({"message": "Department not found"}),
                                 404)
        DepartmentService.delete(department, db.session)
        return '', 204
Пример #4
0
def populate_db(id):
    """User can get address like /populate/23, where 23 is arbitrary number of new fake Employees.
        After this request DB will be updated with new records"""

    if id > 1000:
        flash(f"DB not populated by {id} records, please request less 1000 records", "danger")
        return redirect(url_for('index'))

    fake = Faker()
    employees_to_create = []
    for _ in range(id):
        data = {
            "name": fake.name(),
            "birthday": str(fake.date_between_dates(date_start=datetime(1985, 1, 1),
                                                    date_end=datetime(2000, 1, 1))),
            "salary": random.randrange(100, 5000, 100),
            "department_name": random.choice(['web', 'frontend', 'backend', 'simulations',
                                              'graphic', 'android', 'iOS', 'ml', 'ds', 'marketing'])
        }
        department = DepartmentService.fetch_department_by_name(db.session, name=data["department_name"])

        if not department:
            department = Department(name=data["department_name"])
            db.session.add(department)
            db.session.commit()

        employees_to_create.append(Employee(name=data["name"], birthday=data["birthday"],
                                            salary=data["salary"], department_id=department.id))

    db.session.bulk_save_objects(employees_to_create)
    db.session.commit()
    flash(f"DB successfully populated by {id} records", "success")
    return redirect(url_for('index'))
Пример #5
0
 def post(self):
     """send post request to db(joined query between tables employee and department) json(fields: 'dep')
     and return json data(fields: 'id','name'). If department not exist algorithm creates new department in db"""
     try:
         department = self.department_schema.load(request.json,
                                                  session=db.session)
     except ValidationError as e:
         logger.debug(f"Validation error in post Department by Api is {e}")
         return make_response(jsonify({'message': str(e)}), 400)
     if DepartmentService.fetch_department_by_name(db.session,
                                                   department.name):
         logger.debug('Department not unique, already exists')
         return make_response(
             jsonify({'message': 'Department not unique, already exists'}),
             409)
     return self.department_schema.dump(
         DepartmentService.create(department, db.session)), 201
Пример #6
0
    def get(self, id=None):
        """send get request with id or no to db(joined query between tables employee and department)
        and return json data, and if answer to request to db not empty json will have fields 'department_id',
        'name', 'avg'. It is not json with list of all departments, only departments which binded with employees"""
        if not id:
            field = request.args.get('field', 'id')
            ordr = request.args.get('ordr', 'asc')
            departments = DepartmentService.fetch_all_departments_with_avg_salary_sort_by(
                db.session, field, ordr).all()
            return self.department_schema_with_avg.dump(departments,
                                                        many=True), 200

        department = DepartmentService.fetch_department_by_id(db.session, id)
        if not department:
            return make_response(jsonify({"message": "Department not found"}),
                                 404)
        return self.department_schema.dump(department), 200
Пример #7
0
    def post(self):
        """send post request to db with json(fields: 'dep','name', 'salary', 'birthday') and return
        json data(fields: 'dep', 'department_id','name', 'salary', 'id','birthday'.
        If department not exist algorithm creates new department in db"""
        rq_args = request.args
        rq = request.json
        if not rq_args.get('populate'):
            rq = [rq]
        logger.debug(rq)
        for one_record in rq:
            department_name = one_record['department_name']
            department = DepartmentService.fetch_department_by_name(
                db.session, name=department_name)

            if not department:
                department = self.department_schema_without_id.load(
                    dict(name=department_name), session=db.session)
                DepartmentService.create(department, db.session)

            dep_record = copy.deepcopy(one_record)
            dep_record['department_id'] = department.id
            del dep_record['department_name']
            try:
                employee = self.employee_schema.load(dep_record,
                                                     session=db.session)
            except ValidationError as e:
                logger.debug(
                    f"Validation error to post Employee {one_record} by Api is {e}"
                )
                return make_response(
                    jsonify({
                        'message':
                        f'Validation error to post Employee {one_record} is {e}'
                    }), 400)
            db.session.add(employee)
        db.session.commit()
        return self.employee_schema.dump(employee), 201