def save(self): """ Save registration forms data into User and Staff. If any save operation fails, the others will be rolled back. @return: User instance """ data = self.cleaned_data try: user = User(username=data["username"]) user.email = data["email"] user.set_password(data["password"]) user.first_name = data["firstname"] user.last_name = data["lastname"] user.is_active = True user.save() if data["team"]: try: g = get_object_or_404(Group, pk=data["team"]) user.groups.add(g) except: pass try: staff = Staff(user=user) staff.gender = data["gender"] staff.role = data["role"] staff.save() return user except Exception, e: logger.error("RegisterForm.save():%s" % e) user.delete() raise e except Exception, e: logger.error("RegisterForm.save():%s" % e) raise e
def get(self, id): if Staff.select().count() != 0: query = Staff.select() staff = get_object_or_404(query, Staff.id == int(id)) return render_template('staffs/staff.html', staff=staff, title=staff.name) else: content = 'There are current no staff' return render_template('infor.html', content=content)
def get(self, page=1): max_page = Staff.max_staff_page_all() if Staff.select().count() != 0: staffs = Staff.select().paginate(page, 10) return render_template('staffs/simlist.html', staffs=staffs, max_page=max_page, page=page) else: content = 'No staffs hav been added yet' return render_template('info.html', content=content, title='staff')
def test_staff_model_does_not_find_row_if_it_does_not_exist(initialize_db): """ Tests that model does not find row correctly if it does not exist in the db. Args: initialize_db (None): initializes the database and drops tables when test function finishes. """ with raises(ClientError) as err: Staff.find_by_id(1) assert err.value.message == 'cannot find specified staff' assert err.value.status_code == 404
def multiple_valid_staff_models(initialize_db): """ A fixture for creating a multiple valid staff. Args: initialize_db (None): initializes the database and drops tables when test function finishes. """ staff = [ Staff(username='******', avatar_url='').save(), Staff(username='******', avatar_url='').save(), Staff(username='******', avatar_url='').save(), ] return staff
def new_staff(): if request.method == "GET": if Staff.query.filter(Staff.username.like(session.get("logged_in")), Staff.admin.like(1)).scalar() is None: flash("You do not have permission to access that page.") return redirect(url_for("default")) return render_template("new_staff.html") elif request.method == "POST": if not re.match(r"[^@]+@[^@]+\.[^@]+", request.form["email"]): flash("Please enter a valid email address.") return redirect(url_for('new_staff')) elif Staff.query.filter_by( username=request.form["username"]).scalar() is not None: flash("There's already a staff member with that username.") return redirect(url_for('new_staff')) elif Staff.query.filter_by( email=request.form["email"]).scalar() is not None: flash("There's already a staff member with that email.") return redirect(url_for('new_staff')) newStaff = Staff(firstname=request.form["firstname"], lastname=request.form["lastname"], username=request.form["username"], password=request.form["password"], email=request.form["email"], admin=False) db.session.add(newStaff) try: db.session.commit() flash("{}'s profile was successfully created.".format( request.form["firstname"])) return redirect(url_for('new_staff')) except exc.SQLAlchemyError: flash("There was a problem adding the staff member.") return redirect(url_for('new_staff'))
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding users user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='staff') staff = Staff(user) db.session.add(staff) user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='john_doe') student = Student(user, 'U1722') db.session.add(student) # adding quizzes qz = Quiz(1, 'quiz', True, '2020-03-21', '2020-03-22') db.session.add(qz) # adding quizattempts qa = initializeQuizAttempt(2, 1, 100) db.session.add(qa) db.session.commit()
def get_context(self, id=None): form_cls = model_form(Staff) if id: query = Staff.select() staff = get_object_or_404(query, Staff.id == id) if request.method == 'POST': form = form_cls(request.form, intial=staff.bio) else: form = form_cls(obj=staff) else: staff = Staff() form = form_cls(request.form) context = {'staff': staff, 'form': form, 'create': id is None} return context
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding users user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='john_doe') staff = Staff(user) db.session.add(staff) # adding courses course = Course(index='cz3003') db.session.add(course) # adding quizzes quiz = Quiz( staff_id=1, name="Quiz Test", is_fast=True, date_start='2020-03-01', date_end='2020-03-31', ) db.session.add(quiz) db.session.commit()
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding courses course = Course(index='cz3003') db.session.add(course) # adding users user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='staff') staff = Staff(user) db.session.add(staff) # adding quizzes qz = Quiz(1, 'quiz', True, '2020-03-21', '2020-03-22') db.session.add(qz) # adding RsQuizCourseAssign rs = initializeRsQuizCourseAssign(1, 'cz3003') db.session.add(rs) db.session.commit()
def register(): """Registers the user.""" if g.customer: return redirect(url_for('timeline')) error = None if request.method == 'POST': if g.owner: if not request.form['theUsername']: error = 'You have to enter a username' elif not request.form['password']: error = 'You have to enter a password' elif request.form['password'] != request.form['password2']: error = 'The two passwords do not match' elif get_staff_id(request.form['theUsername']) is not None: error = 'The username is already taken' else: db.session.add(Staff(request.form['theUsername'], generate_password_hash(request.form['password']))) db.session.commit() flash('You were successfully registered and can login now') return redirect(url_for('login')) else: if not request.form['theUsername']: error = 'You have to enter a username' elif not request.form['password']: error = 'You have to enter a password' elif request.form['password'] != request.form['password2']: error = 'The two passwords do not match' elif get_customer_id(request.form['theUsername']) is not None: error = 'The username is already taken' else: db.session.add(Customer(request.form['theUsername'], generate_password_hash(request.form['password']))) db.session.commit() flash('You were successfully registered and can login now') return redirect(url_for('login')) return render_template('register.html', error=error)
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding topics topic = Topic(name='seng') db.session.add(topic) # adding lessons lesson = Lesson(topic_id=1, id=1, name='se', content='test') db.session.add(lesson) # adding users user = User('*****@*****.**', encrypt('password'), 'staff_name') staff = Staff(user) db.session.add(staff) # adding quizzes quiz = Quiz(1, 'quiz_name', True, '2020-03-21', '2020-03-22') db.session.add(quiz) db.session.commit()
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding users user_1 = User('*****@*****.**', encrypt('password'), 'student_1') student_1 = Student(user_1, 'U00000000A') db.session.add(student_1) user_2 = User('*****@*****.**', encrypt('password'), 'student_2') student_2 = Student(user_2, 'U00000000B') db.session.add(student_2) user_3 = User('*****@*****.**', encrypt('password'), 'teacher_1') staff_1 = Staff(user_3) db.session.add(staff_1) # adding topics topic = Topic(name='seng') db.session.add(topic) # adding lessons lesson = Lesson(1, 1, 'lesson_1', 'content') db.session.add(lesson) # adding quizzes quiz = Quiz(3, 'quiz_1', True, '2020-03-30', '2020-03-31') db.session.add(quiz) db.session.commit()
def test_flask_seed_model_cli_seeds_to_db_with_all_option(cli_app): """ Tests that db tables are populated `flask seed model` when passed an `all` option. Args: cli_app (function): a flask app factory function that also manages its context. """ # Create a script for running application. obj = ScriptInfo(create_app=cli_app) # Call command, apply arguments and create app. result = CliRunner().invoke(seed_model, ['all'], obj=obj) clients = Client.get_all() staff = Staff.get_all() requests = Request.get_all() comments = Comment.get_all() assert len(clients) == 3 assert len(staff) == 3 assert len(comments) == 14 assert len(requests) == 12 assert result.exit_code == 0
def valid_staff_model(initialize_db): """ A fixture for creating a valid staff model. Args: initialize_db (None): initializes the database and drops tables when test function finishes. """ return Staff(username='******', avatar_url='').save()
def staffer_account(): if request.method=="POST": s = Staff(username=request.form["username"], password=request.form["password"]) db.session.add(s) db.session.commit() flash("The new staff account is created!") return redirect(url_for("owner")) session['logged_in'] = True return render_template("staffer_account.html")
def newstaff(): if request.method == 'POST': new_staff = Staff(username=request.form['username'], password=request.form['password']) db.session.add(new_staff) db.session.commit() flash('New staff account created successfully!') return redirect(url_for('owner')) session['logged_in'] = True return render_template('create_new_account.html')
def create_rab(): if db.session.query(Roles).filter_by( id_role=current_user.id_role).first().name != "Менеджер": return 'What are you doing here?' if request.method == 'GET': return render_template('create_rab.html', role=db.session.query(Roles).filter_by( id_role=current_user.id_role).first().name) if request.method == 'POST': cipher = Salsa20.new(key=secret) fio = request.form['fio'] created = time.strftime('%d/%m/%Y', time.localtime()) # использовать дату dob = request.form['dob'] if request.form['role'] == 'Стажер': role = 1 id_position = 0 elif request.form['role'] == 'Продавец-консультант': role = 1 id_position = 1 elif request.form['role'] == 'Менеджер': role = 2 id_position = 2 email = request.form['email'] phone = request.form['phone'] company = request.form['company'] hash_password = generate_password_hash(request.form['password']) hash_address = request.form['address'] hash_card = str(cipher.nonce + cipher.encrypt(bytes(request.form['card'], 'utf-8'))) amount = request.form['amount'] new_Client = Clients(email=email, fio=fio, created=created, dob=dob, id_role=role) db.session.add(new_Client) db.session.commit() new_Contactdetailsclients = Contactdetailsclients( id_clients=new_Client.id_clients, phone=phone, company=company) new_Secretdate = Secretdate(id_clients=new_Client.id_clients, hash_password=hash_password, hash_address=hash_address) new_Card = Card(id_clients=new_Client.id_clients, hash_card=hash_card, amount=amount) new_Staff = Staff(id_staff=new_Client.id_clients, id_position=id_position) db.session.add(new_Contactdetailsclients) db.session.add(new_Secretdate) db.session.add(new_Card) db.session.add(new_Staff) db.session.commit() return redirect('/login')
def test_staff_model_finds_row_if_it_exists(valid_staff_model): """ Tests that model finds row correctly if it exists in the db. Args: valid_staff_model (Model): a valid model created by a fixture. """ staff = Staff.find_by_id(1) assert staff.username == 'Leroy Jenkins' assert staff.avatar_url == ''
def test_staffUpdate(self): # create a new Staff object and add it to the database user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='staff') stf = Staff(user=user) db.session.add(stf) db.session.commit() # update value of Staff object stf.name = 'Justin' staffUpdate() # fetch updated Staff object from the database stf = Staff.query.filter_by(email='*****@*****.**').first() # check if value of Staff object has been updated print('--- check if value of Staff object has been updated') self.assertEqual('Justin', stf.name)
def test_staff_model_updates_correctly_if_it_exists(valid_staff_model): """ Tests that model __repr__ row correctly. Args: valid_staff_model (Model): a valid model created by a fixture. """ valid_staff_model.update(username="******") updated_staff = Staff.find_by_id(1) assert updated_staff.username == 'Leroy Jenkins'
def post(self, request): user = User.objects.create_user(username=request.POST['username'], email=request.POST['email'], password=request.POST['password']) obj = Staff() obj.firstname = request.POST['username'] obj.email = request.POST['email'] obj.password = request.POST['password'] obj.user = user obj.save() return HttpResponse() StaffLoginView
def save(self): """ Save registration forms data into User and Staff. If any save operation fails, the others will be rolled back. @return: User instance """ data = self.cleaned_data try: user = User(username=data['username']) user.email = data['email'] user.set_password(data['password']) user.first_name = data['firstname'] user.last_name = data['lastname'] user.is_active = True user.save() if data['team']: try: g = get_object_or_404(Group, pk=data['team']) user.groups.add(g) except: pass try: staff = Staff(user=user) staff.gender = data['gender'] staff.role = data['role'] staff.save() return user except Exception, e: logger.error('RegisterForm.save():%s' % e) user.delete() raise e except Exception, e: logger.error('RegisterForm.save():%s' % e) raise e
def initdb_command(): """Creates the database tables.""" db.drop_all() db.create_all() owner = Staff(firstname="Katie", lastname="Pucci", username="******", password="******", email="*****@*****.**", admin=True) db.session.add(owner) db.session.commit() print('Initialized the database.')
def test_staff_model_gets_all_rows_correctly_after_saving(valid_staff_model): """ Tests that model gets correct number of rows when there is data in the table. Args: valid_staff_model (Model): a valid model created by a fixture. """ staffs = Staff.get_all() assert staffs[0].username == 'Leroy Jenkins' assert staffs[0].avatar_url == '' assert len(staffs) == 1
def put(self, bank_id, branch_id): """API Endpoint for adding staff to a branch instance """ args = _staff_create_parser.parse_args() bank = Bank.query.get_or_404(bank_id) branch = BankBranch.query.filter_by(bank=bank, id=branch_id).first_or_404() user = User.query.get_or_404(args['user_id']) staff = Staff(branch=branch, user=user, role=args['role']) user.staff = staff db.session.add(staff) db.session.commit() return json_serialize(staff)
def post(self): data = data_valid_for('POST') logging.debug(data) staff_already_exist = list( filter(lambda t: data['passport_id'] == t.passport_id, DB['staff'])) if not staff_already_exist: DB['staff'].append(Staff(**data)) new_passport_id = str(DB['staff'][-1].passport_id) location = {"Location": f'/api/v0.1/staff/{new_passport_id}'} return {"message": "staff was added successfully"}, 201, location msg = f"staff with passport_id {data['passport_id']} already exists" return {"message": msg}, 400
def post(self, request): user = User.objects.create_user(username=request.POST['username'],email=request.POST['email'],password=request.POST['password']) obj=Staff() obj.firstname = request.POST['username'] obj.email = request.POST['email'] obj.password = request.POST['password'] obj.user = user obj.save() return HttpResponse() StaffLoginView
def _processstaffrows(self, rows): staffs = [] entries = rows.entry for entry in entries: staff = Staff() staff.staffid = processstr(entry, 'staffid') staff.staffname = processstr(entry, 'staffname') staff.staffrole = processstr(entry, 'staffrole') staff.staffdescription = processstr(entry, 'staffdescription') staff.staffemail = processstr(entry, 'staffemail') staffs.append(staff) return staffs
def manage(): error = None if "owner_id" not in session: abort(401) if request.method == "POST": error = validate_staff_input(request.form) if error == None: staff = Staff(request.form["username"], generate_password_hash(request.form["password"])) db.session.add(staff) db.session.commit() flash("Added new staff " + staff.username + " successfully!") reqs = EventRequest.query.order_by(EventRequest.start_datetime.asc()).all() owner = Owner.query.filter_by(owner_id=session["owner_id"]).first() staffings = {} staff = Staff.query.all() return render_template("manage.html", requests=reqs, staff=staff, staffings=staffings, user_name=owner.username, error=error)
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding users user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='john_doe') staff = Staff(user) db.session.add(staff) db.session.commit()
def test_seed_staff_saves_staffs_to_db(initialize_db): """ Tests that `seed_staff` function stores staffs in the db. Args: initialize_db (None): initializes the database and drops tables when test function finishes. """ seed_staff() staff = Staff.get_all() assert staff[0].username == 'Steve Akinyemi' assert staff[1].username == 'Anu Johnson' assert staff[2].username == 'James Waldo' assert len(staff) == 3