Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scoped_session(sessionmaker()) or plain sessionmaker() in sqlalchemy?

I am using SQlAlchemy in my web project. What should I use - scoped_session(sessionmaker()) or plain sessionmaker() - and why? Or should I use something else?

## model.py from sqlalchemy import * from sqlalchemy.orm import *  engine = create_engine('mysql://dbUser:dbPassword@dbServer:dbPort/dbName', pool_recycle=3600, echo=False) metadata = MetaData(engine) Session = scoped_session(sessionmaker()) Session.configure(bind=engine) user = Table('user', metadata, autoload=True)  class User(object): pass  usermapper = mapper(User, user)  ## some other python file called abc.py from models import *  def getalluser():    session = Session()      session.query(User).all()    session.flush()    session.close()  ## onemore file defg.py from models import *  def updateuser():    session = Session()      session.query(User).filter(User.user_id == '4').update({User.user_lname: 'villkoo'})    session.commit()    session.flush()    session.close() 

I create a session = Session() object for each request and I close it. Am I doing the right thing or is there a better way to do it?

like image 782
skoovill Avatar asked Jun 29 '11 10:06

skoovill


People also ask

What does Session rollback () do?

Session. rollback() rolls back the current transaction.

What is Scoped_session?

the scoped_session() function is provided which produces a thread-managed registry of Session objects. It is commonly used in web applications so that a single global variable can be used to safely represent transactional sessions with sets of objects, localized to a single thread.

What is Sessionmaker in SQLAlchemy?

Python Flask and SQLAlchemy ORM In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier. from sqlalchemy.

What does First () do in SQLAlchemy?

Return the first result of this Query or None if the result doesn't contain any row. first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).


1 Answers

Reading the documentation is recommended:

the scoped_session() function is provided which produces a thread-managed registry of Session objects. It is commonly used in web applications so that a single global variable can be used to safely represent transactional sessions with sets of objects, localized to a single thread.

In short, use scoped_session() for thread safety.

like image 63
tuomur Avatar answered Sep 19 '22 19:09

tuomur