#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : utils.py @Author : liuyihui @Email : liuyihui02@gmail.com ''' # here put the import lib import elo import random from typing import List from db_init import Person from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.session import Session from sqlalchemy.sql.expression import desc, func engine = create_engine('sqlite:///data.db', echo=False) session_maker = sessionmaker(bind=engine) def get_session() -> Session: return session_maker() def get_person(id: int, ses: Session) -> Person: res = ses.query(Person).filter_by(id=id).first() return res def get_enemy(P: Person, ses: Session, delta: float = 0.01) -> Person: min_ = P.rate * (1 - delta) max_ = P.rate * (1 + delta) res = ses.query(Person).filter( Person.id != P.id, Person.rate >= min_, Person.rate <= max_ ).order_by(func.random()).first() return res def get_rank(ses: Session, b: int = 1, len: int = 10) -> List[Person]: res = ses.query(Person).order_by(desc('rate')).offset(b-1).limit(len).all() return res ses = get_session() A = get_person(1, ses) res = get_enemy(A, ses) print(res)