the proper method for making a DB connection available across many python modules

前端 未结 3 685
甜味超标
甜味超标 2020-12-29 12:35

I want to make a single database object available across many python modules.

For a related example, I create globl.py:

DOCS_ROOT=\"c:\\docs         


        
3条回答
  •  天涯浪人
    2020-12-29 12:41

    I think Daniel already answered the question, while I'd like to add few comments about the cursor object you want to share.

    It is generally not a good idea to share the cursor object that way. Certainly it depends on what your program is, but as a general solution I'd recommend you to hide this cursor object behind a "factory" producing cursors. Basically you can create a method cursor() or get_cursor() instead of making the cursor a global variable. The major benefit (but not the only one) - you can hide a more complex logic behind this "factory" - pooling, automatic re-connection in case the connection is dropped, etc. Even if you don't need it right away - it will be very easy to add it later if you start using this approach now, and while for now you can keep this function implementation as simple as return _cursor.

    And yes, still, the module itself will be imported once only.

提交回复
热议问题