在我们的学习过程中,django项目给大家详细的解释了如何配置主从读写分离,但是flask中没有提到相关的知识,这里小编为大家搜集了一篇简单的利用flask-SQLAlchemy为大家搭建mysql的主从读写分离。
flask中没有直接的主从读写分离配置,需要自己创造相应的引擎,构造读模式和写模式的隐射关系,通过判断是读操作或者写操作,连接对应的数据库。
[Python]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 | from sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmaker# 创建对象的基类,所有model继承baseBase = declarative_base()def get_db_sessionmaker(db_uri, **kvargs): # 初始化数据库连接: engine = create_engine(db_uri, **kvargs) # 创建DBSession类型: DBSession = sessionmaker(bind=engine) DBSession.configure(bind=engine) Base.metadata.create_all(engine) return DBSession |
[Python]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | import threadingfrom contextlib import contextmanagerfrom frame.orm.db_util import get_db_sessionmaker, Basefrom utils.collection_util import is_emptyfrom utils.random_util import randchoiceDEFAULT_SESSION_NAME = "default"Base = Baseclass DBManager(object): singleton = None mutex = threading.Lock() def __init__(self): self.__conf = {} self.__session_dict = {} def db_uri(self, name, db_uri, **kwargs): self.__conf[name] = db_uri self.__session_dict[name] = get_db_sessionmaker(db_uri, **kwargs) return self @staticmethod def get_instance(): if DBManager.singleton == None: DBManager.mutex.acquire() if DBManager.singleton == None: DBManager.singleton = DBManager() |
更多免费技术资料可关注:annalin1203