Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#6] DB connection 관련 코드 추가 #20

Merged
merged 1 commit into from Mar 2, 2019
Merged
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.
+107 −3
Diff settings

Always

Just for now

[#6] DB connection 관련 코드 추가

  • Loading branch information...
JoMingyu committed Mar 2, 2019
commit eee69310351eb5bde2f27b68cc6fb1e79be2b8c6
Copy path View file
@@ -6,7 +6,9 @@


def register_extensions(flask_app: Flask):
pass
from app.extensions import main_db

main_db.init_app(flask_app)


def register_views(flask_app: Flask):
Copy path View file
@@ -0,0 +1,4 @@
from app.models import MainDB


main_db = MainDB()
Copy path View file
@@ -0,0 +1,85 @@
from abc import abstractmethod

from flask import g, has_request_context
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session, sessionmaker

Base = declarative_base()


class DB:
@abstractmethod
def extract_create_engine_kwargs(self, flask_app) -> dict:
"""
`self.checkout_new_session`을 초기화하기 위해 호출하는
`sqlalchemy.create_app` 함수에 전달할 인자들을 dictionary로 반환합니다.
"""

pass

@property
@abstractmethod
def attribute_name_on_g(self) -> str:
"""
g 객체에 session 객체를 저장할 때 사용할 attribute name입니다.
setattr(obj, name, value)에서 `name` 자리에 사용됩니다.
"""

pass

@property
def session(self) -> Session:
"""
g 객체에서 session 객체를 가져와 반환합니다.
현재 context에 대해 checkout된 session이 없으며 request context가 활성화되어 있는 경우, 새로 생성합니다.
"""

session = getattr(g, self.attribute_name_on_g, None)

if session is None and has_request_context():
session = self.checkout_new_session()
setattr(g, self.attribute_name_on_g, session)

return session

@session.setter
def session(self, value: Session):
"""
g 객체에 session 객체를 저장합니다.
"""

setattr(g, self.attribute_name_on_g, value)

def __init__(self, flask_app=None):
self.engine = None
self.checkout_new_session = None

if flask_app is not None:
self.init_app(flask_app)

def init_app(self, flask_app):
self.engine = create_engine(**self.extract_create_engine_kwargs(flask_app))
self.checkout_new_session = sessionmaker(self.engine)

@flask_app.teardown_appcontext
def teardown_request(_):
"""
context에 대해 session이 한 번 이상 checkout되었다면 이를 close해주기 위한 teardown callback
"""

session = self.session

if session is not None:
session.close()


class MainDB(DB):
def extract_create_engine_kwargs(self, flask_app):
return {
'name_or_url': flask_app.config['MAIN_DB_URL']
}

@property
def attribute_name_on_g(self):
return 'main_db_session'
Copy path View file
@@ -1,6 +1,19 @@
import os


DB_NAME = 'stay'


class LocalDBConfig:
pass
MAIN_DB_URL = 'mysql+mysqlclient://stay_local:b,to#98gks1VK0@127.0.0.1:3306/{}?charset=utf8mb4'.format(
DB_NAME
)


class RemoteDBConfig:
pass
MAIN_DB_URL = 'mysql+mysqlclient://{}:{}@{}:3306/{}?charset=utf8mb4'.format(
os.getenv('DB_USER'),
os.getenv('DB_PASSWORD'),
os.getenv('DB_ENDPOINT'),
DB_NAME
)
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.