Created
October 20, 2016 06:06
-
-
Save benhoyle/285171fae8813e58adbc0e71669ca403 to your computer and use it in GitHub Desktop.
A quick skeleton file to create an SQLite database with SQL Alchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from datetime import datetime | |
# Define name and path for SQLite3 DB | |
db_name = "filename.db" | |
db_path = os.path.join(os.getcwd(), db_name) | |
# Create DB | |
from sqlalchemy import create_engine | |
engine = create_engine('sqlite:///' + db_path, echo=False) | |
# Setup imports | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.ext.declarative import declared_attr | |
from sqlalchemy.orm import relationship | |
# Define Class for Excluded Matter Case Details | |
from sqlalchemy import Column, Integer, String, Date, Boolean, Text, \ | |
ForeignKey | |
class Base(object): | |
""" Extensions to Base class. """ | |
@declared_attr | |
def __tablename__(cls): | |
return cls.__name__.lower() | |
id = Column(Integer, primary_key=True) | |
def as_dict(self): | |
""" Return object as a dictionary. """ | |
temp_dict = {} | |
temp_dict['object_type'] = self.__class__.__name__ | |
for c in self.__table__.columns: | |
cur_attr = getattr(self, c.name) | |
# If datetime generate string representation | |
if isinstance(cur_attr, datetime): | |
cur_attr = cur_attr.strftime('%d %B %Y') | |
temp_dict[c.name] = cur_attr | |
return temp_dict | |
def populate(self, data): | |
""" Populates matching attributes of class instance. | |
param dict data: dict where for each entry key, value equal attributename, attributevalue.""" | |
for key, value in data.items(): | |
if hasattr(self, key): | |
# Convert string dates into datetimes | |
if isinstance(getattr(self, key), datetime) or str(self.__table__.c[key].type) == 'DATE': | |
value = datetime.strptime(value, "%d %B %Y") | |
setattr(self, key, value) | |
Base = declarative_base(cls=Base) | |
class Example(Base): | |
""" Model for an examples class. """ | |
# name - example field | |
name = Column(String(256)) | |
# Add other fields here | |
# Add other classes here | |
# Create new DB | |
Base.metadata.create_all(engine) | |
# Setup SQLAlchemy session | |
from sqlalchemy.orm import sessionmaker | |
Session = sessionmaker(bind=engine) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use from another Python file in the same directory:
from datamodels import Example, Session
then to create a new session and add an object: