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(, index=True)


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

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

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

people =
for person in people:print
    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  # .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!

Saturday, March 22, 2014

The New Speaking JavaScript

I bought this book despite having other general-purpose Javascript references because I've always really liked Dr. Rauschmeyer's precise writing style on his blog. This book does not disappoint. It's a clear, complete, and unambiguous reference to an sometimes misunderstood and often confusing language.

This is an authoritative guide to the language that doesn't complain or split hairs. There's a tremendous amount of information here presented by a subject matter expert who's adept at explaining sometimes difficult and nuanced concepts with remarkable clarity and terseness. He doesn't gloss over anything or make assumptions; he simply tells it like it is.

This isn't a difficult book to read, in fact it's refreshingly easy, but it's probably not going to be great for novices. It assumes a certain capability on the part of the reader. If you're starting from ground zero, I'd recommend something more conversational or introductory. But if you're looking for a brilliantly organized and researched in-depth reference, you won't be disappointed with Speaking Javascript.

Tuesday, December 31, 2013

How I combined simple #Python list comprehension and JSON parsing

There are lots of very interesting things to discover in Python - especially if you've been working with Java or any other programming language for some time. For example this simple piece of code demonstrates how you can quite easily convert a list of of Strings of integers separated by comma - into a list of integers. What I particularly like about this small code is that it uses what Python developers refer to list comprehension.
string1 = "020783, 503553, 555204"
mylist = [int(n) for n in string1.split(',')]
>>>>>> mylist
>>> [020783, 503553, 555204]
Now, that piece of code was all I needed to get the API application I was working on to generate a nested list of integers. As it turns out, Python makes things really easy.
def parse_points(self, json_response):
            result = json.loads(json_response)
            if result.has_key('points'):
                the_points = result['points']['code']
                mylist = [int(n) for n in the_points.split(',')]
                return mylist 
                return result
        except ValueError, e:
            raise PlottingError('JSON Parsing Error: ' + e)
.... Further down the code, that returned value is eventually used to as an array of list:
This would not make much sense to a lot of people out there - that is deliberate because I don't want to show the code in full. Protecting the real code is vital here. However, the aim for this small code is to demonstrate how to parse a list of integers in string separated by comma. With time I will post a full blog with a complete working code on how this works.
Related Posts with Thumbnails