Created
March 12, 2012 23:31
-
-
Save rduplain/2025411 to your computer and use it in GitHub Desktop.
Use pure SQLAlchemy APIs with Flask. Integrate with Flask-SQLAlchemy.
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
# Using SQLAlchemy 0.7.5 and Flask-SQLAlchemy 0.15. | |
from flask import Flask | |
from flask.ext.sqlalchemy import SQLAlchemy, BaseQuery, _QueryProperty | |
from models import Base | |
SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db' | |
class PrintQuery(BaseQuery): | |
"Dumb query class to demonstrate custom query class injection." | |
def __iter__(self): | |
print self | |
return super(PrintQuery, self).__iter__() | |
app = Flask(__name__) | |
app.config.from_object(__name__) | |
db = SQLAlchemy(app) | |
db.Model = Base | |
db.Model.query_class = PrintQuery | |
db.Model.query = _QueryProperty(db) | |
if __name__ == '__main__': | |
from models import User | |
db.create_all() | |
with app.test_request_context(): | |
user = User(name='Ron', fullname='Ron DuPlain', password='secret') | |
db.session.add(user) | |
db.session.commit() | |
with app.test_request_context(): | |
for user in User.query.all(): | |
print user |
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
"Pure SQLAlchemy models for use with Flask-SQLAlchemy. 0 Flask code here." | |
from sqlalchemy import Column, Integer, String | |
from sqlalchemy.ext.declarative import declarative_base | |
Base = declarative_base() | |
class User(Base): | |
"http://docs.sqlalchemy.org/en/latest/orm/tutorial.html" | |
__tablename__ = 'users' | |
id = Column(Integer, primary_key=True) | |
name = Column(String) | |
fullname = Column(String) | |
password = Column(String) | |
def __repr__(self): | |
return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment