Created
January 21, 2015 18:21
-
-
Save danielthiel/6438b773bcf183208fb8 to your computer and use it in GitHub Desktop.
simple SQLAlchemy example
This file contains hidden or 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
from __future__ import print_function | |
import datetime | |
from sqlalchemy import create_engine | |
from sqlalchemy import Column, DateTime, Integer | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.orm import sessionmaker | |
# connect to an database: | |
engine = create_engine('sqlite:///:memory:', echo=False) | |
# declarative base class for our mapping: | |
Base = declarative_base() | |
# Session class is ORMs handle to the database: | |
Session = sessionmaker(bind=engine) | |
class Tester(Base): | |
__tablename__ = 'tester' | |
id = Column(Integer, primary_key=True) | |
some = Column(Integer, default=0) | |
last_update = Column(DateTime, default=datetime.datetime.utcnow, | |
onupdate=datetime.datetime.utcnow) | |
if __name__ == '__main__': | |
# to have a conversation with our db create a Session instance: | |
session = Session() | |
# create tables in the database via the MetaData registy: | |
Base.metadata.create_all(engine) | |
t = Tester() | |
session.add(t) | |
session.commit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment