我正在编写一个连接到数据库的 Web 应用程序。我目前正在使用从其他模块导入的模块中的变量,但这感觉很讨厌。
# server.py
from hexapoda.application import application
if __name__ == '__main__':
from paste import httpserver
httpserver.serve(application, host='127.0.0.1', port='1337')
# hexapoda/application.py
from mongoalchemy.session import Session
db = Session.connect('hexapoda')
import hexapoda.tickets.controllers
# hexapoda/tickets/controllers.py
from hexapoda.application import db
def index(request, params):
tickets = db.query(Ticket)
问题是我获得了与数据库的多个连接(我猜是因为我application.py
在两个不同的模块中导入,所以该Session.connect()
函数被执行了两次)。
如何在不创建多个连接的情况下从多个模块访问(即在整个应用程序中db
只调用一次)?Session.connect()