def populate_employees(limit: int = 10) -> None: """ Populates 'Employees' Table Parameters: limit (int): Max number of employees per department Returns: None """ logger.info('Populating Employees Database') random.seed(42) Faker.seed(42) faker = Faker() departments = Department.query.all() for department in departments: for _ in range(random.randint(1, limit)): employee = Employee(department_id=department.id, name=faker.name(), birthdate=faker.date_between( start_date='-50y', end_date='-18y').strftime('%m.%d.%Y'), salary=random.randint(700, 2000)) db.session.add(employee) db.session.commit() logger.info('Successfully populated Employees Database')
def _finish_run(self): last_run_str = self.start_time.isoformat() r.set("last_run", last_run_str) logger.info( f"Events: {self.unchanged_event_count} unchanged, {self.new_event_count} new, {self.updated_event_count} updated, {self.deleted_event_count} deleted" )
def unsubscribe(code=None): user = User.query.filter(func.lower(User.uuid) == func.lower(code)).first() if user is not None: user.subscribed = False db.session.add(user) db.session.commit() logger.info('Unsubscribe success - user [' + user.username + '].') flash(gettext('You unsubscribed.')) return redirect(url_for('index'))
def run_migrations_on_dev_server_restart(): logger.info('Running migrations') current = None from sqlalchemy import create_engine with create_engine( f"postgresql://{CONFIG['DB_USER']}:{CONFIG['DB_PW']}" f"@{CONFIG['DB_HOST']}:{CONFIG['DB_PORT']}/{CONFIG['DB_NAME']}" ).connect() as connection: # If the database was just created from scratch, there will be no # alembic_version table, and current will be set to None. with connection.begin(): current = attempt_to_get_alembic_version(connection) if current: logger.info(f'The current revision is {current}') else: logger.info('Could not find a current revision in the DB') # Get the Flask-Migrate config: config = Migrate(app, db, directory=os.path.join(PROJECT_ROOT, 'migrations')).get_config() # We want to run any migrations that haven't been run yet. First, get # all the revision identifiers (as strings) and store them. revisions = [] script_directory = ScriptDirectory.from_config(config) for revision_script in script_directory.walk_revisions(head='head'): revisions.append(revision_script.revision) # walk_revisions starts from the head and goes backwards. We want to # migrate up from scratch, so we need to reverse the order. revisions.reverse() # False if there is a current revision (in which case, we don't want to # start migrating yet), True if there is none and the database was just # created. migrating = False if current else True with app.app_context(): for revision in revisions: if migrating: logger.info(f'Upgrading to {revision}') command.upgrade(config, revision) # One we reach the current revision, we want to upgrade, one step # at a time, for each subsequent revision. If we don't do this, # queries in migrations (but not DDL) will fail. if current and current == revision: migrating = True logger.info('Migrations finished')
def login(): form = LoginForm() if request.method == 'POST': if form.validate_on_submit(): user = User.query.filter(func.lower(User.username) == func.lower(form.username.data)).first() if user is not None and bcrypt.check_password_hash( user.password, form.password.data ): if not user.active: logger.info('Login failed - user not active [' + user.username + '].') flash(gettext('Your account is not activated.')) return redirect(url_for('auth.activate')) login_user(user) logger.info('Login success - user login [' + user.username + '].') flash(gettext('You are logged in.')) return redirect(request.args.get('next') or url_for('index')) else: flash(gettext('Invalid username or password.')) return render_template('login.html', form=form)
def activate(code=None): form = ActivateForm(request.form) if request.method == 'POST': if form.validate_on_submit(): code = form.code.data else: logger.info('Activation failed - Invalid activation code.') flash(gettext('Invalid activation code.')) if code is not None: user = User.query.filter(func.lower(User.uuid) == func.lower(code)).first() if user is not None: user.active = True db.session.add(user) db.session.commit() login_user(user) flash(gettext('Your account is activated.')) logger.info('Activation success - user [' + user.username + '].') return redirect(request.args.get('next') or url_for('index')) return render_template('activate.html', form=form)
def populate_departments(limit: int = 14) -> None: """ Populates 'Department' Table Parameters: limit (int): Max number of departments Returns: None """ logger.info('Populating Departments Database') department_names = [ 'General Management', 'Marketing', 'Operations', 'Finance', 'Sales', 'Human Resource', 'Purchase', 'Training', 'Development', 'Test Team', 'Architecture', 'Customer Support', 'Public relations', 'Research' ] for name in department_names[:limit]: department = Department(name=name) db.session.add(department) db.session.commit() logger.info('Successfully populated Departments Database')
def register(): form = RegisterForm() if form.validate_on_submit(): user = User.query.filter(func.lower(User.username) == func.lower(form.username.data)).first() if user is None: user = User.query.filter(func.lower(User.email) == func.lower(form.email.data)).first() if user is None: # create new user user = User( username=form.username.data, email=form.email.data, password=form.password.data ) db.session.add(user) db.session.commit() if SEND_EMAIL_AFTER_REGISTRATION: send_email_registration(user) logger.info('Registration success - new user [' + form.username.data + '].') # create default media folder # mf = MediaFolder(foldername='default') # mf.rename = False # mf.author = user # db.session.add(mf) # db.session.commit() # activate user if need if not user.active: flash(gettext('Your account is not activated.')) return redirect(url_for('auth.activate')) login_user(user) return redirect(url_for('index')) else: logger.info('Registration failed - email address already in use. [' + form.email.data + '].') flash(gettext('This email address is already in use.')) else: logger.info('Registration failed - user name already in use. [' + form.username.data + '].') flash(gettext('This user name already in use.')) return render_template('register.html', form=form)
# ------------------------------------------------------ # This is the entry point of the Flask application. # ------------------------------------------------------ from project import create_app, logger, db from flask_script import Manager import coverage import unittest # The logger should always be used instead of a print(). You need to import it from # the project package. If you want to understand how to use it properly and why you # should use it, check: http://bit.ly/2nqkupO logger.info('Server has started.') # Defines which parts of the code to includ and omit when calculating code coverage. COV = coverage.coverage(branch=True, include='project/*', omit=['tests/*', 'project/website/*']) COV.start() # Creates the Flask application object that we use to initialize things in the app. app = create_app() import project.models db.create_all(app=app) # Initializes the Manager object, which allows us to run terminal commands on the # Flask application while it's running. manager = Manager(app)
from project import app, logger if __name__ == '__main__': logger.info('Starting the app') app.run(debug=True)
# walk_revisions starts from the head and goes backwards. We want to # migrate up from scratch, so we need to reverse the order. revisions.reverse() # False if there is a current revision (in which case, we don't want to # start migrating yet), True if there is none and the database was just # created. migrating = False if current else True with app.app_context(): for revision in revisions: if migrating: logger.info(f'Upgrading to {revision}') command.upgrade(config, revision) # One we reach the current revision, we want to upgrade, one step # at a time, for each subsequent revision. If we don't do this, # queries in migrations (but not DDL) will fail. if current and current == revision: migrating = True logger.info('Migrations finished') if __name__ == '__main__': # uncomment to automatically run migrations when the dev server restarts: # run_migrations_on_dev_server_restart() logger.info('Running dev server') app.run(host='0.0.0.0', port=8000, debug=True)
def logout(): logout_user() logger.info('Logout success - user logout.') flash(gettext('You were logged out.')) return redirect(url_for('index'))