本文介绍了sqlalchemy中的scoped_session(sessionmaker())或纯sessionmaker()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Web项目中使用SQlAlchemy.我应该使用什么-scoped_session(sessionmaker())或普通的sessionmaker()-为什么?还是我应该使用其他东西?

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()

我为每个请求创建一个session = Session()对象,然后将其关闭.我是在做正确的事,还是有更好的方法呢?

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?

推荐答案

阅读文档:

简而言之,请使用scoped_session()来确保线程安全.

In short, use scoped_session() for thread safety.

这篇关于sqlalchemy中的scoped_session(sessionmaker())或纯sessionmaker()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 14:56