модель:
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
class BaseClass:
def __init__(self):
self.BaseDeclarative = declarative_base()
self.BaseEngine = create_engine('sqlite:///englishdb.db', encoding='utf-8')
main_object = BaseClass()
class Category(main_object.BaseDeclarative):
__tablename__ = 'category'
id = Column(Integer, primary_key=True)
title = Column(String(250), nullable=False)
class Words(main_object.BaseDeclarative):
__tablename__ = 'words'
id = Column(Integer, primary_key=True)
rusword = Column(String(250))
engword = Column(String(250))
true = Column(Integer, default=0)
trial = Column(Integer, default=30)
category_id = Column(Integer, ForeignKey('category.id'), default=1)
main_object.BaseDeclarative.metadata.create_all(main_object.BaseEngine)
сессия и взаимодействия:
# -*- coding: utf-8 -*-
from models import main_object as model
from models import Category, Words
from sqlalchemy.orm import sessionmaker
class InitQueries:
def __init__(self):
model.BaseDeclarative.metadata.bind = model.BaseEngine
DBSession = sessionmaker(bind=model.BaseEngine)
self.session = DBSession()
init = InitQueries()
class DbFunc:
def addcategory(self, title):
try:
category = Category(title=title)
init.session.add(category)
init.session.commit()
print("Category added!")
except:
print("произошла ошибка!")
pass
def addrow(self, rusword, engword, category_id=1):
try:
row = Words(rusword=rusword, engword=engword, category_id=category_id)
init.session.add(row)
init.session.commit()
except:
print("Что то не так. Ошибка в запросе!")
pass
def deleterow(self, ident):
try:
row = init.session.query(Words).filter(Words.id == ident).one()
init.session.delete(row)
init.session.commit()
except:
print("Ошибка удаления!")
pass
function = DbFunc()