推荐学习书目
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 · Nov 8, 2017 · 2186 views
    This topic created in 3109 days ago, the information mentioned may be changed or developed.

    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 replies    2017-11-09 18:02:00 +08:00
    Wichna
        1
    Wichna  
       Nov 8, 2017   ❤️ 1
    session.rollback() 的执行应该是具有幂等性的吧,没有任何 commit 执行 rollback 应该不会有什么问题
    fox0001
        2
    fox0001  
       Nov 8, 2017
    事务没学好…
    RuiQ
        3
    RuiQ  
    OP
       Nov 8, 2017
    @fox0001 唉 补课去了。。
    ryd994
        4
    ryd994  
       Nov 8, 2017 via Android
    我觉得你这里设计就错了。看你的意思,a 和 b 要求同时成功或失败,那他们就应该合并为一个事务啊。
    siteshen
        5
    siteshen  
       Nov 9, 2017
    @ryd994 我觉得题主的意思是,a_session 和 b_session 访问的是不同的数据库,没法在一个 transaction 处理。
    RuiQ
        6
    RuiQ  
    OP
       Nov 9, 2017
    @siteshen
    @ryd994
    是的 不是同一个数据库
    ryd994
        7
    ryd994  
       Nov 9, 2017 via Android
    等等,你 commit 过的怎么还能 rollback ?
    siteshen
        8
    siteshen  
       Nov 9, 2017
    这个能解决你的问题,可以去研究下。
    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.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1044 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 18:41 · PVG 02:41 · LAX 11:41 · JFK 14:41
    ♥ Do have faith in what you're doing.