如何使用 webpy 和 SQLObject 管理数据库连接?
Web.py 有自己的数据库 API,web.db。可以使用 SQLObject 代替,但我无法找到描述如何正确执行此操作的文档。我对管理数据库连接特别感兴趣。最好在 wsgi 入口点建立连接并重用它。 Webpy Cookbook 包含一个如何使用 SQLAlchemy 执行此操作的示例。我有兴趣了解如何使用 SQLObject 正确执行类似的操作。
这就是我目前的做法:
class MyPage(object):
def GET(self):
ConnectToDatabase()
....
return render.MyPage(...)
这显然效率低下,因为它在每个查询上建立一个新的数据库连接。我确信有更好的方法。
Web.py has its own database API, web.db. It's possible to use SQLObject instead, but I haven't been able to find documentation describing how to do this properly. I'm especially interested in managing database connections. It would be best to establish a connection at the wsgi entry point, and reuse it. Webpy cookbook contains an example how to do this with SQLAlchemy. I'd be interested to see how to properly do a similar thing using SQLObject.
This is how I currently do it:
class MyPage(object):
def GET(self):
ConnectToDatabase()
....
return render.MyPage(...)
This is obviously inefficient, because it establishes a new database connection on each query. I'm sure there's a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我了解给出的 SQLAlchemy 示例,使用了一个处理器,即为每个连接创建一个会话,并在处理程序完成时提交(或在发生错误时回滚)。
我没有看到任何简单的方法来执行您建议的操作,即在 WSGI 入口点打开连接。您可能需要一个连接池来同时为多个客户端提供服务。 (不过,我不知道效率、代码简单性等方面的要求是什么。请发表评论。)
将
ConnectToDatabase
调用插入每个处理程序当然是丑陋的。我建议您修改说明书示例,将 SQLAlchemy 会话替换为 SQLObject 连接。As far as I understand the SQLAlchemy example given, a processor is used, that is, a session is created for each connection and committed when the handler is complete (or rolled back if an error has occurred).
I don't see any simple way to do what you propose, i.e. open a connection at the WSGI entry point. You will probably need a connection pool to serve multiple clients at the same time. (I have no idea what are the requirements for efficiency, code simplicity and so on, though. Please comment.)
Inserting
ConnectToDatabase
calls into each handler is of course ugly. I suggest that you adapt the cookbook example replacing the SQLAlchemy session with a SQLObject connection.