Thursday, July 24, 2014

Working with Peewee ORM

Wow, it's been a long while since I last posted something here. As always work and family have been taking a huge chunk of my free time - making it almost impossible to drop by to update this blog.

That said, I have been playing around with Peewee. It is a very small ORM (Object Relational Mapping) framework for working with your database. It is fits very well with things like Flask or Bottle Python frameworks. If you've spent time developing in Django you will feel very much at home. All the models and queries are basically the same except a few that make the Peewee stand out.

It currently supports PostgreSQL, MySQL and SQLite. Installation is a breeze - just use pip at a command prompt like so:

$pip install peewee

Here is a sample application that defines our models, creates the tables, inserts the data and prints them all out again.

################### Example of using the Peewee ORM ########################

from peewee import *
db = SqliteDatabase(app.db)
class BaseModel(Model):
    class Meta:

        database = db        
class Person(BaseModel):
    name = CharField(max_length=100, index=True)    
class StatusUpdate(BaseModel):

    person    = ForeignKeyField(Person, related_name='statuses')
    status  = TextField()
    timestamp = DateTimeField(default=datetime.datetime.now, index=True)

Person.create_table()
StatusUpdate.create_table()    

#------ Inserting into our new tables --------
huey = Person(name='Nkem')
huey.save()

#or
charlie =  Person.create(name='Charlie')
StatusUpdate.create(charlie, status='First status')

#----- querying -----

people = Person.select().order_by(Person.name)
for person in people:print person.name
    print person.name 
    for status in person.statuses.order_by(StatusUpdate.timestamp):
        print '*', status.status

        
 
For those who like to take control of their SQL, Peewee also allows you to run raw SQL commands. Here is an example of it:

db = SqliteDatabase(':memory:')

class Person(Model):
    name = CharField()
    class Meta:
        database = db

# let's pretend we want to do an "upsert", something that SQLite can
# do, but peewee cannot.
for name in ('charlie', 'mickey', 'huey'):
    db.execute_sql('REPLACE INTO person (name) VALUES (?)', (name,))

# now let's iterate over the people using our own query.
for person in Person.raw('select * from person'):
    print person.name  # .raw() will return model instances.
I find it quite interesting mixing it with Flask. There are a few ideas I have and will explore them over the weekend and post the result here. There are tons of things you can do with this little framework - so go explore and see what you come up with. Good luck!

No comments:

Related Posts with Thumbnails