async def init_db(): from models import Department, Employee, Role Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) # Create Fixture for department engineering = Department(name='Engineering') db_session.add(engineering) hr = Department(name='Human Resource') db_session.add(hr) # Create Fixture for Role manager = Role(name='manager') db_session.add(manager) engineer = Role(name='Engineer') db_session.add(engineer) # Create peter = Employee(name='Peter', department=engineering, role=manager) db_session.add(peter) roy = Employee(name='Roy', department=engineering, role=engineer) db_session.add(roy) tracy = Employee(name='Tracy', department=hr, role=manager) db_session.add(tracy) # Insert seed data into database db_session.commit()
def add_department(self): # ------------------------- # Add a department # ------------------------- name = request.form.get('name', '') id = 0 try: id = Department().get_next_department_id() except BaseException: app.logger.info('Error finding next department ID') abort(422) department = Department( id=id, name=name ) try: department = department.add_department_to_database() flash(f'Department {name} was successfully added!', 'success') except BaseException: app.logger.info( f'An error occurred. Department {name} could not be added!') abort(422) return redirect(url_for('departments'))
def create_all(): if not database_exists('sqlite:///fastlane.db'): db.create_all() db.session.add(Department(department_name='Design')) db.session.add(Department(department_name='Production')) db.session.add(Department(department_name='Prototype')) db.session.commit()
def get(self): id = self.request.get('id') jsArray = [] if not id: dptList = Department.all() for one in dptList: jsObj = { str(one.dptCode):one.dptName #'link' :one.dptLink } jsArray.append( jsObj ) else: jsArray.append( {"id": id } ) dept = Department.all().filter('dptCode = ', int(id) ).get() if dept: jsArray.append( {"name": dept.dptName } ) # searching for the clinic info: doctors = [] times = [] docCodes = [] clinics = Clinic.all().filter('dept =', dept.key() ).order('date') for one in clinics: times.append( one.date ) if one.doctor.docCode not in docCodes: docCodes.append( one.doctor.docCode ) doctors.append( { one.doctor.docCode : one.doctor.docName } ) jsArray.append( { "doctor" : doctors }) jsArray.append( { "time" : times }) self.response.headers['Content-Type'] = 'application/json' self.response.out.write( simplejson.dumps(jsArray) )
def init_db(): """Import all modules here that might define models so that they will be registered properly on the metadata. Otherwise you will have to import them first before calling init_db() """ from models import Department, Employee, Pokemon, Role Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) engineering = Department(name="Engineering") db_session.add(engineering) hr = Department(name="Human Resources") db_session.add(hr) manager = Role(name="manager") db_session.add(manager) engineer = Role(name="engineer") db_session.add(engineer) peter = Employee(name="Peter", department=engineering, role=engineer) db_session.add(peter) roy = Employee(name="Roy", department=engineering, role=engineer) db_session.add(roy) tracy = Employee(name="Tracy", department=hr, role=manager) db_session.add(tracy) db_session.commit() charzard = Pokemon(name="Charzard", level=100, type="fire") db_session.add(charzard) db_session.commit()
def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() from models import Department, Employee, Role Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) # Create the fixtures engineering = Department(name='Engineering') db_session.add(engineering) hr = Department(name='Human Resources') db_session.add(hr) manager = Role(name='manager') db_session.add(manager) engineer = Role(name='engineer') db_session.add(engineer) peter = Employee(name='Peter', department=engineering, role=engineer) db_session.add(peter) roy = Employee(name='Roy', department=engineering, role=engineer) db_session.add(roy) tracy = Employee(name='Tracy', department=hr, role=manager) db_session.add(tracy) db_session.commit()
def create_data(): Base.metadata.create_all(bind=engine) engineering = Department(name='Engineering') db_session.add(engineering) hr = Department(name='Human Resources') db_session.add(hr) peter = Employee(name='Peter', department=engineering, hobbies="['pool', 'sitting down']", results="{'code': 'A+', 'team work': 'C'}") db_session.add(peter) roy = Employee(name='Roy', department=engineering, hobbies="['football', 'mechanics']", results="{'code': 'B', 'team work': 'A'}") db_session.add(roy) tracy = Employee(name='Tracy', department=hr, hobbies="['smoking', 'guns']", results="{'code': 'A+', 'team work': 'B'}") db_session.add(tracy) db_session.commit() return jsonify({'status': 'ok'})
def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() from models import Department, Employee, Role Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) # Create the fixtures one_app = Department(name='One App(人工智能)') db_session.add(one_app) tire = Department(name='TireO2O(卖轮胎的)') db_session.add(tire) hr = Department(name='HR(协助人口买卖)') db_session.add(hr) manager = Role(name='product manager') db_session.add(manager) engineer = Role(name='engineer') db_session.add(engineer) hydra = Employee(name='Hydra', department=one_app, role=engineer) db_session.add(hydra) samuel = Employee(name='Samuel', department=one_app, role=engineer) db_session.add(samuel) tony = Employee(name='Tony', department=one_app, role=manager) db_session.add(tony) daisy = Employee(name='Daisy', department=tire, role=manager) db_session.add(daisy) kyle = Employee(name='Kyle', department=tire, role=engineer) db_session.add(kyle) xenia = Employee(name='Xenia', department=hr, role=manager) db_session.add(xenia) db_session.commit()
def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() from models import Department, Employee, Role Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) # Create the fixtures engineering = Department(name='Engineering') db_session.add(engineering) hr = Department(name='Human Resources') db_session.add(hr) manager = Role(name='manager') db_session.add(manager) engineer = Role(name='engineer') db_session.add(engineer) peter = Employee(name='Peter', department=engineering, role=engineer) db_session.add(peter) roy = Employee(name='Roy', department=engineering, role=engineer) db_session.add(roy) tracy = Employee(name='Tracy', department=hr, role=manager) # postgresql specific dialects tests # tracy.articles = [1, 2, 3, 4] # tracy.json_data = {"test_json": "test_json"} # tracy.jsonb_data = {"test_jsonb": "test_jsonb"} # tracy.hstore_data = {"test_hstore": "test_hstore"} db_session.add(tracy) db_session.commit()
def parse_schedule(): html = open("switcher/schedule.txt") counter = 0 department = "" for line in html: print counter counter += 1 if re.findall(r'\S+', line) == []: continue x = re.findall('([A-Z]+[\s,/&]*?[A-Z]+)\s\s+([0-9A-Z]+)\s+([\s\S]+[\S])', line) if x == []: department = line.strip() #print department #""" d = Department() d.init(department) d.save() #""" else: #print x code = x[0][0] + "." + x[0][1] + ".Spring.2014" #""" c = Course() c.init(code, d) c.save()
def departmentJobname(): ''' 新增部门名称,岗位名称及其显示 ''' department = Department.query.order_by('id desc').all() jobname = Jobname.query.order_by('id desc').all() if request.method == 'POST': department = request.form.get('department', '') jobname = request.form.get('jobname', '') if department and jobname: db.session.add(Department(department)) db.session.add(Jobname(jobname)) db.session.commit() elif department: db.session.add(Department(department)) db.session.commit() elif jobname: db.session.add(Jobname(jobname)) db.session.commit() return redirect(url_for('.departmentJobname')) return render_template('userManage/departmentJobname.html', data=locals())
def get_dep_by_id(_id, lang='en', fields=[]): item = {} if lang == 'en': item = Department.objects(_id=_id).only( *fields).exclude('translation').first() elif lang: item = Department.objects(_id=_id, translation__language=lang).first() return item
def create_department(): #pass the model where the data is to be sent for saving ie department model #Pass the form data from the frontend form = DepartmentForm(request.form) if request.method == 'POST': department = Department() department.name = form.name.data db.session.add(department) db.session.commit() return render_template('departments/create_department.html', form=form)
def populate_test_data(): with database: database.drop_tables([Department, Person]) database.create_tables([Department, Person]) dpts = [('Бухгалтерия',), ('Отдел автоматизации',), ('Отдел продаж',)] with database.atomic(): Department.insert_many(dpts, fields=[Department.name]).execute() Person.insert_many(get_persons()).execute()
def creating_department(): departments = Department.query.all() form = DepartmentForm(request.form) if request.method == "POST": name = form.name.data chief = form.chief.data Department.save(Department(name=name, chief=chief)) return render_template('department.html', departments=departments, form=form)
def init_db(): Department.objects(name="Engineering").update_one(set__name="Engineering", upsert=True) engineering = Department.objects.get(name="Engineering") print(engineering) Department.objects(name="Human Resources").update_one( set__name="Human Resources", upsert=True) hr = Department.objects.get(name="Human Resources") print(hr) Role.objects(name="manager").update_one(set__name="manager", upsert=True) manager = Role.objects.get(name="manager") print(manager) engineer = Role.objects(name="engineer").update_one(set__name="engineer", upsert=True) engineer = Role.objects.get(name="engineer") print(engineer) task1 = Task(name="Build apps") # task1.save() task2 = Task(name="Graphql tutorials") # task2.save() task3 = Task(name="Mongodb tutorials") # task3.save() task4 = Task(name="Graphql Relay") # task4.save() aman = Employee( name="Aman", department=engineering, roles=[engineer], tasks=[task2, task3, task4], ) richa = Employee( name="Richa", department=engineering, roles=[engineer], leader=aman, tasks=[task1, task2], ) rian = Employee(name="Rian", department=hr, roles=[manager], tasks=[task2, task3]) try: aman.save() richa.save() rian.save() except NotUniqueError: pass except ValidationError: pass
def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() from models import Department, User, Role, Dataset Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) # Create the fixtures engineering = Department(name='Engineering') db_session.add(engineering) hr = Department(name='Human Resources') db_session.add(hr) manager = Role(name='manager') db_session.add(manager) engineer = Role(name='engineer') db_session.add(engineer) peter = User(name='Peter', department=engineering, role=engineer) db_session.add(peter) roy = User(name='Roy', department=engineering, role=engineer) db_session.add(roy) tracy = User(name='Tracy', department=hr, role=manager) db_session.add(tracy) # Dataset import random from random import randint from faker import Faker fake = Faker('en_US') nPoints = 11 # data = {'x': [randint(0, 1000) for i in range(nPoints)], 'z': [float(random.randrange(0, 1000))/100 for i in range(nPoints)], 'names': [fake.name() for i in range(nPoints)] } data = { 'x': [int(i) for i in range(nPoints)], 'z': [float(i) for i in range(nPoints)], 'names': [fake.name() for i in range(nPoints)] } test_data1 = Dataset(name='dataset1', description='First dataset', table_name='data1', enabled=True, raw=data) db_session.add(test_data1) # data = {'x': [randint(0, 1000) for i in range(nPoints)], 'z': [float(random.randrange(0, 1000))/100 for i in range(nPoints)], 'names': [fake.name() for i in range(nPoints)] } # test_data2 = Dataset(name='dataset2', description='Second dataset', table_name='data2', enabled=False, raw=data) # db_session.add(test_data2) db_session.commit()
def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() from models import Department, Employee, Role for model in [Department, Employee, Role]: if model.exists(): model.delete_table() model.create_table(read_capacity_units=1, write_capacity_units=1, wait=True) # Create the fixtures engineering = Department(id=str(uuid4()), name='Engineering') engineering.save() hr = Department(id=str(uuid4()), name='Human Resources') hr.save() manager = Role(id=str(uuid4()), name='manager') manager.save() engineer = Role(id=str(uuid4()), name='engineer') engineer.save() peter = Employee(id=str(uuid4()), name='Peter', department=engineering, role=engineer) peter.save() roy = Employee(id=str(uuid4()), name='Roy', department=engineering, role=engineer) roy.save() tracy = Employee(id=str(uuid4()), name='Tracy', department=hr, role=manager) tracy.save()
def init_db(): # Create the fixtures engineering = Department(name='Engineering') engineering.save() hr = Department(name='Human Resources') hr.save() manager = Role(name='manager') manager.save() engineer = Role(name='engineer') engineer.save() peter = Person(first_name='Peter', last_name='Parker', department=engineering, role=engineer) peter.save() roy = Person(first_name='Roy', last_name='Royce', department=engineering, role=engineer) roy.save() tracy = Person(first_name='Tracy', last_name='Monita', department=hr, role=manager) tracy.save()
def make_data(db): from models import Department, Worker, WorkCommand db.create_all() _commit = (lambda *objs: commit(db, *objs)) d_a = Department(name='A') d_b = Department(name='B') d_c = Department(name='C') _commit(d_a, d_b, d_c) workers = [ Worker(name='Noah', department=d_a, age=random.randrange(18, 61)), Worker(name='Liam', department=d_a, age=random.randrange(18, 61)), Worker(name='Jacob', department=d_a, age=random.randrange(18, 61)), Worker(name='Mason', department=d_a, age=random.randrange(18, 61)), Worker(name='William', department=d_a, age=random.randrange(18, 61)), Worker(name='Ethan', department=d_a, age=random.randrange(18, 61)), Worker(name='Michael', department=d_b, age=random.randrange(18, 61)), Worker(name='Alexander', department=d_b, age=random.randrange(18, 61)), Worker(name='Jayden', department=d_b, age=random.randrange(18, 61)), Worker(name='Daniel', department=d_c, age=random.randrange(18, 61)), Worker(name='Sophia', department=d_c, age=random.randrange(18, 61)), Worker(name='Emma', department=d_c, age=random.randrange(18, 61)), Worker(name='Olivia', department=d_c, age=random.randrange(18, 61)), Worker(name='Isabella', department=d_c, age=random.randrange(18, 61)), Worker(name='Ava', department=d_c, age=random.randrange(18, 61)), Worker(name='Mia', department=d_c, age=random.randrange(18, 61)), Worker(name='Emily', department=d_c, age=random.randrange(18, 61)), Worker(name='Abigail', department=d_c, age=random.randrange(18, 61)), Worker(name='Madison', department=d_c, age=random.randrange(18, 61)), Worker(name='Elizabeth', department=d_c, age=random.randrange(18, 61)), ] _commit(*workers) work_commands = [] for worker in workers: for i in xrange(random.randrange(1, 559)): quantity = random.randrange(1, 21) today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) # last six month created = today - timedelta(random.randrange(1, 186)) work_commands.append( WorkCommand(worker=worker, quantity=quantity, created=created)) _commit(*work_commands)
def get_departments(lang='en', fields=[]): if lang == 'en': items = Department.objects().exclude("translation").only( *fields).order_by('code') items = items2dict(items) elif lang: items = Department.objects(translation__language=lang).only( *fields).only('translation').order_by('translation.code') items = items2dict(items) items = translations_unify(items, lang) else: raise BadRequest return items
def init_db(): Base.query = db_session.query_property() Base.metadata.create_all(bind=engine) engineering = Department(name='Engineering') db_session.add(engineering) hr = Department(name='Human Resources') db_session.add(hr) db_session.add(Employee(name='Peter', department=engineering)) db_session.add(Employee(name='Roy', department=engineering)) db_session.add(Employee(name='Tracy', department=hr)) db_session.commit()
def add_department(department_id): from datetime import datetime as dd new_department = Department(department_id=department_id, created_timestamp=dd.utcnow()) session.add(new_department) session.commit() print(session.query(Department).all()[-1].__dict__)
def department(id): #Get the department by id and the add members to it department = Department() qry = db.session.query(Department).filter(Department.id == id) department = qry.first() #Handle exception for missing id in the databse return render_template( 'departments/department.html', department=department ) #Display the department and the various members and ther positions
def test_view_employees(self): response = self.client.get('/employees') self.assertTrue(response.status_code, 200) department = Department('IT', 'Ivanov I.I', '+38(093)1548-093') employee_1 = Employee('Anna', 'Olekseevna', 'Ivanova', 22, '1998-01-01', '+38(099)1548123', 'trainee', 2, 1, 10000) db.session.add(department) db.session.add(employee_1) db.session.commit() employees = db.session.query(Employee.id, Employee.first_name, Employee.patronymic, Employee.last_name, Employee.age, Employee.birth_date, Employee.phone, Employee.position, Employee.experience, Employee.salary, Department.name.label('department_name')) \ .select_from(Employee) \ .join(Department, isouter=True).all() self.assertEqual(employees[0].id, 1) self.assertEqual(employees[0].first_name, 'Anna') self.assertEqual(employees[0].patronymic, 'Olekseevna') self.assertEqual(employees[0].last_name, 'Ivanova') self.assertEqual(employees[0].age, 22) self.assertEqual(employees[0].birth_date, date(1998, 1, 1)) self.assertEqual(employees[0].position, 'trainee') self.assertEqual(employees[0].experience, 2) self.assertEqual(employees[0].department_name, 'IT') self.assertEqual(employees[0].salary, 10000)
def addaction(): dpmname = request.form.get("dpmname") dpmnames = Department(dpmname=dpmname) db.session.add(dpmnames) db.session.commit() return redirect(url_for('show_all'))
def update_user(payload={}, fields=[]): if 'user_id' in payload: user_id = payload.pop('user_id') # print(payload) user = User.objects(pk=user_id) if user is not None: user = user.first() if 'country' in payload: payload['country'] = Country(pk=payload['country']) if 'gender' in payload and payload['gender'] is not None: payload['gender'] = Gender(pk=int(payload['gender'])) if 'languages' in payload: payload['languages'] = [ Language(pk=lang) for lang in payload['languages'] ] if 'department' in payload and payload['department'] is not None: payload['department'] = Department( pk=int(payload['department'])) if 'chair' in payload and payload['chair'] is not None: payload['chair'] = Chair(pk=int(payload['chair'])) if 'bio' in payload: payload["bio"] = payload['bio'] updated = user.update(**payload) print(user) return updated >= 1, payload else: print("Not found") return False, None else: print("Not found") return False, None
def get(self): code = int(self.request.get('code', '0')) q = Department.gql('WHERE dptCode >= :1 ORDER BY dptCode', code) dpts = q.fetch(limit=2) nowDpt = dpts[0] soup = BeautifulSoup( urllib2.urlopen( nowDpt.dptLink ) ) list = soup.table.findAll('a') for one in list: text = one.text; name = re.split('[0-9]', text)[0] code = text[ len(name):].split(' ')[0].split('(')[0] # Dealing w/ the special cases doc = Doctor.all().filter('docCode =', code).get() if not doc and len(code) != 0: doc = Doctor() doc.docName = name doc.docCode = code doc.put() if( len(dpts) > 1): nextDpt = dpts[1] nextUrl = '/parse/doctor?code=%d' % nextDpt.dptCode nextName = nextDpt.dptName else: nextUrl = '/' nextName = 'END OF PARSING' context = { 'type' : 'Doctor', 'nextUrl' : nextUrl, 'nextName': nextName, } path = os.path.join( os.path.dirname('__file__'), 'templates', 'parser.html') self.response.out.write( template.render( path, context) )
def get(self): # Get all the displayable books books_query = Book.query(ancestor=ROOT_BOOK_KEY) # Get the books currently in the cart cart_query = [] # check for a person and filter the books if self.person: books_query = books_query.filter(ndb.OR(Book.cart_key == None, Book.cart_key == self.person.key)) cart_query = self.person.get_cart() else: # remove all the books that are in someone's cart books_query = books_query.filter(Book.cart_key == None) books_query = books_query.order(-Book.last_touch_date_time) # Get additional details needed to populate lists dept_query = Department.query(ancestor=ROOT_DEPT_KEY).order(Department.abbrev) book_conditions = Book.get_conditions() self.values.update({"books_query": books_query, "cart_query" : cart_query, "dept_query": dept_query, "book_conditions": book_conditions}) self.render(**self.values)
def test_create_employee(self): employee = Employee('Anna', 'Olekseevna', 'Ivanova', 22, '1998-01-01', '+38(099)1548123', 'trainee', 2, 1, 10000) department = Department('IT', 'Ivanov I.I', '+38(093)1548-093') db.session.add(department) db.session.add(employee) db.session.commit() department = Department.query.get(1) self.assertEqual(department.id, 1) self.assertEqual(department.name, 'IT') self.assertEqual(department.manager, 'Ivanov I.I') self.assertEqual(department.phone, '+38(093)1548-093') self.assertEqual(employee.first_name, 'Anna') self.assertEqual(employee.patronymic, 'Olekseevna') self.assertEqual(employee.last_name, 'Ivanova') self.assertEqual(employee.age, 22) self.assertEqual(employee.birth_date, date(1998, 1, 1)) self.assertEqual(employee.phone, '+38(099)1548123') self.assertEqual(employee.position, 'trainee') self.assertEqual(employee.experience, 2) self.assertEqual(employee.department_id, 1) self.assertEqual(employee.salary, 10000) assert department in db.session assert employee in db.session
def extract_results(html, year, season): soup = BeautifulSoup(html, 'html.parser').find_all(id='searchResultsPanel')[0] soup = soup.find_all('div', recursive=False)[1].find_all('table', limit=1)[0] semester = Semester(year, season) for row in soup.find_all('tr', recursive=False): tds = row.find_all('td', recursive=False) if not tds: continue department, number, section = extract_text(tds[1]).split() course = Course(Department.get(department), number) title = extract_text(tds[2]) units = int(extract_text(tds[3])) instructors = [] for tag in tds[4].find_all('abbr'): instructor_str = tag['title'] if instructor_str == 'Instructor Unassigned': instructors.append(None) else: instructors.append(Faculty(instructor_str, *Faculty.split_name(instructor_str))) meetings = [] for tr in tds[5].find_all('tr'): meetings.append(Meeting.from_str(*(extract_text(tag) for tag in tr.find_all('td')))) cores = list(set(Core.get(extract_text(tag)) for tag in tds[6].find_all('abbr'))) if not cores: cores = [] seats = int(extract_text(tds[7])) enrolled = int(extract_text(tds[8])) reserved = int(extract_text(tds[9])) reserved_open = int(extract_text(tds[10])) waitlisted = int(extract_text(tds[11])) Offering(semester, course, section, title, units, tuple(instructors), tuple(meetings), tuple(cores), seats, enrolled, reserved, reserved_open, waitlisted)
def ADDepartment(): system('cls') print('Enter Name Of Department') name = input() departmentName = Department(name=name) session.add(departmentName) session.commit()
def get(self): code = int(self.request.get('code', '0')) q = Department.gql('WHERE dptCode >= :1 ORDER BY dptCode', code) dpts = q.fetch(limit=2) nowDpt = dpts[0] soup = BeautifulSoup( urllib2.urlopen( nowDpt.dptLink ) ) trlist = soup.table.findAll('tr', align='left') for tr in trlist: tdlist = tr.findAll('td') column = 0; for td in tdlist: if column == 0: dateStr = td.text.split('(')[1].split(')')[0] month = dateStr.split('/')[0] day = dateStr.split('/')[1] year = str(datetime.datetime.now().year) else: if column == 1: timeStr = 'A' elif column == 2: timeStr = 'B' else: timeStr = 'C' alist = td.findAll(lambda tag: tag.name == 'a' and len(tag.attrs) == 2) for a in alist: text = a.text name = re.split('[0-9]', text)[0] doc = Doctor.all().filter('docName = ', name).get() if doc: clinic = Clinic() link = a['href'] code = link.split('data=')[1].split('&sLoc')[0] clinic.link = tzuPrifix + link clinic.code = code clinic.doctor = doc.key() clinic.dept = nowDpt.key() clinic.date = year + '-' + month + '-' + day + '-' + timeStr clinic.put() column = column + 1 if( len(dpts) > 1): nextDpt = dpts[1] nextUrl = '/parse/clinic?code=%d' % nextDpt.dptCode nextName = nextDpt.dptName else: nextUrl = '/' nextName = 'END OF PARSING' context = { 'type' : 'Clinic', 'nextUrl' : nextUrl, 'nextName': nextName, } path = os.path.join( os.path.dirname('__file__'), 'templates', 'parser.html') self.response.out.write( template.render( path, context) )
def get(self): books_query = self.person.get_books_for_sale() dept_query = Department.query(ancestor=ROOT_DEPT_KEY).order(Department.abbrev) book_conditions = Book.get_conditions() self.values.update({"books_query": books_query, "dept_query": dept_query, "book_conditions": book_conditions}) self.render(**self.values)
def employees(self): # ------------------------- # List all employees # ------------------------- try: results = Employee().list_all_employees_filtered(Department()) if results is None: app.logger.info('No matches between Employees\ and Department tables') abort(422) dtos = [] for emp, dep in results: dto = EmployeeDto( id=emp.id, name=emp.name, department_id=emp.department_id, department_name=dep.name, title=emp.title, emp_number=emp.emp_number, address=emp.address, phone=emp.phone, wage=emp.wage, is_active=emp.is_active ) dtos.append(dto) departments = Department().list_all_departments() if departments is None or len(departments) == 0: app.logger.info('Departments table is empty?') abort(422) return render_template( 'grocery/employees.html', data=dtos, departments=departments, nickname=session[conf_profile_key]['nickname'] if 'POSTMAN_TOKEN' not in request.headers and 'test_permission' not in request.headers else 'Guest') except BaseException: app.logger.info('An error occurred. Employees not available') abort(422)
def add_department(self, entity): if entity.name == None: raise tt.InvalidValueException( 2, "no department name value exception") entity = Department(entity) self.session.add(entity) self.session.commit() print("Processing department {0}".format(entity.name)) return True
def department_add(): form = DepartmentNewEdit() if form.validate_on_submit(): dept = Department(name=form.name.data, description=form.description.data, isfin=form.isfin.data, organization=current_user.organization) db.session.add(dept) db.session.commit() flash('Department Added.') return redirect(url_for('department_list_all')) return render_template('/admin/dept_new.html', form=form)
def post(self): okey = False errorMessage = '' docData = self.request.get('doctor') deptData = self.request.get('dept') timeData = self.request.get('time') idData = self.request.get('id') firstData = self.request.get('first') phoneData = self.request.get('phone') if len(phoneData) == 0 and bool(firstData.lower() == 'true'): jsDic = { "status" : "2", "message": [{"phone":"Phone Number"}], } self.response.headers['Content-Type'] = 'application/json' self.response.out.write( simplejson.dumps(jsDic) ) return # Check for rest values: doc = Doctor.all().filter('docCode =', docData ).get() dept = Department.all().filter('dptCode =', int(deptData) ).get() if not doc: errorMessage = 'BadDoctorId' elif not dept: errorMessage = 'BadDeptId' elif not timeData: errorMessage = 'MissingTimeInfo' else: clinic = Clinic.all().filter('doctor =', doc).filter('dept =', dept).filter('date =', timeData).get() if not clinic: errorMessage = 'WrongInfo' else: okey = True if okey: # Save the info to the db: reg = Register() reg.doc = doc reg.dept = dept reg.link = clinic.link reg.theId = idData reg.isFirst = bool(firstData.lower() == 'true') reg.phone = phoneData reg.put() self.redirect('/tools/register?key=%s' % str(reg.key()) ) else: jsDic = { "status":"1", "message": errorMessage, } self.response.headers['Content-Type'] = 'application/json' self.response.out.write( simplejson.dumps(jsDic) )
def get(self): books_query = Book.query(ancestor=ROOT_BOOK_KEY).order(-Book.last_touch_date_time) # Get additional details needed to populate lists dept_query = Department.query(ancestor=ROOT_DEPT_KEY).order(Department.abbrev) book_conditions = Book.get_conditions() # Perform the search from the "q"uery param q = self.request.get("q") if q: q = q.lower() books_query = books_query.filter(ndb.OR(Book.title_lower == q, Book.dept == q, Book.author_lower == q, Book.isbn == q)) self.values.update({"books_query": books_query, "dept_query": dept_query, "book_conditions": book_conditions}) self.render(**self.values)
def get(self): soup = BeautifulSoup( urllib2.urlopen( dptUrl ) ) table = soup.form.find('table', id='Table1') tdlist = table.findAll('td') code = 0; for td in tdlist: name = td.a.text.split('(')[0] # Using split to escape the spcial case dpt = Department() dpt.dptName = name # Removing the @ character dpt.dptCode = code code = code + 1 urlStr1 = 'http://www.tzuchi.com.tw/tchw/opdreg/OpdTimeShow.aspx?Depart=' urlStr2 = '&HospLoc=3' dpt.dptLink = urlStr1 + urllib2.quote(name.encode('utf-8')) + urlStr2 dpt.put() self.response.out.write("Finish for department list ...")
def initial(self): u = User("Sasha", "Chepurnoi", 20) u2 = User("Erik", "Gimiranov", 18) u3 = User("Dima", "Lysogor", 27) p = Product("Bread", 1000) p2 = Product("Water", 4000) p3 = Product("Chocolate", 500) d = Department("Food store 1", "Street 1") d2 = Department("Food store 2", "Street 2") d3 = Department("Food store 3", "Street 3") self.users.insert(u.mongify()) self.users.insert(u2.mongify()) self.users.insert(u3.mongify()) self.products.insert(p.mongify()) self.products.insert(p2.mongify()) self.products.insert(p3.mongify()) self.departments.insert(d.mongify()) self.departments.insert(d2.mongify()) self.departments.insert(d3.mongify())
def get(self): depts = Department.all() for one in depts: one.delete() return
def get(self): # CLEAR All query = Department.query() entries = query.fetch() entry_keys = [entry.key for entry in entries] ndb.delete_multi(entry_keys) query = House.query() entries = query.fetch() entry_keys = [entry.key for entry in entries] ndb.delete_multi(entry_keys) query = Class.query() entries = query.fetch() entry_keys = [entry.key for entry in entries] ndb.delete_multi(entry_keys) query = Student.query() entries = query.fetch() entry_keys = [entry.key for entry in entries] ndb.delete_multi(entry_keys) user = users.get_current_user() if user and users.is_current_user_admin(): # Create houses houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"] for house in houses: House(house_name=house).put() # Create departments deps = [ {"code": "CS", "name": "Computer Science"}, {"code": "BA", "name": "Business Administration"}, {"code": "PHY", "name": "Physics"}, {"code": "MAT", "name": "Mathematics"}, {"code": "DRA", "name": "Drama"}, {"code": "ECE", "name": "Electrical Engineering"}, ] for dep in deps: Department(id=dep["code"], dept_name=dep["name"]).put() # Create 40 classes for department, update depts classes_count = 40 for dept in deps: department_key = ndb.Key("Department", dept["code"]) department_obj = department_key.get() for i in range(classes_count): class_full_name = "%s - Class %d" % (dept["name"], i) department = department_key class_key = Class(id="%s-%d" % (dept["code"], i), class_full_name=class_full_name).put() department_obj.classes.append(class_key) department_obj.put() # Create students students_count = 1000 random.seed() all_classes = Class.query().fetch() all_houses = House.query().fetch() for i in range(students_count): house = random.choice(all_houses) house_key = house.key student_name = "Student %d" % i student_year = random.randint(1, 4) current_classes = random.sample(all_classes, 5) current_classes_keys = [el.key for el in current_classes] all_classes_keys = [el.key for el in all_classes] leftovers = set(all_classes_keys) - set(current_classes_keys) completed_classes_keys = random.sample(leftovers, 6 * (student_year - 1)) student_key = Student( student_name=student_name, student_year=student_year, current_classes=current_classes_keys, completed_classes=completed_classes_keys, house=house_key, ).put() house.students.append(student_key) for el in current_classes: el.students_enrolled.append(student_key) # save new status of houses and current classes for house in all_houses: house.put() for current_class in all_classes: current_class.put() elif user and not users.is_current_user_admin(): self.redirect(users.create_logout_url("/create_entries")) else: self.redirect(users.create_login_url("/create_entries"))
def get(self): # CLEAR All query = Department.query() entries =query.fetch() entry_keys =[entry.key for entry in entries] ndb.delete_multi(entry_keys) query = House.query() entries =query.fetch() entry_keys =[entry.key for entry in entries] ndb.delete_multi(entry_keys) query = Class.query() entries =query.fetch() entry_keys =[entry.key for entry in entries] ndb.delete_multi(entry_keys) query = Student.query() entries =query.fetch() entry_keys =[entry.key for entry in entries] ndb.delete_multi(entry_keys) user = users.get_current_user() if user and users.is_current_user_admin(): # Create houses houses = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin'] for house in houses: House(house_name=house).put() # Create departments deps = [ {'code': 'CS', 'name': 'Computer Science'}, {'code': 'BA', 'name': 'Business Administration'}, {'code': 'PHY', 'name': 'Physics'}, {'code': 'MAT', 'name': 'Mathematics'}, {'code': 'DRA', 'name': 'Drama'}, {'code': 'ECE', 'name': 'Electrical Engineering'}, ] for dep in deps: Department(id = dep['code'], dept_name = dep['name']).put() # Create 40 classes for department, update depts classes_count = 40 for dept in deps: department_key = ndb.Key('Department', dept['code']) department_obj = department_key.get() for i in range(classes_count): class_full_name = "%s - Class %d" % (dept['name'] ,i) class_key = Class(id='%s-%d'%(dept['code'], i), class_full_name = class_full_name, department = department_key).put() department_obj.classes.append(class_key) department_obj.put() # Create students students_count = 1000 random.seed() all_classes = Class.query().fetch() all_houses = House.query().fetch() for i in range(students_count): house = random.choice(all_houses) house_key = house.key student_name = 'Student %d'% i student_year = random.randint(1,4) current_classes = random.sample(all_classes, 5) current_classes_keys = [el.key for el in current_classes] all_classes_keys = [el.key for el in all_classes] leftovers = set(all_classes_keys) - set(current_classes_keys) completed_classes_keys = random.sample(leftovers, 6*(student_year-1)) student_key = Student( student_name = student_name, student_year = student_year, current_classes = current_classes_keys, completed_classes = completed_classes_keys, house = house_key).put() house.students.append(student_key) for el in current_classes: el.students_enrolled.append(student_key) # save new status of houses and current classes for house in all_houses: house.put() for current_class in all_classes: current_class.put() elif user and not users.is_current_user_admin(): self.redirect(users.create_logout_url('/create_entries')) else: self.redirect(users.create_login_url('/create_entries'))
def post(self): docData = self.request.get('doctor') deptData = self.request.get('dept') timeData = self.request.get('time') doc = Doctor.all().filter('docCode =', docData ).get() dept = Department.all().filter('dptCode =', int(deptData) ).get() # Check for post data: errorMessage = None if not doc: errorMessage = 'BadDoctorId' elif not dept: errorMessage = 'BadDeptId' elif not timeData: errorMessage = 'MissingTimeInfo' else: clinic = Clinic.all().filter('doctor =', doc).filter('dept =', dept).filter('date =', timeData).get() if not clinic: errorMessage = 'WrongInfo' if errorMessage: jsDic = { "status":"1", "message": errorMessage, } self.response.headers['Content-Type'] = 'application/json' self.response.out.write( simplejson.dumps(jsDic) ) return vals = {} vals['RadioButtonList1'] = '花蓮' vals['txtMRNo'] = 'A123123123' vals['btnQry'] = '查詢' vals['__EVENTARGUEMENT'] = '' vals['__EVENTTARGET'] = '' vals['__VIEWSTATE'] = '' cookie = cookielib.CookieJar() opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cookie)) #Operation: GET ----------------------' req = urllib2.Request(cancelUrl) rsp = opener.open(req) soup = BeautifulSoup(rsp) qText = soup.find(id='lblQuestion').text if len(qText.split('+')) == 2: A = qText.split('+')[0] B = qText.split('+')[1].split('=')[0] C = int(A) + int(B) elif len(qText.split('-')) == 2: A = qText.split('-')[0] B = qText.split('-')[1].split('=')[0] C = int(A) - int(B) vals['txtAnswer'] = str(C) vals['__EVENTVALIDATION'] = soup.find(id='__EVENTVALIDATION')['value'] vals['__VIEWSTATE'] = soup.form.find(id='__VIEWSTATE')['value'] #Operation: POST --------------------' req = urllib2.Request(cancelUrl, urllib.urlencode(vals) ) rsp = opener.open(req) soup = BeautifulSoup(rsp) error = soup.find(id='Label5') if error: # No Registeration jsDic = { "status":"1", "message": error.text, } self.response.headers['Content-Type'] = 'application/json' self.response.out.write( simplejson.dumps(jsDic) ) return rTable = soup.find(id='dgList') results = rTable.findAll('tr') row = 0 target = None for one in results: if row != 0: tds = one.findAll('td') col = 0 for td in tds: if col == 0: script = td.find('a')['href'] elif col == 1: date = td.text elif col == 2: time = td.text elif col == 4: docInfo = td.text col = col + 1 year = str(int(date[:3]) + 1911) month = date[3:5] day = date[5:] if time == u'早上': time = 'A' elif time == u'下午': time = 'B' elif time == u'晚上': time = 'C' datetime = year + '-' + month + '-' + day + '-' + time docCode = docInfo.split('(')[1].split(')')[0].split(' ')[0] if doc.docCode == docCode and clinic.date == datetime: target = script.split('\'')[1].split('\'')[0] break row = row + 1 if target: vals['__EVENTTARGET'] = target vals['__EVENTVALIDATION'] = soup.find(id='__EVENTVALIDATION')['value'] vals['__VIEWSTATE'] = soup.form.find(id='__VIEWSTATE')['value'] del vals['btnQry'] req = urllib2.Request(cancelUrl, urllib.urlencode(vals) ) rsp = opener.open(req) jsDic = { "status": "0" } else: jsDic = { "status":"1", "message": "RecordNotFound", } self.response.headers['Content-Type'] = 'application/json' self.response.out.write( simplejson.dumps(jsDic) )
def get(self): departments = Department.all() for one in departments: one.delete() self.response.out.write('Delete all department data ...')