Created
June 18, 2015 14:04
-
-
Save herbps10/3c51cff5b14e6df3be85 to your computer and use it in GitHub Desktop.
Setting up SQLAlchemy with Application Factory pattern and Blueprints
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 flask import current_app, Blueprint, render_template | |
from database import db_session | |
from model import Product | |
admin = Blueprint('admin', __name__, url_prefix='/admin') | |
@admin.route('/') | |
def index(): | |
product = db_session.query(Product).first() | |
return product.name |
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 flask import Flask | |
from database import init_engine, init_db | |
def init_app(): | |
app = Flask(__name__) | |
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' | |
init_engine(app.config['SQLALCHEMY_DATABASE_URI']) | |
init_db() | |
from admin import admin | |
app.register_blueprint(admin) | |
return app | |
if __name__ == '__main__': | |
app = init_app() | |
app.run('127.0.0.1', 5000, debug=True) |
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 sqlalchemy import create_engine | |
from sqlalchemy.orm import scoped_session, sessionmaker, create_session | |
from sqlalchemy.ext.declarative import declarative_base | |
engine = None | |
db_session = scoped_session(lambda: create_session(bind=engine)) | |
Base = declarative_base() | |
#Base.query = db_session.query_property() | |
def init_engine(uri, **kwargs): | |
global engine | |
engine = create_engine(uri, **kwargs) | |
return engine | |
def init_db(): | |
from model import Product | |
Base.metadata.create_all(bind=engine) |
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 sqlalchemy import Column, Integer, String | |
from database import Base | |
class Product(Base): | |
__tablename__ = 'products' | |
id = Column(Integer, primary_key=True) | |
name = Column(String(50), unique=True) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment