dre
dre

Reputation: 1434

python design pattern for abstracting data access: advantages, disadvantages?

I was wondering for a few ways to accomplish abstracting the data storage access away from the main application and a small example, an IoC framework seems overkill, maybe passing object via constructor parameter (facade).

is the below pseudo-code a good way to do things and how do i fill in the missing pieces with python?

main.py
    resp = Repository(engine=NoSql)  # can easily switch to nosql???
    resp.save("hello");
    resp.select("hello");

repository.py
class Repository:
    def __init__(self, engine):
        self.engine = engine

    def save(self, str)
        engine.save(str)

    def select(self, str)
        engine.select(str)

nosql.py
class NoSql:
    def save(self, str)
        nosql.save(str)

    def select(self, str)
        nosql.select(str)

mysql.py
class MySql:
    def save(self, str)
        mysql.save(str)

    def select(self, str)
        mysql.select(str)

Upvotes: 0

Views: 4162

Answers (3)

S.Lott
S.Lott

Reputation: 391952

You're about to create Yet Another ORM layer.

Rather than waste a lot of time reinventing that wheel, learn about existing ORM, and adapt one to your noSQL database engine of choice.

Start, for example, with SQLAlchemy as an ORM that can do all of what you want (and more) for SQL.

Because of Python's duck typing you can invent a compatible noSQL ORM or Repository ORM or anything else you think is important.

Do not, however, reinvent this wheel from scratch. Read a few other implementations. SQLObject, Django ORM, SQLAlchemy are good places to start.

Upvotes: 2

Hunter
Hunter

Reputation: 107

That's a workable solution, I've done similar things on other projects. Make sure you keep all the database implementation in the database classes. main should be able to switch between the two without any changes. If you need to make changes to main when switching, that's probably code that should be in the Sql classes.

I would make Repository a base class that the others derive from instead of a wrapper. That way if two implementations have identical or very similar code you can move parts into Repository so you don't have to duplicate it.

Upvotes: 0

Demian Brecht
Demian Brecht

Reputation: 21378

I'd say the above isn't a great way to go about it. The consumer (in this case main.py) shouldn't know anything about the model's implementation details. What I might do is store key/value pairs in an external configuration file to be used by the model to determine the engine to use.

Upvotes: 1

Related Questions