Skip to content

Instantly share code, notes, and snippets.

@wmantly
Last active February 13, 2017 14:26
Show Gist options
  • Select an option

  • Save wmantly/963e9d43436afbe3630d6d3e7797ddd8 to your computer and use it in GitHub Desktop.

Select an option

Save wmantly/963e9d43436afbe3630d6d3e7797ddd8 to your computer and use it in GitHub Desktop.
import sqlite3
conn = sqlite3.connect( 'babyorm.db' )
conn.row_factory = sqlite3.Row
c = conn.cursor()
class Model( dict ):
def __init__( self, **kwargs ):
for key, value in kwargs.items():
self[key] = value
@staticmethod
def __build_row( row ):
obj = {}
for key in row.keys():
obj[key] = row[key]
return obj
@staticmethod
def __parse_args( obj ):
out = ''
for name, value in obj.items():
if len(out) > 1:
out += " AND "
out += "{}='{}'".format( name, value )
return out
@classmethod
def all( cls ):
c.execute( "SELECT * FROM {}".format(cls.__name__) )
out = []
for row in c:
row_as_dict = cls.__build_row( row )
out.append( cls(**row_as_dict) )
return out
@classmethod
def get( cls, **kwargs ):
c.execute( "SELECT * FROM {} WHERE {} limit 1".format(
cls.__name__,
cls.__parse_args( kwargs )
) )
return cls( **cls.__build_row( c.fetchone() ) )
@classmethod
def filter( cls, **kwargs ):
out = []
c.execute( "SELECT * FROM {} WHERE {} ".format(
cls.__name__,
cls.__parse_args( kwargs )
) )
for row in c:
row_as_dict = cls.__build_row( row )
out.append( cls(**row_as_dict) )
return out
###don't touch the code for these
class Users(Model):
pass
class Stocks(Model):
pass
if __name__ == '__main__':
from pprint import pprint
print( 'all' )
pprint( Users.all() )
print( 'get' )
pprint( Users.get(name="Kenny") )
print( 'filter' )
pprint( Users.filter(name="Dr.") )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment