-1

guys.I need some help.Days ago,I deployed my web project on our server,everything worked well.But next morning I loged the page,and I got an error "Mysql server has gone away...",then I checked the reasons.I found it caused by that the conf of Msyql "wait_timeout=2880000" and "interactive_timeout = 2880000",I also got some solutions like "set pool_recycle=7200 when create_engine" but it doesn't work.I continue searching the ways to it.Someones says 'we must execute session.close() when after use if'.I was going to try it,but there is another error came to me.I used sqlalchemy.orm.relation, there is many_to_many relation between class User and Role.Now I add DBSession.close() like

  @classmethod
  def get_by_id(cls, id):
    user_ = DBSession.query(cls).get(id)
    DBSession.close()
    return user_

But now when I did this

user = User.get_by_id(1)
user.roles

ERROR:Parent instance <User at 0xace51cc> is not bound to a Session;
lazy load operation of attribute 'roles' cannot proceed

So How can I solve my problem.Much appreciate!

jiank
  • 305
  • 1
  • 4
  • 8

1 Answers1

1

Add the user instance to an open session.

# assuming databaseSession is a valid session object using a valid engine
engine = create_engine('mysql://user@localhost:3600/database')
Session = sqlalchemy.orm.sessionmaker()
Session.configure(bind=engine) 
databaseSession = Session()
databaseSession.add(user)

user.roles

then close the session later.

databaseSession.close()
Keith John Hutchison
  • 4,955
  • 11
  • 46
  • 64
  • firstly,thanks for answering.This way probably isn't practical.Some times I will use it on html pages. – jiank Aug 19 '13 at 07:11
  • You need an open session in order for lazy load operations to work. An alternative would be to get the role information and pass that back in the result before closing the session. When I use this method I return something that is converted to json, something like json.dumps( { 'user' : ..., roles : [ 'role' : ..., 'role' : ... ] } ) – Keith John Hutchison Aug 19 '13 at 07:20