diff --git a/__pycache__/add_func.cpython-311.pyc b/0.4_stable/__pycache__/add_func.cpython-311.pyc similarity index 62% rename from __pycache__/add_func.cpython-311.pyc rename to 0.4_stable/__pycache__/add_func.cpython-311.pyc index a1da1c9..ed8982d 100644 Binary files a/__pycache__/add_func.cpython-311.pyc and b/0.4_stable/__pycache__/add_func.cpython-311.pyc differ diff --git a/0.4_stable/__pycache__/dbconnection.cpython-311.pyc b/0.4_stable/__pycache__/dbconnection.cpython-311.pyc new file mode 100644 index 0000000..821ec32 Binary files /dev/null and b/0.4_stable/__pycache__/dbconnection.cpython-311.pyc differ diff --git a/__pycache__/dbtable.cpython-311.pyc b/0.4_stable/__pycache__/dbtable.cpython-311.pyc similarity index 96% rename from __pycache__/dbtable.cpython-311.pyc rename to 0.4_stable/__pycache__/dbtable.cpython-311.pyc index 0c7c812..e9fc9a2 100644 Binary files a/__pycache__/dbtable.cpython-311.pyc and b/0.4_stable/__pycache__/dbtable.cpython-311.pyc differ diff --git a/__pycache__/project_config.cpython-311.pyc b/0.4_stable/__pycache__/project_config.cpython-311.pyc similarity index 70% rename from __pycache__/project_config.cpython-311.pyc rename to 0.4_stable/__pycache__/project_config.cpython-311.pyc index bf4398f..cb30855 100644 Binary files a/__pycache__/project_config.cpython-311.pyc and b/0.4_stable/__pycache__/project_config.cpython-311.pyc differ diff --git a/0.4_stable/__pycache__/texts.cpython-311.pyc b/0.4_stable/__pycache__/texts.cpython-311.pyc new file mode 100644 index 0000000..f006ee2 Binary files /dev/null and b/0.4_stable/__pycache__/texts.cpython-311.pyc differ diff --git a/add_func.py b/0.4_stable/add_func.py similarity index 100% rename from add_func.py rename to 0.4_stable/add_func.py diff --git a/config.yaml b/0.4_stable/config.yaml similarity index 100% rename from config.yaml rename to 0.4_stable/config.yaml diff --git a/dbconnection.py b/0.4_stable/dbconnection.py similarity index 100% rename from dbconnection.py rename to 0.4_stable/dbconnection.py diff --git a/dbtable.py b/0.4_stable/dbtable.py similarity index 100% rename from dbtable.py rename to 0.4_stable/dbtable.py diff --git a/main.py b/0.4_stable/main.py similarity index 100% rename from main.py rename to 0.4_stable/main.py diff --git a/default_project/project_config.py b/0.4_stable/project_config.py similarity index 100% rename from default_project/project_config.py rename to 0.4_stable/project_config.py diff --git a/tables/__pycache__/cath_table.cpython-311.pyc b/0.4_stable/tables/__pycache__/cath_table.cpython-311.pyc similarity index 94% rename from tables/__pycache__/cath_table.cpython-311.pyc rename to 0.4_stable/tables/__pycache__/cath_table.cpython-311.pyc index 2ab3c77..25e31db 100644 Binary files a/tables/__pycache__/cath_table.cpython-311.pyc and b/0.4_stable/tables/__pycache__/cath_table.cpython-311.pyc differ diff --git a/tables/__pycache__/dish_table.cpython-311.pyc b/0.4_stable/tables/__pycache__/dish_table.cpython-311.pyc similarity index 97% rename from tables/__pycache__/dish_table.cpython-311.pyc rename to 0.4_stable/tables/__pycache__/dish_table.cpython-311.pyc index 147aaaf..3af5eec 100644 Binary files a/tables/__pycache__/dish_table.cpython-311.pyc and b/0.4_stable/tables/__pycache__/dish_table.cpython-311.pyc differ diff --git a/tables/cath_table.py b/0.4_stable/tables/cath_table.py similarity index 100% rename from tables/cath_table.py rename to 0.4_stable/tables/cath_table.py diff --git a/tables/dish_table.py b/0.4_stable/tables/dish_table.py similarity index 100% rename from tables/dish_table.py rename to 0.4_stable/tables/dish_table.py diff --git a/default_project/tables/people_table.py b/0.4_stable/tables/people_table.py similarity index 100% rename from default_project/tables/people_table.py rename to 0.4_stable/tables/people_table.py diff --git a/default_project/tables/phones_table.py b/0.4_stable/tables/phones_table.py similarity index 100% rename from default_project/tables/phones_table.py rename to 0.4_stable/tables/phones_table.py diff --git a/texts.py b/0.4_stable/texts.py similarity index 100% rename from texts.py rename to 0.4_stable/texts.py diff --git a/0.5_test/add_func.py b/0.5_test/add_func.py new file mode 100644 index 0000000..163c1fc --- /dev/null +++ b/0.5_test/add_func.py @@ -0,0 +1,5 @@ +import re + +def is_cyr_or_dig(string): + pattern = r'^[\u0400-\u04FF\d]+$' + return bool(re.match(pattern, string)) \ No newline at end of file diff --git a/0.5_test/config.yaml b/0.5_test/config.yaml new file mode 100644 index 0000000..26dda36 --- /dev/null +++ b/0.5_test/config.yaml @@ -0,0 +1,6 @@ +# Базовые параметры настройки конфигурации проекта +dbname: DBProd # В классе менять не надо +user: postgres # Замените на свой логин от БД в классе +password: Qwerty # Замените на свой пароль от БД в классе +host: localhost # Замените на 192.168.0.48 в классе +dbtableprefix: "public." # Замените на свой логин от БД \ No newline at end of file diff --git a/default_project/dbconnection.py b/0.5_test/dbconnection.py similarity index 100% rename from default_project/dbconnection.py rename to 0.5_test/dbconnection.py diff --git a/0.5_test/dbtable.py b/0.5_test/dbtable.py new file mode 100644 index 0000000..7888a05 --- /dev/null +++ b/0.5_test/dbtable.py @@ -0,0 +1,113 @@ +# Базовые действия с таблицами + +from dbconnection import * + +class DbTable: + dbconn = None + + def __init__(self): + return + + def table_name(self): + return self.dbconn.prefix + "table" + + def columns(self): + return {"test": ["integer", "PRIMARY KEY"]} + + def column_names(self): + return sorted(self.columns().keys(), key = lambda x: x) + + def primary_key(self): + return ['id'] + + def column_names_without_id(self): + res = sorted(self.columns().keys(), key = lambda x: x) + if 'id' in res: + res.remove('id') + return res + + def table_constraints(self): + return [] + + def create(self): + sql = "CREATE TABLE " + self.table_name() + "(" + arr = [k + " " + " ".join(v) for k, v in sorted(self.columns().items(), key = lambda x: x[0])] + sql += ", ".join(arr + self.table_constraints()) + sql += ")" + cur = self.dbconn.conn.cursor() + cur.execute(sql) + self.dbconn.conn.commit() + return + + def drop(self): + sql = "DROP TABLE IF EXISTS " + self.table_name() + cur = self.dbconn.conn.cursor() + cur.execute(sql) + self.dbconn.conn.commit() + return + + def insert_one(self, vals): + for i in range(0, len(vals)): + if type(vals[i]) == str: + vals[i] = "'" + vals[i] + "'" + else: + vals[i] = str(vals[i]) + sql = "INSERT INTO " + self.table_name() + "(" + sql += ", ".join(self.column_names_without_id()) + ") VALUES(" + sql += ", ".join(vals) + ")" + cur = self.dbconn.conn.cursor() + # cur.execute(sql) + try: + cur.execute(sql) + self.dbconn.conn.commit() + except psycopg2.errors.UniqueViolation: + self.dbconn.conn.rollback() + return + + def first(self): + sql = "SELECT * FROM " + self.table_name() + sql += " ORDER BY " + sql += ", ".join(self.primary_key()) + cur = self.dbconn.conn.cursor() + cur.execute(sql) + return cur.fetchone() + + def last(self): + sql = "SELECT * FROM " + self.table_name() + sql += " ORDER BY " + sql += ", ".join([x + " DESC" for x in self.primary_key()]) + cur = self.dbconn.conn.cursor() + cur.execute(sql) + return cur.fetchone() + + def all(self): + sql = "SELECT * FROM " + self.table_name() + sql += " ORDER BY " + sql += ", ".join(self.primary_key()) + cur = self.dbconn.conn.cursor() + cur.execute(sql) + return cur.fetchall() + + def select_one(self, **kwargs): + conditions = [] + values = [] + + sorted_kwargs = sorted(kwargs.items(), key=lambda x: x[0]) + + for key, value in sorted_kwargs(): + conditions.append(f"{key}=%s") + values.append(value) + + sql = f"SELECT * FROM {self.table_name()} WHERE " + " AND ".join(conditions) + cur = self.dbconn.conn.cursor() + cur.execute(sql, tuple(values)) + result = cur.fetchone() + cur.close() + + if result: + return True + else: + return False + + + diff --git a/0.5_test/main.py b/0.5_test/main.py new file mode 100644 index 0000000..7d0b05f --- /dev/null +++ b/0.5_test/main.py @@ -0,0 +1,221 @@ +import add_func +import sys +import texts +sys.path.append('tables') + +from project_config import * +from dbconnection import * + +from tables.dish_table import * +from tables.cath_table import * + +class Main: + + config = ProjectConfig() + connection = DbConnection(config) + + def __init__(self): + DbTable.dbconn = self.connection + return + + def db_init(self): + cth = CathTable() + d = DishTable() + cth.create() + d.create() + return + + def db_insert_somethings(self): + cth = CathTable() + dsh = DishTable() + + cth.insert_one(["Завтрак"]) + cth.insert_one(["Обэд"]) + cth.insert_one(["Ужин"]) + + dsh.insert_one([1, "10 minutes", "Яичница", "Взбить яйца, нарезать помидоры, обжарить их вместе."]) + dsh.insert_one([1, "20 minutes", "Блины", "Замесить тесто, да пожарить. ©️ Никита Сергеич"]) + dsh.insert_one([2, "2 hours", "Хлэб", "Почти, как блины, но не совсем."]) + dsh.insert_one([3, "40 minutes", "Паста", "Почувствуй себя итальянцем"]) + + def db_drop(self): + cth = CathTable() + d = DishTable() + d.drop() + cth.drop() + return + + def show_main_menu(self): + menu = texts.show_main_menu_txt + print(menu) + return + + def read_next_step(self): + return input("=> ").strip() + + def after_main_menu(self, next_step): + if next_step == "2": + self.db_drop() + self.db_init() + self.db_insert_somethings() + print("Таблицы созданы заново!") + return "0" + elif next_step != "1" and next_step != "9": + print("Выбрано неверное число! Повторите ввод!") + return "0" + else: + return next_step; + + def show_cath(self): + self.cath_id = -1 + menu = texts.show_cath_1txt + print(menu) + lst = CathTable().all() + j = 1 + for i in lst: + print(str(j) + "\t" + str(i[0])) + j += 1 + menu = texts.show_cath_2txt + print(menu) + return + + def after_show_cath(self, next_step): + """Выбор действий после вывода категорий + """ + while True: + if next_step == "4": + CathTable().delete(input('Введите название удаляемой категории(1 - для отмены): ')) + return "1" + + elif next_step == "6": #Добавление блюда в категорию + DishTable().insert_dishone(self.cath_id) + next_step = "5" + + elif next_step == "7":#Удаление блюда из категории + del_name = input('Введите название удаляемого блюда (1 - для отмены): ') + while (del_name.strip() == '')or(len(del_name.strip()) > 32)or(add_func.is_cyr_or_dig(del_name.strip())==0): + if(del_name.strip() == ''): + del_name = input("Пустая строка. Повторите ввод! Укажите название удаляемого блюда (0 - отмена): ") + if del_name == "0": + return "1" + elif(len(del_name.strip()) > 32): + del_name = input("Слишком длинная строка. Повторите ввод!\ + Укажите название удаляемого блюда (0 - отмена): ") + if del_name == "0": + return "1" + elif(add_func.is_cyr_or_dig(del_name.strip())==0): + del_name = input("Название должно состоять только из символов кириллицы. Повторите ввод!\ + Укажите название удаляемого блюда (0 - отмена): ") + if del_name == "0": + return "1" + DishTable().delete(del_name) + next_step = "5" + elif next_step == "5": + next_step = self.show_dish_in_cath() + elif next_step != "0" and next_step != "9" and next_step != "3": + print("Выбрано неверное число! Повторите ввод!") + return "1" + else: + return next_step + + def add_cath(self): + """ + Добавление новой категории в таблицу + """ + data = [] + data.append(input("Введите название (1 - отмена): ").strip()) + if data[0] == "1": + return + while((len(data[0].strip()) == 0)or(len(data[0].strip()) > 32)or(add_func.is_cyr_or_dig(data[0].strip())==0)): + if (len(data[0].strip()) > 32): + data[0] = input("Название слишком длинное! Введите название заново (1 - отмена):").strip() + if data[0] == "1": + return + elif add_func.is_cyr_or_dig(data[0].strip())==0: + data[0] = input("Название должно состоять только из символов кириллицы!\ + Введите название заново (1 - отмена):").strip() + if data[0] == "1": + return + else: + data[0] = input("Название не может быть пустым! Введите название заново (1 - отмена):").strip() + if data[0] == "1": + return + CathTable().insert_one(data) + return + + def show_dish_in_cath(self): + """Вывод всех блюд в выбранной пользователем категории + """ + if self.cath_id == -1: + while True: + name = input("Укажите название категории для вывода блюд (0 - отмена):") + while (name.strip() == '')or(len(name.strip()) > 32)or(add_func.is_cyr_or_dig(name.strip())==0): + if(name.strip() == ''): + name = input("Пустая строка. Повторите ввод! Укажите название категории для вывода блюд (0 - отмена):") + if name == "0": + return "1" + elif(len(name.strip()) > 32): + name = input("Сликшом длинная строка. Повторите ввод!\ + Укажите название категории для вывода блюд (0 - отмена):") + if name == "0": + return "1" + elif(add_func.is_cyr_or_dig(name.strip())==0): + name = input("Название должно состоять только из символов кириллицы. Повторите ввод!\ + Укажите название категории для вывода блюд (0 - отмена):") + if name == "0": + return "1" + flag, cath = CathTable().find_by_name(name) + print(flag) + if flag == 0: + print("Введено неверное название!") + else: + self.cath_id = cath + # self.cath_obj = cath + break + print("Выбрана категория: " + name) + print("Блюда:") + print("№\tНазвание\tВремя приготовления\tКраткая инструкция\ + \n-------------------------------------------------------------------------------------") + lst = DishTable().all_by_cath_id(cath) + j = 1 + for i in lst: + print(str(j) + "\t" + i[2] + "\t\t" + str(i[1]) + "\t\t\t" + str(i[4])) + j += 1 + menu = texts.show_dish_in_cath_txt + print(menu) + return self.read_next_step() + + def main_cycle(self): + """Основной цикл программы, регулирующий порядок действий + """ + current_menu = "0" + next_step = None + + while(current_menu != "9"): + + if current_menu == "0": + self.show_main_menu() + next_step = self.read_next_step() + current_menu = self.after_main_menu(next_step) + + elif current_menu == "1": + self.show_cath() + next_step = self.read_next_step() + current_menu = self.after_show_cath(next_step) + + elif current_menu == "2": + self.show_main_menu() + + elif current_menu == "3": + self.add_cath() + current_menu = "1" + + print("До свидания!") + return + + def test(self): + DbTable.dbconn.test() + +m = Main() +# m.test() +m.main_cycle() \ No newline at end of file diff --git a/project_config.py b/0.5_test/project_config.py similarity index 100% rename from project_config.py rename to 0.5_test/project_config.py diff --git a/0.5_test/tables/__pycache__/cath_table.cpython-311.pyc b/0.5_test/tables/__pycache__/cath_table.cpython-311.pyc new file mode 100644 index 0000000..25e31db Binary files /dev/null and b/0.5_test/tables/__pycache__/cath_table.cpython-311.pyc differ diff --git a/0.5_test/tables/__pycache__/dish_table.cpython-311.pyc b/0.5_test/tables/__pycache__/dish_table.cpython-311.pyc new file mode 100644 index 0000000..3af5eec Binary files /dev/null and b/0.5_test/tables/__pycache__/dish_table.cpython-311.pyc differ diff --git a/0.5_test/tables/cath_table.py b/0.5_test/tables/cath_table.py new file mode 100644 index 0000000..5aefaf2 --- /dev/null +++ b/0.5_test/tables/cath_table.py @@ -0,0 +1,43 @@ +# Таблица с категориями и действия с ними + +from dbtable import * + +class CathTable(DbTable): + def table_name(self): + return self.dbconn.prefix + "cath" + + def columns(self): + return {"id": ["serial", "PRIMARY KEY"], + "cath_name": ["varchar(32)", "NOT NULL"]} + + def table_constraints(self): + return ['CONSTRAINT "Name" UNIQUE (cath_name)'] + + def delete(self, val): + sql = "DELETE FROM " + self.table_name() + sql += " WHERE cath_name" + sql += "=" + "'" + "".join(val) + "';" + cur = self.dbconn.conn.cursor() + cur.execute(sql) + self.dbconn.conn.commit() + + def find_by_name(self, name): + flag = 0 + cur = self.dbconn.conn.cursor() + sql_sel = "SELECT id FROM " + self.table_name() + sql_sel += " WHERE cath_name = " + "'" + name + "'" + ";" + cur.execute(sql_sel) + ret = cur.fetchone() + # print(ret) + if(ret != None): + flag = 1 + return [flag, list(ret)[0]] + else: + return [flag, list(ret)[0]] + # sql = "SELECT * FROM " + self.table_name() + # sql += " ORDER BY " + # sql += ", ".join(self.primary_key()) + # sql += " LIMIT 1 OFFSET %(offset)s" + # cur.execute(sql, {"offset": num - 1}) + # print(cur) + diff --git a/0.5_test/tables/dish_table.py b/0.5_test/tables/dish_table.py new file mode 100644 index 0000000..8a3850c --- /dev/null +++ b/0.5_test/tables/dish_table.py @@ -0,0 +1,102 @@ +# Таблица с блюдами и действия с ними + +from dbtable import * +import add_func + +class DishTable(DbTable): + def table_name(self): + return self.dbconn.prefix + "dish" + + def columns(self): + return {"id": ["serial", "PRIMARY KEY"], + "cath_id": ["integer", "REFERENCES cath(id) ON DELETE CASCADE", "NOT NULL"], + "dish_name": ["varchar(32)", "NOT NULL"], + "cook_time": ["interval"], + "manual": ["text"]} + + def table_constraints(self): + return ['CONSTRAINT "Name Dish" UNIQUE (dish_name)'] + + + + def find_by_position(self, num): + sql = "SELECT * FROM " + self.table_name() + sql += " ORDER BY " + sql += ", ".join(self.primary_key()) + sql += " LIMIT 1 OFFSET %(offset)s" + cur = self.dbconn.conn.cursor() + cur.execute(sql, {"offset": num - 1}) + return cur.fetchone() + + def all_by_cath_id(self, cath_id): + sql = "SELECT * FROM " + self.table_name() + sql += " WHERE cath_id = " + str(cath_id) + sql += " ORDER BY " + sql += ", ".join(self.primary_key()) + cur = self.dbconn.conn.cursor() + cur.execute(sql) + return cur.fetchall() + + def delete(self, val): + sql = "DELETE FROM dish" + sql += " WHERE dish_name" + sql += "=" + "'" + val + "';" + cur = self.dbconn.conn.cursor() + cur.execute(sql) + self.dbconn.conn.commit() + + def check_by_name(self, value): + sql = f"SELECT * FROM {self.table_name()} WHERE dish_name='{value}'" + cur = self.dbconn.conn.cursor() + cur.execute(sql) + result = cur.fetchone() + cur.close() + if result: + return True + else: + return False + + def insert_dishone(self, cath_id): + + ins_name = input('Введите название добавляемого блюда (1 - для отмены): ') + + while (ins_name.strip() == '')or(len(ins_name.strip()) > 32)\ + or(add_func.is_cyr_or_dig(ins_name.strip())==0)or(DishTable().check_by_name(ins_name)): + + if(ins_name.strip() == ''): + ins_name = input("Пустая строка. Повторите ввод! Укажите название удаляемого блюда (0 - отмена): ") + if ins_name == "0": + return "1" + + elif(len(ins_name.strip()) > 32): + ins_name = input("Слишком длинная строка. Повторите ввод!\ + Укажите название удаляемого блюда (0 - отмена): ") + if ins_name == "0": + return "1" + + elif(add_func.is_cyr_or_dig(ins_name.strip())==0): + ins_name = input("Название должно состоять только из символов кириллицы. Повторите ввод!\ + Укажите название удаляемого блюда (0 - отмена): ") + if ins_name == "0": + return "1" + + else: + print('Такое блюдо уже существует') + ins_name = input("Повторите ввод! Укажите название блюда (0 - отмена): ") + if ins_name == "0": + return "1" + + ins_time = input(f'Процесс добавления блюда: {ins_name}\ + \nВведите время приготовления в формате 10 minutes/1 hour 5 minutes (1 - для отмены): ') + if ins_time == "0": + return "1" + ins_manual = input(f'Процесс добавления блюда: {ins_name}\ + \nВведите краткую инструкцию приготовления блюда (1 - для отмены): ') + if ins_time == "0": + return "1" + + insert = [cath_id, ins_time, ins_name, ins_manual] + DishTable().insert_one(insert) + + + \ No newline at end of file diff --git a/tables/people_table.py b/0.5_test/tables/people_table.py similarity index 100% rename from tables/people_table.py rename to 0.5_test/tables/people_table.py diff --git a/tables/phones_table.py b/0.5_test/tables/phones_table.py similarity index 100% rename from tables/phones_table.py rename to 0.5_test/tables/phones_table.py diff --git a/0.5_test/texts.py b/0.5_test/texts.py new file mode 100644 index 0000000..da2f6df --- /dev/null +++ b/0.5_test/texts.py @@ -0,0 +1,20 @@ +show_main_menu_txt = """Привутствуем в меню, выберите действие: + 1 - просмотр категорий; + 2 - сброс и инициализация БД; + 9 - выход;""" +show_cath_1txt = """Просмотр списка категорий! +№\tНазвание\n-------------------------------------------------------------------------------------""" + +show_cath_2txt = """-------------------------------------------------------------------------------------\nДальнейшие операции: + 0 - возврат в главное меню; + 3 - добавление новой категории; + 4 - удаление категории; + 5 - просмотр блюд в категории; + 9 - выход.""" + +show_dish_in_cath_txt = """-------------------------------------------------------------------------------------\nДальнейшие операции: + 0 - возврат в главное меню; + 1 - возврат в просмотр категорий; + 6 - добавление нового блюда; + 7 - удаление блюда; + 9 - выход.""" \ No newline at end of file diff --git a/__pycache__/dbconnection.cpython-311.pyc b/__pycache__/dbconnection.cpython-311.pyc deleted file mode 100644 index 9cbb354..0000000 Binary files a/__pycache__/dbconnection.cpython-311.pyc and /dev/null differ diff --git a/BDLab2-6.pdf b/other/BDLab2-6.pdf similarity index 100% rename from BDLab2-6.pdf rename to other/BDLab2-6.pdf diff --git a/default_project/config.yaml b/other/default_project/config.yaml similarity index 100% rename from default_project/config.yaml rename to other/default_project/config.yaml diff --git a/other/default_project/dbconnection.py b/other/default_project/dbconnection.py new file mode 100644 index 0000000..6fac33c --- /dev/null +++ b/other/default_project/dbconnection.py @@ -0,0 +1,34 @@ +# Установка соединения с базой данных +# (параметры передаются через класс конфиг). +import psycopg2 + +class DbConnection: + + def __init__(self, config): + self.dbname = config.dbname + self.user = config.user + self.password = config.password + self.host = config.host + self.prefix = config.dbtableprefix + self.conn = psycopg2.connect(dbname = self.dbname, + user = self.user, + password = self.password, + host = self.host) + + def __del__(self): + if self.conn: + self.conn.close() + + def test(self): + cur = self.conn.cursor() + cur.execute("DROP TABLE IF EXISTS test CASCADE") + cur.execute("CREATE TABLE test(test integer)") + cur.execute("INSERT INTO test(test) VALUES(1)") + self.conn.commit() + cur.execute("SELECT * FROM test") + result = cur.fetchall() + cur.execute("DROP TABLE test") + self.conn.commit() + return (result[0][0] == 1) + + diff --git a/default_project/dbtable.py b/other/default_project/dbtable.py similarity index 100% rename from default_project/dbtable.py rename to other/default_project/dbtable.py diff --git a/default_project/main.py b/other/default_project/main.py similarity index 100% rename from default_project/main.py rename to other/default_project/main.py diff --git a/other/default_project/project_config.py b/other/default_project/project_config.py new file mode 100644 index 0000000..2b451e5 --- /dev/null +++ b/other/default_project/project_config.py @@ -0,0 +1,21 @@ +# Загрузка настроек проекта (в данном случае только настроек соединения с БД) +# из файла config.yaml. +import yaml + +class ProjectConfig: + """Класс считывает базовые настройки из файла config.yaml""" + + def __init__(self): + with open('config.yaml') as f: + config = yaml.safe_load(f) + self.dbname = config['dbname'] + self.user = config['user'] + self.password = config['password'] + self.host = config['host'] + self.dbtableprefix = config['dbtableprefix'] + +# Этот метод запускается только, если запускать +# данный файл, а не подключать его. +if __name__ == "__main__": + x = ProjectConfig() + print(x.dbfilepath) diff --git a/other/default_project/tables/people_table.py b/other/default_project/tables/people_table.py new file mode 100644 index 0000000..d27e8ea --- /dev/null +++ b/other/default_project/tables/people_table.py @@ -0,0 +1,23 @@ +# Таблица персоны и особые действия с ней + +from dbtable import * + +class PeopleTable(DbTable): + def table_name(self): + return self.dbconn.prefix + "people" + + def columns(self): + return {"id": ["serial", "PRIMARY KEY"], + "last_name": ["varchar(32)", "NOT NULL"], + "first_name": ["varchar(32)", "NOT NULL"], + "second_name": ["varchar(32)"]} + + def find_by_position(self, num): + sql = "SELECT * FROM " + self.table_name() + sql += " ORDER BY " + sql += ", ".join(self.primary_key()) + sql += " LIMIT 1 OFFSET %(offset)s" + cur = self.dbconn.conn.cursor() + cur.execute(sql, {"offset": num - 1}) + return cur.fetchone() + diff --git a/other/default_project/tables/phones_table.py b/other/default_project/tables/phones_table.py new file mode 100644 index 0000000..c6326f0 --- /dev/null +++ b/other/default_project/tables/phones_table.py @@ -0,0 +1,27 @@ +# Таблица Телефоны и особые действия с ней. + +from dbtable import * + +class PhonesTable(DbTable): + def table_name(self): + return self.dbconn.prefix + "phones" + + def columns(self): + return {"person_id": ["integer", "REFERENCES people(id)"], + "phone": ["varchar(12)", "NOT NULL"]} + + def primary_key(self): + return ['person_id', 'phone'] + + def table_constraints(self): + return ["PRIMARY KEY(person_id, phone)"] + + def all_by_person_id(self, pid): + sql = "SELECT * FROM " + self.table_name() + sql += " WHERE person_id = %s" + sql += " ORDER BY " + sql += ", ".join(self.primary_key()) + cur = self.dbconn.conn.cursor() + cur.execute(sql, str(pid)) + return cur.fetchall() + diff --git a/test.py b/other/test.py similarity index 100% rename from test.py rename to other/test.py diff --git a/test.sql b/other/test.sql similarity index 100% rename from test.sql rename to other/test.sql diff --git a/project/Lib/site-packages/psycopg2/__pycache__/__init__.cpython-311.pyc b/project/Lib/site-packages/psycopg2/__pycache__/__init__.cpython-311.pyc index 9b8e13c..bebc802 100644 Binary files a/project/Lib/site-packages/psycopg2/__pycache__/__init__.cpython-311.pyc and b/project/Lib/site-packages/psycopg2/__pycache__/__init__.cpython-311.pyc differ diff --git a/project/Lib/site-packages/psycopg2/__pycache__/_json.cpython-311.pyc b/project/Lib/site-packages/psycopg2/__pycache__/_json.cpython-311.pyc index 0cb7df0..7c6bb5a 100644 Binary files a/project/Lib/site-packages/psycopg2/__pycache__/_json.cpython-311.pyc and b/project/Lib/site-packages/psycopg2/__pycache__/_json.cpython-311.pyc differ diff --git a/project/Lib/site-packages/psycopg2/__pycache__/_range.cpython-311.pyc b/project/Lib/site-packages/psycopg2/__pycache__/_range.cpython-311.pyc index c1a02ab..6bfddfd 100644 Binary files a/project/Lib/site-packages/psycopg2/__pycache__/_range.cpython-311.pyc and b/project/Lib/site-packages/psycopg2/__pycache__/_range.cpython-311.pyc differ diff --git a/project/Lib/site-packages/psycopg2/__pycache__/errors.cpython-311.pyc b/project/Lib/site-packages/psycopg2/__pycache__/errors.cpython-311.pyc index d917ecc..0dca915 100644 Binary files a/project/Lib/site-packages/psycopg2/__pycache__/errors.cpython-311.pyc and b/project/Lib/site-packages/psycopg2/__pycache__/errors.cpython-311.pyc differ diff --git a/project/Lib/site-packages/psycopg2/__pycache__/extensions.cpython-311.pyc b/project/Lib/site-packages/psycopg2/__pycache__/extensions.cpython-311.pyc index c60e40d..56d7dbe 100644 Binary files a/project/Lib/site-packages/psycopg2/__pycache__/extensions.cpython-311.pyc and b/project/Lib/site-packages/psycopg2/__pycache__/extensions.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/__init__.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/__init__.cpython-311.pyc index 17625b2..5b841e6 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/__init__.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/__init__.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/composer.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/composer.cpython-311.pyc index cd6e99e..75df32e 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/composer.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/composer.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/constructor.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/constructor.cpython-311.pyc index 129088d..c97dd49 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/constructor.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/constructor.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/cyaml.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/cyaml.cpython-311.pyc index fff6130..9becea1 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/cyaml.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/cyaml.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/dumper.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/dumper.cpython-311.pyc index 9b07182..c6f3103 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/dumper.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/dumper.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/emitter.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/emitter.cpython-311.pyc index 4986e5d..10546bc 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/emitter.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/emitter.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/error.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/error.cpython-311.pyc index 70a05f8..2f44ada 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/error.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/error.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/events.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/events.cpython-311.pyc index c3b771f..26678d6 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/events.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/events.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/loader.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/loader.cpython-311.pyc index fabe168..f522237 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/loader.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/loader.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/nodes.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/nodes.cpython-311.pyc index 5c59582..165b206 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/nodes.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/nodes.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/parser.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/parser.cpython-311.pyc index 2a9e020..ea500d0 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/parser.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/parser.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/reader.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/reader.cpython-311.pyc index c061922..18fcfae 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/reader.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/reader.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/representer.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/representer.cpython-311.pyc index 727c85f..9409e93 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/representer.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/representer.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/resolver.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/resolver.cpython-311.pyc index 99cfcad..7a4f1fe 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/resolver.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/resolver.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/scanner.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/scanner.cpython-311.pyc index 0d63322..9ab35d0 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/scanner.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/scanner.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/serializer.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/serializer.cpython-311.pyc index 619c076..971bd53 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/serializer.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/serializer.cpython-311.pyc differ diff --git a/project/Lib/site-packages/yaml/__pycache__/tokens.cpython-311.pyc b/project/Lib/site-packages/yaml/__pycache__/tokens.cpython-311.pyc index 4be94d0..8ba3f2a 100644 Binary files a/project/Lib/site-packages/yaml/__pycache__/tokens.cpython-311.pyc and b/project/Lib/site-packages/yaml/__pycache__/tokens.cpython-311.pyc differ