Skip to content

Instantly share code, notes, and snippets.

@nickretallack
Created October 30, 2014 01:00
Show Gist options
  • Save nickretallack/ec096a8013046c42d8f9 to your computer and use it in GitHub Desktop.
Save nickretallack/ec096a8013046c42d8f9 to your computer and use it in GitHub Desktop.
LocalProxy and Flask-SQLAlchemy don't play nicely together
from flask import Flask, Response
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug.local import LocalProxy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config["SQLALCHEMY_ECHO"] = True
db = SQLAlchemy(app)
def get_current_friend():
return Friend.query.filter_by(name="fred").first()
current_name = LocalProxy(lambda: "bob")
current_friend = LocalProxy(get_current_friend)
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
friend = db.relationship('Friend', uselist=False)
class Friend(db.Model):
id = db.Column(db.ForeignKey('person.id'), primary_key=True)
name = db.Column(db.String)
@app.route('/')
def test():
# setup
friend = Friend(name="fred")
person = Person(name="bob", friend=friend)
db.session.add(person)
db.session.commit()
# make sure to evaluate it early
print current_friend.name
result = []
result.append("== Using a string LocalProxy but it thinks it's the wrong type")
try:
person = Person.query.filter_by(name=current_name).first()
except Exception, error:
result.append(str(error))
result.append("== Using a model LocalProxy but it thinks it's None")
try:
person = Person.query.filter_by(friend=current_friend).first()
except Exception, error:
result.append(str(error))
result.append("== Creating a model with a string LocalProxy. Same problem.")
new_person = Person(name=current_name)
db.session.add(new_person)
try:
db.session.commit()
except Exception, error:
db.session.rollback()
result.append(str(error))
result.append("== Uh oh, that rollback destroyed my LocalProxy, so I can't even demonstrate the last one.")
new_person = Person(name="joe", friend=current_friend)
try:
db.session.add(new_person)
except Exception, error:
result.append(str(error))
return Response("\n".join(result), content_type="text/plain")
if __name__ == "__main__":
db.create_all()
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment