[英]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
提交更改,则有几种可能性。
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 ''
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 ''
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:无论您如何选择这样做,请注意:
db.session
to roll back, making log messages potentially invalid.db.session
回滚,从而使日志消息可能无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.