SQLAlchemy黄金体验

[color=red]session的生命期[/color]

[quote]Web Server Web Framework User-defined Controller Call
-------------- -------------- ------------------------------
web request ->
call controller -> # call Session(). this establishes a new,
# contextual Session.
session = Session()

# load some objects, save some changes
objects = session.query(MyClass).all()

# some other code calls Session, it's the
# same contextual session as "sess"
session2 = Session()
session2.add(foo)
session2.commit()

# generate content to be returned
return generate_content()
Session.remove() <-
web response <-[/quote]
参考链接:
[url]http://docs.sqlalchemy.org/en/latest/orm/session.html#sqlalchemy.orm.session.sessionmaker[/url]

[color=red]遇到下边这个异常应该如何解决?[/color]
[quote]TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30。[/quote]
You are probably not removing the session after the request has been served.
Check out SQLAlchemy documentation on Session.remove.
使用完Seesion后,应该立即把它删除。
示例代码如下:
    
def load(self, class_alias, filterExpr):
klass = pyamf.load_class(class_alias).klass
session = Schema().session
result = session.query(klass).filter(filterExpr).all()
session.remove()
return result

参考链接:[url]http://stackoverflow.com/questions/2314844/limiting-pyamf-flex-sessions-or-setting-a-timeout[/url]

[color=red]数据库路径需要转成ascii码,否则回sqlalchemy会抛出下边的错误[/color]
sqlalchemy.exc.DBAPIError: (error) argument for 's' must be a string None None

[color=red]如何在建表的时候为字段指定默认值?[/color]
使用PassiveDefault(),这是数据库级别的默认值。
如果希望默认值仅在Insert的时候使用的话,使用default

Field(Unicode(256), default=u'default name', nullable=False)


[color=red]使用@hybrid_method时为啥SQLAlchemy抛出这么一个错误:sqlalchemy.exc.ArgumentError: filter() argument must be of type sqlalchemy.sql.ClauseElement or string[/color]
hybrid_method不要直接返回字符串或者布尔值,而是应该返回表达式,如:
return self.name == categoryName

[color=red]
过滤条件中,in_和contains的区别[/color]
[quote]contains(other, **kwargs)
Implement the ‘contains’ operator.
In a column context, produces the clause LIKE '%<other>%'[/quote]
[quote]in_(other)
Implement the in operator.
In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.[/quote]

[color=red]SQLAlchemy的children默认使用的List如何将其改为Dictionary?[/color]
通过为relationship设置collection_class属性,示例代码如下:
children = relationship("Category", lazy="joined", join_depth =1, backref = backref('parent', remote_side=[id]), collection_class=attribute_mapped_collection('name'),)


[color=red]将小数保存到数据库时如何指定保存小数点后边的数字的个数?[/color]
通过设置Numeric的第2个参数,示例代码如下:
unitPrice = Column(Numeric(5, 2))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值