我有一个基于SQLAlchemy的现有项目,具有以下结构
# __init__.py
import yaml
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
try:
with open('config.yaml', 'r') as yaml_config_file:
config = yaml.safe_load(yaml_config_file)
except:
raise Exception
Base = declarative_base()
Session = sessionmaker(bind=create_engine(config['db']))
# models.py:
from fmgcore import Base
class Image(Base):
__tablename_- = 'image'
....
...
# service.py
from fmgcore import config, Session
import sqlalchemy.exc as sql_exc
log = logging.getLogger(__name__)
class Services(object):
def __init__(self, config):
self.config = config
def create_image(self, name, filename,
disk_format,
size=None,
description=None):
session = Session()
try:
session.add(...)
session.commit(...)
except sql_exc.IntegrityError as e:
logging.info("Image with name {0} already exists".format(name))
session.rollback()
except sql_exc.SQLAlchemyError as e:
session.rollback()
finally:
session.close()
def get_image():
####
我想使用Django-Rest使用REST Api公开这些服务。我不想使用Django模型。
我的问题是我应该如何在view.py中使用Services(),以便它不会为每个REST请求创建引擎或新连接的多个实例,而是使用同一池。