def load_departments(): """ Loads departments from connected Uber instance :return: """ REQUEST_HEADERS = {'X-Auth-Token': cfg.uber_authkey} # data being sent to API request_data = {'method': 'dept.list'} request = requests.post(url=cfg.api_endpoint, json=request_data, headers=REQUEST_HEADERS) response = json.loads(request.text) response = response['result'].items() # print('loading departments') session = models.new_sesh() for dept in response: try: mydept = session.query(Department).filter_by(id=dept[0]).one() if not mydept.name == dept[1]: mydept.name = dept[1] except sqlalchemy.orm.exc.NoResultFound: mydept = Department() mydept.id = dept[0] mydept.name = dept[1] session.add(mydept) session.commit() session.close() return
def get_department(id): sql = "Select * from departments where id = %s" cursor = connection.cursor() cursor.execute(sql, [id]) record = cursor.fetchone() department = Department(id=record[0], name=record[1], head=record[2]) return department
def dep_create(): if not session["logged_in"] or not session.get("person")["admin"]: return redirect(url_for("dep_page")) db = Database() data = request.form dep= Department(data["name"], data["fac_id"], data["bu_id"], data["ch_id"]) db.add_department(dep) return redirect(url_for("dep_page"))
def create_record(self, department, fk1=None, fk2=None): sql = "INSERT INTO departments VALUES (%s, %s) RETURNING *" cursor = connection.cursor() cursor.execute( sql, (department.department_name, department.department_head)) connection.commit() record = cursor.fetchone() return Department(record[0], record[1])
def dci_from_data(dataset, db, conn): for model in [Department(), Course(), Instructor()]: sanitized_data = list(map(model.sanitize_from_raw, dataset)) sanitized_data = list({v['id']: v for v in sanitized_data}.values()) modeltable = model.__class__.__name__ result = r.db(db).table(modeltable).insert(sanitized_data).run(conn) inserted = result['inserted'] errors = result['errors'] logging.info("{0} Inserted \t {1} \t Skipped {2}".format( modeltable.ljust(12), inserted, errors))
def dep_insert(): if request.method == 'POST': dep_name = request.form['dep_name'] description = request.form['description'] my_data = Department(dep_name, description) db.session.add(my_data) db.session.commit() flash("Department inserted successfully") return redirect(url_for('department.dep_index'))
def get_record(self, department_name, fk1=None, fk2=None): sql = "SELECT * FROM departments WHERE department_name=%s" cursor = connection.cursor() cursor.execute(sql, [department_name]) record = cursor.fetchone() if record: return Department(record[0], record[1]) else: raise ResourceNotFound( f"Department with name {department_name} not found.")
def get_all_records(self): sql = "SELECT * FROM departments" cursor = connection.cursor() cursor.execute(sql) records = cursor.fetchall() department_list = [] for record in records: department = Department(record[0], record[1]) department_list.append(department.json()) return department_list
def add_department(self, fields: str): ref_id = generate_uuid() department = Department(ref_id=ref_id, **fields, created_at=get_current_time(), updated_at=get_current_time()) db.session.add(department) try: db.session.commit() except Exception as e: print(str(e.orig)) error_orig = str(e.orig).replace("(", "").replace(")", "").split(",")[1].strip().replace("'", "").replace('"', '').split(":")[0] raise IntegrityError(message=error_orig) return department
def post(self): """Adds a department to the database. Returns: Department's id using marshal or aborts with 404. """ try: raw_data = lomarsh(request.form, DepartmentSchema) raw_data['id'] = None return Operator.insert(Department(**raw_data)) except IntegrityError: abort(400)
def create_data(session: Session): department1_id = uuid.uuid4().hex department2_id = uuid.uuid4().hex department1 = Department(id=department1_id, title='Биология и Общая генетика') department2 = Department(id=department2_id, title='Биотехнология') session.add(department1) session.add(department2) mypath = "C:/Users/Andrey/Pictures/PNG" onlyfiles = listdir(mypath) added_objects = [] for obj in onlyfiles: splited_obj = obj.split('_') if splited_obj[0] in added_objects: continue obj_id = uuid.uuid4().hex new_object = Object(id=obj_id, title=splited_obj[0], department_id=department1_id) session.add(new_object) for fl in onlyfiles: splited_fl = fl.split('_') zoom_fl = splited_fl[1].split('.') if fl.find(splited_obj[0]) != -1: fl_id = uuid.uuid4().hex new_file = File(id=fl_id, type='image', url=fl, zoom=zoom_fl[0], object_id=obj_id) session.add(new_file) added_objects.append(splited_obj[0]) session.commit() session.close()
def setUp(self): app.config.from_object(TestConfiguration) self.app = app.test_client() db.create_all() db.session.add(Department(id=10001, name='Test Department')) db.session.add( Employee(name='Steven Gray', department_id=10001, date_of_birthday=date(1997, 10, 1), salary=Decimal(1000))) db.session.add( Employee(name='John Spins', department_id=10001, date_of_birthday=date(1997, 5, 11), salary=Decimal(3000))) db.session.commit()
def test_update(self): self.assertEqual( crud.Departments.update(10001, 10002, 'UpdatedDepartment'), Department(id=10002, name='UpdatedDepartment', employees=[ Employee(id=1, name='Steven Gray', department_id=10002, date_of_birthday=date(1997, 10, 1), salary=Decimal(1000)), Employee(id=2, name='John Spins', department_id=10002, date_of_birthday=date(1997, 5, 11), salary=Decimal(3000)) ]))
def digest_file(filename, db, conn): data = dataSet('data/csv/' + filename) fcq_data = list(map(Fcq().sanitize_from_raw, data.raw_data)) for model in [Department(), Course(), Instructor()]: sanitized_data = list(map(model.sanitize_from_raw, fcq_data)) sanitized_data = list({v['id']: v for v in sanitized_data}.values()) modeltable = model.__class__.__name__ result = r.db(db).table(modeltable).insert(sanitized_data).run(conn) inserted = result['inserted'] errors = result['errors'] logging.info("{0} Inserted \t {1} \t Skipped {2}".format(modeltable.ljust(12), inserted, errors)) result = r.db(db).table('Fcq').insert(fcq_data).run(conn) inserted = result['inserted'] errors = result['errors'] logging.info("{0} \t Inserted {1}".format(filename.ljust(12), inserted)) if errors: first_error = result['first_error'] logging.warn("{0} Errors inserting fcqs. First Error:\n{1}".format(errors, first_error))
def test_get_all(self): self.assertEqual(crud.Departments.get_all(), ([ Department(id=10001, name='Test Department', employees=[ Employee(id=1, name='Steven Gray', department_id=10001, date_of_birthday=date(1997, 10, 1), salary=Decimal(1000)), Employee(id=2, name='John Spins', department_id=10001, date_of_birthday=date(1997, 5, 11), salary=Decimal(3000)) ]) ], [(Decimal(2000), 10001)]))
def add(dep_id, name): """ Adds new department :param dep_id: The unique number of department :param name: Department`s name :return: New department that has been added :rtype: Department """ try: department = Department(id=dep_id, name=name) except: logger.debug(f'Department {dep_id} is exist, it can`t be added') raise AttributeError db.session.add(department) db.session.commit() logger.debug(f'Department {dep_id} was added') return department
def create(): try: input_json_data = request.get_json() db.create_all() db.session.commit() if not input_json_data: return {"message": "No input data provided"}, 400 new_category = input_json_data['category'] new_department = input_json_data['department'] department_results = Department.query.filter( Department.department == new_department) # validation of department details for temp in department_results: string_val = temp.serialize() if (new_department == string_val.get('department')) and ( new_category == string_val.get('category')): data = { 'Inserting Data': 'Failure', 'Error': "Department and Category have been already exists" } resp = jsonify(data), 205 return resp # assign department details to Department model department = Department( department=input_json_data['department'], department_id=Sequence('user_id_seq').next_value(), category=input_json_data['category'], details=input_json_data['details']) db.session.add(department) db.session.commit() data = {'create': 'success', 'department_id': department.department_id} resp = jsonify(data), 201 except Exception as e: data = {'create': 'fail'} resp = jsonify(data), 500 print(e) return resp
def load_departments(): """ Loads departments from connected Uber instance :return: """ REQUEST_HEADERS = {'X-Auth-Token': cfg.uber_authkey} request_data = {'method': 'dept.list'} request = requests.post(url=cfg.api_endpoint, json=request_data, headers=REQUEST_HEADERS) response = json.loads(request.text) response = response['result'].items() session = models.new_sesh() for dept in response: try: mydept = session.query(Department).filter_by(id=dept[0]).one() if not mydept.name == dept[1]: mydept.name = dept[1] except sqlalchemy.orm.exc.NoResultFound: mydept = Department() mydept.id = dept[0] mydept.name = dept[1] session.add(mydept) request_data = {'method': 'dept.jobs', "params": {"department_id": dept[0]}} request = requests.post(url=cfg.api_endpoint, json=request_data, headers=REQUEST_HEADERS) dept_details = json.loads(request.text) # this checks if changed before updating because my memory tells me # fewer changed records makes the SQL commit faster if not mydept.is_shiftless == dept_details['result']['is_shiftless']: mydept.is_shiftless = dept_details['result']['is_shiftless'] session.commit() session.close() return
from models.grade import Grade from models.course import Course from models.instructor import Instructor from models.department import Department from handlers.not_found_handler import NotFoundHandler import logging settings = { 'cookie_secret': 'PqITv9b7QUyoAUUcgfRtReoZIXjQrEKKk9fpQpGu6MU=', 'template_path': 'templates/', 'static_path': 'static/', 'grade': Grade(), 'fcq': Fcq(), 'course': Course(), 'instructor': Instructor(), 'department': Department(), 'default_handler_class': NotFoundHandler, 'ui_modules': { 'chart_overtime': LineChartModule, 'fcq_card': FcqCardModule } } def initialize_settings(): settings['debug'] = options.debug settings['autoreload'] = options.debug settings['site_port'] = options.port database_name = options.database_name database_port = options.database_port database_host = options.database_host
def add_dept(self): self.view.add_dept(Department())
def test_add(self): self.assertEqual( crud.Departments.add(10002, 'NewDepartment'), Department(id=10002, name='NewDepartment', employees=[]))