Last active
July 2, 2018 13:19
-
-
Save dittos/6396622 to your computer and use it in GitHub Desktop.
Two concurrent sessions in Flask-SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
import flask | |
from flask.ext.sqlalchemy import SQLAlchemy | |
app = flask.Flask(__name__) | |
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' | |
app.config['SQLALCHEMY_ECHO'] = True | |
db = SQLAlchemy(app) | |
log_db = SQLAlchemy(app, session_options={ | |
'autocommit': True, | |
'autoflush': False | |
}) | |
class User(db.Model): | |
id = db.Column(db.Integer, primary_key=True) | |
class Log(db.Model): | |
id = db.Column(db.Integer, primary_key=True) | |
line = db.Column(db.Text) | |
user_id = db.Column(db.Integer, db.ForeignKey(User.id)) | |
user = db.relationship(User) | |
def __repr__(self): | |
return '[%d] %s' % (self.user_id, self.line) | |
db.create_all() | |
with app.test_request_context(): | |
u = User() | |
db.session.add(u) | |
db.session.commit() | |
u2 = User() | |
db.session.add(u2) | |
# 다음 줄은 u가 이미 db.session에 붙어있어서 오류 | |
#log_db.session.add(Log(line='hi', user=u)) | |
log_db.session.add(Log(line='hi', user_id=u.id)) | |
log_db.session.flush() | |
#log_db.session.commit() # autocommit=True라서 안해도 됨 | |
print log_db.session.query(Log).all() | |
db.session.commit() |
flask sqlalchemy set autocommit = 0 default, and your operation to set autocommit = True is fail.You can use Neor profile sql to catch sql statement what you send.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you use this pattern to avoid transaction overhead on operations that dont require them?