开发者

What is a good way to handle database objects in python classes?

开发者 https://www.devze.com 2022-12-21 23:42 出处:网络
Should I access global db object directly from within the methods of each class? 开发者_开发技巧 Or from each method, should I instantiate an instance of the db object?

Should I access global db object directly from within the methods of each class? 开发者_开发技巧 Or from each method, should I instantiate an instance of the db object?

One of my database objects changes depending on the id of the info being accessed so it is created through a function connectToDatabase(id). Should I make this a global function, have it return a database object and instantiate it from each method, or something else?

Thanks.


In this case, like in many others, I prefer dependency injection: have your class (e.g in its __init__) accept the DB connection as an argument.

This makes it easier and cleaner to test, lets you switch strategies as needed (e.g. to move to a "pool of DB connections" strategy if you find otherwise you're making too many DB connections at once), and distributes responsibilities more accurately and flexibly.

In general, I think of Dependency Injection as probably the most important Design Pattern that was not listed in the great "Gang of 4" book!-)


SQLAlchemy suggests that a function which creates the session be global.

http://www.sqlalchemy.org/docs/reference/orm/sessions.html#sqlalchemy.orm.sessionmaker

It is intended that the sessionmaker() function be called within the global scope of an application, and the returned class be made available to the rest of the application as the single class used to instantiate sessions.

0

精彩评论

暂无评论...
验证码 换一张
取 消