sqlalchemy 默認的pool_size=5
pool裡存放的是在跟數據庫的的閒置連接,
使用c1 = engine.connect() 或
session = scoped_session(sessionmaker(bind=engine))
會創建連接, 創建連接的步驟
1、看pool裡是否有連接,如果有取出該連接返回
2、pool沒有空閉的連接則建立一個新接的連接
隻有當使用engine.close() 或
session2.commit()、session2.rollback()、session2.close()
後連接又返回到pool連接池裡
http://simple-is-better.com/news/651
文章說要在 finally 裡web.ctx.orm.commit()後加上
web.ctx.orm.close() # <=- 关闭session,或者用 .remove()
個人認為這一點並不是必須的,因為以經調用了web.ctx.orm.commit()
pool裡存放的是在跟數據庫的的閒置連接,
使用c1 = engine.connect() 或
session = scoped_session(sessionmaker(bind=engine))
會創建連接, 創建連接的步驟
1、看pool裡是否有連接,如果有取出該連接返回
2、pool沒有空閉的連接則建立一個新接的連接
隻有當使用engine.close() 或
session2.commit()、session2.rollback()、session2.close()
後連接又返回到pool連接池裡
http://simple-is-better.com/news/651
文章說要在 finally 裡web.ctx.orm.commit()後加上
web.ctx.orm.close() # <=- 关闭session,或者用 .remove()
個人認為這一點並不是必須的,因為以經調用了web.ctx.orm.commit()
#!/usr/bin/env python
from sqlalchemy import create_engine
engine = create_engine("mysql://root:liukesun@172.17.22.131/testdb", pool_size=5,echo_pool=True)
c1 = engine.connect()
c2 = engine.connect()
c3 = engine.connect()
c1.close()
c2.close()
c3.close()
# pool size is now three.
raw_input()
for i in xrange(10):
c = engine.connect()
print c.execute("select 1").fetchall()
c.close()
import string
import random
import web
from sqlalchemy.orm import scoped_session, sessionmaker
from models import *
urls = (
"/", "add",
"/view", "view"
)
def load_sqla(handler):
web.ctx.orm = scoped_session(sessionmaker(bind=engine))
try:
return handler()
except web.HTTPError:
web.ctx.orm.commit()
raise
except:
web.ctx.orm.rollback()
raise
finally:
web.ctx.orm.commit()
# If the above alone doesn't work, uncomment
# the following line:
#web.ctx.orm.expunge_all()
app = web.application(urls, locals())
app.add_processor(load_sqla)
class add:
def GET(self):
web.header('Content-type', 'text/html')
fname = "".join(random.choice(string.letters) for i in range(4))
lname = "".join(random.choice(string.letters) for i in range(7))
u = User(name=fname
,fullname=fname + ' ' + lname
,password =542)
web.ctx.orm.add(u)
return "added:" + web.websafe(str(u)) \
+ "<br/>" \
+ '<a href="/view">view all</a>'
class view:
def GET(self):
web.header('Content-type', 'text/plain')
return "\n".join(map(str, web.ctx.orm.query(User).all()))
if __name__ == "__main__":
app.run()