sqlalchemy Connection Pool

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

#!/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()





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值