V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
RuiQ
V2EX  ›  Python

关于 SQLAlchemy 的一个问题

  •  
  •   RuiQ · 2017-11-08 18:44:43 +08:00 · 1670 次点击
    这是一个创建于 2353 天前的主题,其中的信息可能已经有所发展或是发生改变。

    try: a_session.commit() b_sessiom.commit() except Exception: a_session.rollback() b_session.rollback()

    在处理两个 db 的时候,如果执行 a_session.commit() 就报错了,因为 b_session.commit()没有执行,那么 b_session.rollback() 会报错 或者会有什么不好的影响吗。

    本意就是 a 或 b 其中一个执行错了 都回滚的。

    求教大佬们。。。

    8 条回复    2017-11-09 18:02:00 +08:00
    Wichna
        1
    Wichna  
       2017-11-08 19:01:34 +08:00   ❤️ 1
    session.rollback() 的执行应该是具有幂等性的吧,没有任何 commit 执行 rollback 应该不会有什么问题
    fox0001
        2
    fox0001  
       2017-11-08 19:01:48 +08:00
    事务没学好…
    RuiQ
        3
    RuiQ  
    OP
       2017-11-08 19:05:30 +08:00
    @fox0001 唉 补课去了。。
    ryd994
        4
    ryd994  
       2017-11-08 20:47:04 +08:00 via Android
    我觉得你这里设计就错了。看你的意思,a 和 b 要求同时成功或失败,那他们就应该合并为一个事务啊。
    siteshen
        5
    siteshen  
       2017-11-09 00:07:53 +08:00
    @ryd994 我觉得题主的意思是,a_session 和 b_session 访问的是不同的数据库,没法在一个 transaction 处理。
    RuiQ
        6
    RuiQ  
    OP
       2017-11-09 11:15:13 +08:00
    @siteshen
    @ryd994
    是的 不是同一个数据库
    ryd994
        7
    ryd994  
       2017-11-09 13:07:13 +08:00 via Android
    等等,你 commit 过的怎么还能 rollback ?
    siteshen
        8
    siteshen  
       2017-11-09 18:02:00 +08:00
    这个能解决你的问题,可以去研究下。
    http://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#enabling-two-phase-commit

    For backends which support two-phase operation (currently MySQL and PostgreSQL), the session can be instructed to use two-phase commit semantics. This will coordinate the committing of transactions across databases so that the transaction is either committed or rolled back in all databases.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1356 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:41 · PVG 07:41 · LAX 16:41 · JFK 19:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.