简体   繁体   English

使用Peewee ORM打开和关闭多个功能的连接

[英]Opening and closing connections from multiple functions with Peewee ORM

Currently i'm working on a program using the Peewee ORM (v2.10.2). 目前,我正在使用Peewee ORM(v2.10.2)编写程序。 I've read in the docs that is good practice to explicitly open and close the connections in each function. 我已经阅读了文档中的一种很好的做法,即明确地打开和关闭每个函数中的连接。 However, as i've split up my code in different functions the situation occurs where function A uses function B and both independently open and close the DB connection. 但是,由于我将代码拆分为不同的函数,因此会发生以下情况:函数A使用函数B,并且都独立打开和关闭DB连接。 By doing so i get an exception that the connection is already closed, but also has the potential to disrupt the program if function B finishes and closes the connection and function A still has work to do on the database. 这样,我得到一个例外,即连接已经关闭,但是如果函数B完成并关闭连接并且函数A仍在数据库上进行工作,则有可能破坏程序。

Here is some pseudo code to illustrate my problem: 这是一些伪代码来说明我的问题:

def func_b():
    database.get_conn()
    #do database stuff
    database.close()

def func_a():
    database.get_conn()
    #do database stuff
    func_b()
    #do more database stuff <---this will fail cause the connection is already closed by func_b
    database.close() <---this wil raise an exception stating the connection is already closed

What would be the best way to avoid these problems? 避免这些问题的最佳方法是什么?

The answer seems obvious to me...if func_b is only called from func_a, then just remove the connection management code from func_b. 对于我来说,答案似乎很明显...如果仅从func_a中调用func_b,则只需从func_b中删除连接管理代码。 The outermost function, func_a in this case, would handle it. 最外层的函数func_a在这种情况下会处理它。

In a more general sense, typically there is a discrete unit of computation being done. 从更一般的意义上讲,通常有一个离散的计算单元正在执行。 In a web app, this would be a request/response -- thus, for web apps you typically open a connection when you receive a request, then close it upon sending the response. 在Web应用程序中,这将是一个请求/响应-因此,对于Web应用程序,通常在收到请求时打开一个连接,然后在发送响应时将其关闭。

For a script, you can just connect once at the start of the script and close the connection (implicitly or explicitly) when the script finishes. 对于脚本,您只需在脚本开始处连接一次,然后在脚本完成时关闭(隐式或显式)连接。

Generally it is unwise to put your connection management code within functions that do things. 通常,将连接管理代码放在执行功能的函数中是不明智的。 Put them in the outermost scope -- the part that calls the functions. 将它们放在最外面的范围内-调用函数的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM