3

I am looking for a generic way to store python objects in a database. Of course I could just pickle the objects, but that way I would have binary blobs in my database. That way I can not search my objects. Also it seems to be easier to put it together with other applications.

So in my fantasy, I have on object like

class myClass
    data1=1
    data2='foobar'
    data3=some_html_object
    ...

and could do something like

mydata=myClass()
mydata.add_data(various_things)
mydata.save_to_database()

and would end up with a database which has colums called data1,data2, data3, where I have the values of the of the objects attributes in the rows stored as text which would be searchable. Of course some inital setup would have to be done.

And of course it would be nice if I could plug any database I want (well, at least not just one database) and would not be bothered with the details.

Now of course I could program my own framework to let me do this, but I was hoping that this has been done bevore by someone else :)

Any suggestions?

Isaac
  • 810
  • 2
  • 13
  • 31

2 Answers2

4

Your fantasy in fact exists!

You describe something called the Active Record Pattern. It is usually implemented by using Object-Relational Mapping. One common solution for Python is SQLAlchemy, but Storm is somehow popular too:

See What are some good Python ORM solutions?


If your are developing for the Web, Django possess its own ORM.

Community
  • 1
  • 1
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125
3

It sounds like what you want is an Object Relational Mapper (ORM) to map SQL tables to objects.

The most popular ORMs that support different dialects by community are the following:

  • Python -- SQLAlchemy, Storm, Django (built into web framework)
  • Ruby -- ActiveRecord, Sequel
  • Node -- Sequelize

For a specific example of implementing what you described in Python using SQLAlchemy, check out this blog post that walks through a simple example

lbayas
  • 31
  • 1