Search code examples
pythonpeewee

Opening and closing connections from multiple functions with Peewee ORM


Currently i'm working on a program using the 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. 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.

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?


Solution

  • 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. The outermost function, func_a in this case, would handle it.

    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.

    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.