stuff
This commit is contained in:
44
6-baby-orm-save/README.md
Normal file
44
6-baby-orm-save/README.md
Normal file
@ -0,0 +1,44 @@
|
||||
ORM Save
|
||||
========
|
||||
|
||||
You're going to write the save function for your Baby ORM. After this, your Baby ORM is complete and usable!
|
||||
|
||||
#### Pseudocode
|
||||
|
||||
Before we write any real code, we're going to write pseudocode. Read through the rest of this README, and pseudocode the two methods. Please include it in comments in your file.
|
||||
|
||||
#### The Save Method
|
||||
|
||||
You want to be able to take any number or arguments from whatever table is supplied, and either create the row, if it doesn't exist, or update the row, if it does exist. The save method should not take parameters, and is an instance method.
|
||||
```py
|
||||
user = Users(name="Cassie") # new instance
|
||||
user.save() # creates new row in table, stores id, returns True on success
|
||||
|
||||
cassie = Users.get(name="Cassie") # existing row instance
|
||||
cassie.hair = "purple"
|
||||
cassie.save() # updates row, returns True
|
||||
```
|
||||
|
||||
#### The Create Method
|
||||
|
||||
The create function is a class method, that creates a new row and returns the instance.
|
||||
```py
|
||||
user = Users.create(name="Greg") # returns newly created instance of User class
|
||||
```
|
||||
Think about the simplest way you can accomplish this.
|
||||
|
||||
|
||||
Recommendations
|
||||
---------------
|
||||
|
||||
If you haven't already become familiar, google the following:
|
||||
```py
|
||||
setattr()
|
||||
hasattr()
|
||||
__name__
|
||||
type(self)
|
||||
__dict__
|
||||
**kwargs
|
||||
```
|
||||
Map this out before starting. Plan for what you need to solve this.
|
||||
Go back to your game plan to make sure you're on track. Was your pseudocode accurate? If not, adjust it.
|
BIN
6-baby-orm-save/__pycache__/save.cpython-34.pyc
Normal file
BIN
6-baby-orm-save/__pycache__/save.cpython-34.pyc
Normal file
Binary file not shown.
BIN
6-baby-orm-save/babyorm.db
Normal file
BIN
6-baby-orm-save/babyorm.db
Normal file
Binary file not shown.
15
6-baby-orm-save/create_db.py
Normal file
15
6-baby-orm-save/create_db.py
Normal file
@ -0,0 +1,15 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect('babyorm.db')
|
||||
c = conn.cursor()
|
||||
c.execute("DROP TABLE IF EXISTS Users")
|
||||
c.execute("""CREATE TABLE Users(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR,
|
||||
username VARCHAR,
|
||||
email VARCHAR,
|
||||
created_at DATE,
|
||||
updated_at DATE
|
||||
)""")
|
||||
conn.commit()
|
||||
conn.close()
|
121
6-baby-orm-save/save.py
Normal file
121
6-baby-orm-save/save.py
Normal file
@ -0,0 +1,121 @@
|
||||
from pprint import pprint
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect( 'babyorm.db' )
|
||||
c = conn.cursor()
|
||||
|
||||
class Model( dict ):
|
||||
def __init__(self, **kwargs):
|
||||
# c.execute('pragma table_info("{}")'.format(self.__class__.__name__))
|
||||
self.columns = self.__columns()
|
||||
|
||||
for key, value in kwargs.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
if key in self.columns:
|
||||
return super().__setitem__(key, value)
|
||||
else:
|
||||
return False
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
self.__setitem__(key, value)
|
||||
|
||||
return super().__setattr__(key, value)
|
||||
|
||||
@staticmethod
|
||||
def __parse_args(obj, on_join=" AND "): # needs better name
|
||||
return on_join.join("{} = '{}'".format(name, value) for name, value in obj.items())
|
||||
|
||||
@classmethod
|
||||
def __row_to_dict(cls, row):
|
||||
return {column:row[index] for index, column in enumerate( cls.__columns() )}
|
||||
|
||||
@classmethod
|
||||
def __columns(cls, force_update=False):
|
||||
if force_update or hasattr(cls, 'column'):
|
||||
return cls.column
|
||||
|
||||
c.execute('pragma table_info("{}")'.format(cls.__name__))
|
||||
cls.columns = tuple(d[1] for d in c)
|
||||
|
||||
return cls.columns
|
||||
|
||||
@classmethod
|
||||
def all(cls):
|
||||
c.execute( "SELECT * FROM {}".format(cls.__name__) )
|
||||
|
||||
return [cls(**cls.__row_to_dict(row)) for row in c.fetchall()]
|
||||
|
||||
@classmethod
|
||||
def get(cls, *args, **kwargs):
|
||||
kwargs_ = {'id': args[0]} if args else kwargs
|
||||
c.execute("SELECT * FROM {} WHERE {} limit 1".format(
|
||||
cls.__name__,
|
||||
cls.__parse_args(kwargs_)
|
||||
))
|
||||
|
||||
return cls(**cls.__row_to_dict(c.fetchone()))
|
||||
|
||||
@classmethod
|
||||
def filter(cls, **kwargs):
|
||||
|
||||
c.execute("SELECT * FROM {} WHERE {} ".format(
|
||||
cls.__name__,
|
||||
cls.__parse_args(kwargs)
|
||||
))
|
||||
|
||||
return [cls(**cls.__row_to_dict(row)) for row in c.fetchall()]
|
||||
|
||||
def save( self ):
|
||||
if 'id' in self:
|
||||
self.update()
|
||||
else:
|
||||
self.create()
|
||||
|
||||
def create( self ):
|
||||
keys = ','.join( [key for key in self.keys()] )
|
||||
values = ','.join( ["'{}'".format(value) for value in self.values()] )
|
||||
|
||||
sql_string = "INSERT INTO {} ({}) VALUES ({})".format(
|
||||
self.__class__.__name__,
|
||||
keys,
|
||||
values
|
||||
)
|
||||
print(sql_string)
|
||||
c.execute(sql_string)
|
||||
|
||||
setattr(self, 'id', c.lastrowid)
|
||||
conn.commit()
|
||||
return self
|
||||
|
||||
def update( self ):
|
||||
c.execute("UPDATE {} SET {} WHERE id={}".format(
|
||||
self.__class__.__name__,
|
||||
self.__parse_args(self, ', '),
|
||||
self['id']
|
||||
) )
|
||||
|
||||
conn.commit()
|
||||
|
||||
###don't touch the code for these
|
||||
class Users(Model):
|
||||
pass
|
||||
|
||||
class Stocks(Model):
|
||||
pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
pass
|
||||
# dan = Users(name='dan')
|
||||
# dan.save()
|
||||
# dan.email = "dan@gmail.com"
|
||||
# dan.save()
|
||||
# pprint(dan)
|
||||
|
||||
# print( 'all' )
|
||||
# pprint( Users.all() )
|
||||
# print( 'get' )
|
||||
# pprint( Users.get(name="Kenny") )
|
||||
# print( 'filter' )
|
||||
# pprint( Users.filter(id=dan['id']) )
|
Reference in New Issue
Block a user