Example #1
0
def get_switches_from_db():
    """
    Возвращает список устройств удовлетворяющих фильтрующим условиям в виде словаря словарей.
    Итерируется по списку устройств и отфильтровывает лишнее
    Записывает предварительное базовое количество свободных абонентских портов
    За основу берем положение что у 10-портового коммутаторов два trunk и восемь access портов, trunk не учитывается
    """
    right_dev_dict = {}
    for device in session.query(Device).filter(
            Device.location_type == 'signal_center', Device.location_id
            is not None, or_(Device.port_count == 10, Device.port_count >= 24),
            or_(Device.switch_role == 'acc', Device.switch_role == 'gb')):

        if device.port_count == 10:
            free = 8
        else:
            free = 24

        right_dev_dict[device.id] = {
            'location_id': device.location_id,
            'switch_role': device.switch_role,
            'port_count': device.port_count,
            'used': 0,
            'free': free
        }
    return right_dev_dict
Example #2
0
def get_port_state_from_db(devs):
    """
    Принимает словарь с отфильтрованными устройствами и производит подсчет используемых и неиспользуемых портов
    Исключает порты <24 | <8 если они задействованы не для клиентских устройств
    """
    def check_access_port(a, b):
        if a <= 8 and b == 10 or a <= 24 <= b:
            devs[dev]['free'] -= 1

    # Для каждого устройства...
    usr = nested_dict(2, int)
    for dev, val in devs.items():
        # Создать список пользователей
        if len(usr[val['location_id']]) == 0:
            usr[val['location_id']] = []
        devs[dev]['usr'] = []
        # Для каждого порта...
        for port in session.query(SwitchPort).filter(
                SwitchPort.device_id == dev):
            # Крутить нужные счетчики
            if port.binding_type == 'user':
                devs[dev]['used'] += 1
                devs[dev]['free'] -= 1
                usr[val['location_id']].append(int(port.binding_value))
            elif port.binding_type is not None:
                check_access_port(port.port_id, devs[dev]['port_count'])
        usr[val['location_id']] = list(set(usr[val['location_id']]))
    return devs, usr
Example #3
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = session.query(User).filter(
            User.email == form.email.data).first()
        if (not user is None) and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            return redirect('/')
        else:
            flash('Invalid username or password.')

    return render_template(
        'login_or_register.html',
        title='Login',
        name='login',
        form=form,
    )
Example #4
0
 def process(self):
     """
     Руководит последовательностью действий:
     1. Итерируется по всем пользователям и вычисляет дату начала работы сегмента
     2. Итерируется по живым пользователям
     3. Итерируется по мертвым
     4. Строит прогноз
     """
     for unit_num, user_list in self.u_users.items():
         self.unit_num = unit_num
         self.user_list = user_list
         self.db_data = session.query(UserProperties).filter(
             UserProperties.uid.in_(self.user_list))
         self.segment_reg_date = date.today()
         self.dead_user_count = 0
         self.user_growth = 0
         self.segment_status = True  # True, если сегмет старый, False, если новый
         self.segment()
         self.alive_users()
         self.dead_users()
         self.forecast()
Example #5
0
def request_logs():

    exercise_types = [
        Swimming,
    ]

    days_to_exercises_map = {}

    for e in exercise_types:
        exercise_rows = session.query(e).filter(
            e.user_id == current_user.id).all()
        for exercise_row in exercise_rows:
            exercise_date = exercise_row.exercise_date
            if exercise_date in days_to_exercises_map:
                days_to_exercises_map[exercise_date].append(
                    exercise_row.renderable_dict)
            else:
                days_to_exercises_map[exercise_date] = [
                    exercise_row.renderable_dict
                ]

    return jsonify(days_to_exercises_map)
#!/usr/bin/env python3

from db_connect import Salary, Employees, session
from sqlalchemy.orm import aliased
from sqlalchemy import and_, or_

sal = aliased(Salary)

for empid in session.query(
        sal.emp_id).filter(sal.basic > 10000).filter(sal.extra > 1000):
    print(empid)

print('-' * 50)
for empid in session.query(
        sal.emp_id).filter(sal.basic > 10000).filter(sal.extra > 1000):
    print(empid)

print('-' * 50)
for row in session.query(sal.emp_id, sal.basic, sal.extra).filter(
        and_(sal.basic > 10000, sal.extra > 2000)):
    print(row.emp_id)

print('-' * 50)
for row in session.query(sal.emp_id, sal.basic, sal.extra).filter(
        or_(sal.basic > 10000, sal.extra > 3000)):
    print(row.emp_id)

session.close()
Example #7
0
#!/usr/bin/env python3

from db_connect import Employees, session
from sqlalchemy.orm import aliased

new_emp = aliased(Employees)

for name, phone in session.query(Employees.name, Employees.phone):
    print(name, phone)

print('-' * 50)
for name, phone in session.query(new_emp.name, new_emp.phone):
    print(name, phone)

print('-' * 50)
for name, phone in session.query(new_emp.name,
                                 new_emp.phone).filter(new_emp.name == 'john'):
    print(name, phone)

print('-' * 50)
for name, phone in session.query(new_emp.name,
                                 new_emp.phone).filter(new_emp.name != 'john'):
    print(name, phone)

print('-' * 50)
for name, phone in session.query(new_emp.name, new_emp.phone).filter(
        new_emp.name.like('j%')):
    print(name, phone)

print('-' * 50)
for name, phone in session.query(new_emp.name, new_emp.phone).filter(
Example #8
0
#!/usr/bin/env python3

from db_connect import Departments, session
from sqlalchemy.orm import aliased

new_dep = aliased(Departments)

for instance in session.query(Departments).order_by(Departments.dep_id):
    print(instance.dep_id, instance.dep_name)

for instance in session.query(Departments.dep_name.label('部门')):
    print(instance.部门)



for dep_id,dep_name in session.query(new_dep.dep_id,new_dep.dep_name).\
    order_by(new_dep.dep_id):
    print(dep_id, dep_name)


for dep_id,dep_name in session.query(new_dep.dep_id,new_dep.dep_name).\
    order_by(new_dep.dep_id)[0:2]:
    print(dep_id, dep_name)

session.close()
#!/usr/bin/env python3

from sqlalchemy.orm import sessionmaker, aliased
from db_connect import Employees, session

new_emp = aliased(Employees)

query = session.query(new_emp.name, new_emp.phone).order_by(new_emp.emp_id)
# print(query)
# print(query.all())
# print(query.first())
# print(query.one())

query2 = session.query(new_emp.name,
                       new_emp.phone).filter(new_emp.emp_id == '4')
print(query2.one())
print(query2.scalar())

query3 = session.query(new_emp.name,
                       new_emp.phone).filter(new_emp.emp_id == '5')
print(query3.count())
Example #10
0
def load_user(user_id):
    return session.query(User).get(int(user_id))
#!/usr/bin/env python3

from sqlalchemy.orm import aliased
from db_connect import session, Employees, Departments

new_emp = aliased(Employees)
new_dep = aliased(Departments)

query = session.query(new_emp.name,
                      new_dep.dep_name).join(new_dep,
                                             new_emp.dep_id == new_dep.dep_id)
print(query.all())