使用最小SQLAlchemy的金字塔数据库连接管理器 [英] Database Connection Manager for Pyramid using minimal SQLAlchemy

查看:248
本文介绍了使用最小SQLAlchemy的金字塔数据库连接管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Pyramid做了一个启动程序(pcreate -s starter myproject)项目。
如何在需要时为我的应用程序提供数据库连接

I made a starter (pcreate -s starter myproject) project in Pyramid. How do I make database connection available to my application when needed

我在这里查看:订阅数据库授权

下面是代码:

@subscriber(NewRequest)
def new_request_subscriber(event):
    request = event.request
    settings = request.registry.settings
    request.db = sqlite3.connect(settings['db'])
    request.add_finished_callback(close_db_connection)

def close_db_connection(request):
    request.db.close()

我担心的性能,因为它会使每个请求的数据库连接,无论我们是否使用它。

I am worried about the performance as it will make a database connection for every request whether or not we use it or not.

是否好或我应该做在一些其他方式?我如何使用sqlalchemy(在最小的方式,可能是10到15行代码),并使它更好?

Is it fine or should I do it in some other way?How can I use sqlalchemy(in a minimal way,may be 10 to 15 lines of code)and make it better?

注意: t要使用sqlalchemy orm(深度学习曲线)。因此我避免了(pcreate -s alchemy MyProject)

Note:I don't want to use sqlalchemy orm(deep learning curve).Therefore I avoided (pcreate -s alchemy MyProject)

推荐答案

SQLAlchemy解决如果你选择自己做一些事情,你会发现几个问题:)像连接池,事务管理,线程本地会话等。

SQLAlchemy solves quite a few problems you're about to discover if you choose to do everything yourself :) Like connection pooling, transaction management, thread-local sessions etc.

想要使用SQLAlchemy的ORM部分,并且更喜欢在任何地方使用字面SQL(当你遇到SQL注入的时候用hello到SQL注入),你可以轻松地做类似

If you don't want to use the ORM part of SQLAlchemy and prefer to use literal SQL everywhere (say hello to SQL injection when you meet it), you can easily do something like

result = session.execute("""SELECT spam, eggs FROM blah WHERE moo='foo'""")
for row in result:
    print "spam = %s" % row.spam
    print "eggs = %s" % row.eggs

我只是从炼金术模板创建的应用程序开始,删除你不要使用的部分。这可能只是 MyModel models.py 中的定义以及视图中的示例视图.py

I would just start with an app created from the "alchemy" template and remove the parts you're not going to use. Which probably are just the definition of MyModel in models.py and the sample view in views.py.

这篇关于使用最小SQLAlchemy的金字塔数据库连接管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆