Question

I'm actually using SQLAlchemy with MySQL and Pyro to make a server program. Many clients connect to this server to make requests. The programs only provides the information from the database MySQL and sometimes make some calculations.

Is it better to create a session for each client or to use the same session for every clients?

Was it helpful?

Solution

What you want is a scoped_session.

The benefits are (compared to a single shared session between clients):

  • No locking needed
  • Transactions supported
  • Connection pool to database (implicit done by SQLAlchemy)

How to use it

You just create the scoped_session:

Session = scoped_session(some_factory)

and access it in your Pyro methods:

class MyPyroObject():
    def remote_method(self):
         Session.query(MyModel).filter...

Behind the scenes

The code above guarantees that the Session is created and closed as needed. The session object is created as soon as you access it the first time in a thread and will be removed/closed after the thread is finished (ref). As each Pyro client connection has its own thread on the default setting (don't change it!), you will have one session per client.

OTHER TIPS

The best I can try is to create new Session in every client's request. I hope there is no penalty in the performance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top