Skip to content

Instantly share code, notes, and snippets.

@caffeinatedMike
Forked from vulcan25/README.md
Created July 27, 2022 03:18
Show Gist options
  • Save caffeinatedMike/7e7b734834a28a8c0bfc53620047ea79 to your computer and use it in GitHub Desktop.
Save caffeinatedMike/7e7b734834a28a8c0bfc53620047ea79 to your computer and use it in GitHub Desktop.
Flask + sqlalchemy declarative base example

TODO: write readme

from flask import Flask
from database import db_session
app = Flask(__name__)
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
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)
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