Skip to content
Permalink
Browse files

[#14] Base Model 정의

  • Loading branch information...
JoMingyu committed Mar 6, 2019
1 parent b9b6f89 commit eb3bff1237699960ff5f5f544604352534a6ae9d
Showing with 45 additions and 2 deletions.
  1. +45 −2 app/models/__init__.py
@@ -1,11 +1,54 @@
from abc import abstractmethod
from typing import Union

from flask import g, has_request_context
from flask import abort, g, has_request_context
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.sql.elements import ClauseElement

Base = declarative_base()
_Base = declarative_base()


class Base(_Base):
__abstract__ = True

@classmethod
def get_first_without_none_check(cls, read_session: Session, where_clause: Union[ClauseElement, bool]):
"""
전달된 session을 통해 cls에 대해 where_caluse로 필터해 쿼리하고, None 여부에 상관없이 .first()의 결과를 리턴합니다.
"""
return read_session.query(cls).filter(where_clause).first()

@classmethod
def get_first_or_abort_on_none(cls, read_session: Session, where_clause: Union[ClauseElement, bool], code=404, message: str=None):
"""
1. 전달된 session을 통해 cls에 대해 where_caluse로 필터해 쿼리하고
2. .first() 후 결과가 None이면 인자 정보들을 통해 abort,
3. None이 아니라면 해당 객체를 리턴
"""
res = cls.get_first_without_none_check(read_session, where_clause)

if res is None:
abort(code, message)
else:
return res

@classmethod
def delete(cls, write_session: Session, where_clause: Union[ClauseElement, bool]):
"""
전달된 session을 통해 cls에 대해 where_clause로 필터해 쿼리하고, 결과를 모두 delete합니다.
commit을 수행하지 않음에 주의하기 바랍니다.
"""
write_session.query(cls).filter(where_clause).delete()

@classmethod
def delete_and_commit(cls, write_session: Session, where_clause: Union[ClauseElement, bool]):
"""
where_clause를 통해 delete 후, commit까지 수행합니다.
"""
cls.delete(write_session, where_clause)
write_session.commit()


class DB:

0 comments on commit eb3bff1

Please sign in to comment.
You can’t perform that action at this time.