TODO: write readme
-
-
Save caffeinatedMike/7e7b734834a28a8c0bfc53620047ea79 to your computer and use it in GitHub Desktop.
Flask + sqlalchemy declarative base example
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
from flask import Flask | |
from database import db_session | |
app = Flask(__name__) | |
@app.teardown_appcontext | |
def shutdown_session(exception=None): | |
db_session.remove() |
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
from sqlalchemy import create_engine | |
from sqlalchemy.orm import scoped_session, sessionmaker | |
from sqlalchemy.ext.declarative import declarative_base | |
engine = create_engine('sqlite:///test.db', convert_unicode=True) | |
db_session = scoped_session(sessionmaker(autocommit=False, | |
autoflush=False, | |
bind=engine)) | |
Base = declarative_base() | |
Base.query = db_session.query_property() | |
def init_db(): | |
# import all modules here that might define models so that | |
# they will be registered properly on the metadata. Otherwise | |
# you will have to import them first before calling init_db() | |
import models | |
Base.metadata.create_all(bind=engine) |
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
from sqlalchemy import Column, Integer, String | |
from database import Base | |
class User(Base): | |
__tablename__ = 'users' | |
id = Column(Integer, primary_key=True) | |
name = Column(String(50), unique=True) | |
email = Column(String(120), unique=True) | |
def __init__(self, name=None, email=None): | |
self.name = name | |
self.email = email | |
def __repr__(self): | |
return '<User %r>' % (self.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment