def create_data(session: Session): department1_id = uuid.uuid4().hex department2_id = uuid.uuid4().hex department1 = Department(id=department1_id, title='Биология и Общая генетика') department2 = Department(id=department2_id, title='Биотехнология') session.add(department1) session.add(department2) mypath = "C:/Users/Andrey/Pictures/PNG" onlyfiles = listdir(mypath) added_objects = [] for obj in onlyfiles: splited_obj = obj.split('_') if splited_obj[0] in added_objects: continue obj_id = uuid.uuid4().hex new_object = Object(id=obj_id, title=splited_obj[0], department_id=department1_id) session.add(new_object) for fl in onlyfiles: splited_fl = fl.split('_') zoom_fl = splited_fl[1].split('.') if fl.find(splited_obj[0]) != -1: fl_id = uuid.uuid4().hex new_file = File(id=fl_id, type='image', url=fl, zoom=zoom_fl[0], object_id=obj_id) session.add(new_file) added_objects.append(splited_obj[0]) session.commit() session.close()
import datetime import discord from discord import MessageType from discord.ext import commands, tasks from models.Message import Message from models.Members import Member from models.database import Session from discord.commands import slash_command, Option from discord.ext.pages import Paginator, Page from sqlalchemy import desc session = Session() class Memory(commands.Cog): def __init__(self, bot): self.bot = bot self.forget.start() @tasks.loop(seconds=3600, reconnect=True) async def forget(self): session.query(Message).filter( Message.Created <= (datetime.datetime.now() - datetime.timedelta(hours=1))).delete() session.commit() @slash_command( name='memory', description="Выводит удалённые сообщения.",
from sqlalchemy import and_, or_ from sqlalchemy.orm import Session as SQLSession from models.database import DATABASE_NAME, Session import create_database as db_creator from models.lesson import Lesson, association_table from models.student import Student from models.group import Group if __name__ == '__main__': db_is_created = os.path.exists(DATABASE_NAME) if not db_is_created: db_creator.create_database() session: SQLSession = Session() print(f'Кол-во студентов: {session.query(Student).count()}') student = session.query(Student).filter( and_(Student.surname.like('Д%'), Student.age > 18)).one() print(student) print('*' * 30) students = session.query(Student).filter( and_(Student.surname.like('А%'), Student.age > 16)) for it in students: print(it) print('*' * 30) students_list: list[Student] = [it for it in students] print(students_list) print('*' * 30) for it in session.query(Student).filter( or_(Student.surname.like('Д%'), Student.surname.like('В%'))):
def __init__(self): self.session = Session()
def create_database(load_fake_data: bool = True): create_db() if load_fake_data: _load_fake_data(Session())
def _load_fake_data(session: Session): lessons_names = ['Математика', 'Программирование', 'Философствуем за кружечкой пенного', 'Алгоритмы и структуры данных', 'Линейная алгебра', 'Мат. статистика', 'Физкультура'] group1 = Group(group_name='1-МДА-7') group2 = Group(group_name='1-МДА-9') session.add(group1) session.add(group2) for key, it in enumerate(lessons_names): lesson = Lesson(lesson_title=it) lesson.groups.append(group1) if key % 2 == 0: lesson.groups.append(group2) session.add(lesson) faker = Faker('ru_RU') group_list = [group1, group2] session.commit() for _ in range(50): full_name = faker.name().split(' ') age = faker.random.randint(16, 25) address = faker.address() group = faker.random.choice(group_list) student = Student(full_name, age, address, group.id) session.add(student) session.commit() session.close()
import os from sqlalchemy import and_ from models.database import DATABASE_NAME, Session import create_database as db_creator from models.lesson import Lesson, association_table from models.student import Student from models.group import Group if __name__ == '__main__': db_is_created = os.path.exists(DATABASE_NAME) if not db_is_created: db_creator.create_database() session = Session() for it in session.query(Lesson): print(it) print('*' * 30) for it in session.query(Lesson).filter(Lesson.id > 3): print(it) print('*' * 30) for it in session.query(Lesson).filter( and_(Lesson.id >= 3, Lesson.lesson_title.like('Ф%'))): print(it) print('*' * 30) for it in session.query(Student).join(Group).filter( Group.group_name == '1-МДА-9'): print(it) print('*' * 30) for it, gr in session.query(Student, Group):
from flask import Flask, jsonify import os def load_json_data(filename): data = {} with open(filename) as json_file: data = json.load(json_file) # test print("================ load_json loading data ==========") #print(data["config"][0]["data"][1]) return data #Base.metadata.create_all(engine) session = Session() def create_users(session): # email,password,first_name,last_name,role users = [ User("*****@*****.**", "changeit", "System2", "Administrator", "Admin"), User("*****@*****.**", "changeit", "Josh2", "Wase", "Guest") ] session.add_all(users) session.commit() def query_users_more(): db = DatabaseService()
def create_database(load_data: bool = True): if load_data: create_data(Session())
def get_department_objects(id: str): session = Session() obj_out = session.query(Object).join(Department).filter( Department.id == id).all() obj_list = schemas.ObjectList(objects=obj_out) return obj_list
def get_department(id: str): session = Session() dep_out = session.query(Department).filter(Department.id == id).first() return dep_out
def get_departments(): session = Session() dep_out = session.query(Department).all() dep_list = schemas.DepartmentList(departments=dep_out) return dep_list