简体   繁体   English

没有会话的烧瓶 sqlalchemy 插入

[英]flask sqlalchemy insert without session

HI is there is any way that I can insert a row to db without using session.嗨,有什么方法可以在不使用会话的情况下向 db 插入一行。 A simple Example:一个简单的例子:

try:
   db.session.add(user1)
   #in here I want to insert a row to my db but I can't do it with session because if i commit in here it will commit all inserts so my transaction not work.
   db.session.add(user2)
except:
   db.session.rollback()
else:
   db.session.commit()

thank you谢谢你

If you want to commit changes independently of the default db.session there a couple of possibilities.如果您想独立于默认的db.session提交更改,则有几种可能性。

  1. If you need an actual session, create one using SQLAlchemy and use it for your log entries:如果您需要一个实际会话,请使用 SQLAlchemy 创建一个并将其用于您的日志条目:

     from sqlalchemy import orm ... @app.route('/') def index(): model = MyModel(name='M1') db.session.add(model) with orm.Session(db.engine).begin() as log_session: # Session.begin will commit automatically. log = MyLog(message='hello') log_session.add(log) return ''
  2. If you are just inserting entries in the log table you can just connect using the engine.如果您只是在日志表中插入条目,则可以使用引擎进行连接。

     import sqlalchemy as sa ... @app.route('/') def index(): model = MyModel(name='M1') db.session.add(model) log_table = sa.Table('my_log', db.metadata, autoload_with=db.engine) with db.engine.begin() as conn: conn.execute(log_table.insert(), {'message': 'hello'}) db.session.rollback() return ''
  3. You could also send a raw SQL statement using the mechanism in (2.), by replacing log_table.insert with sa.text(sql_string)您还可以使用 (2.) 中的机制发送原始 SQL 语句,方法是将log_table.insert替换为sa.text(sql_string)

How ever you choose to do this be aware that:无论您如何选择这样做,请注意:

  • Due to transaction isolation, you two transactions may have different views of the data in the database由于事务隔离,您的两个事务可能对数据库中的数据有不同的看法
  • You are responsible for making sure these additional sessions/transactions/connections are rolled back, committed and closed as necessary您有责任确保在必要时回滚、提交和关闭这些额外的会话/事务/连接
  • You are responsible for handling problem scenarios, for example if an error causes the db.session to roll back, making log messages potentially invalid.您负责处理问题场景,例如,如果错误导致db.session回滚,从而使日志消息可能无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM