Bromide
Bromide

Reputation: 1112

How is using SQLAlchemy different in Flask framework

I've written things in SQLAlchemy that work fine but the same workflow/commands seem to be askew when doing them in Flask. For example, these types of lines are getting flagged as "undefined":

metadata = MetaData(db)

abc = Table('abc', metadata, autoload=True)

s = select([abc.name])

I do have from flask.ext.sqlalchemy import SQLAlchemy at the top.

Is there something else I need to be doing additionally or instead?

(For reference, I'm running it at pythonanywhere)

Upvotes: 1

Views: 215

Answers (1)

holdenweb
holdenweb

Reputation: 37023

Importing SQLAlchemy will not give you direct access to the names inside that module. You should also be aware that using the flask_sqlalchemy (formerly flask.ext.sqlalchemy) module uses a somewhat different mechanism to access SQLAlchemy features. This means that any attempt to transfer your current knowledge of SQLAlchemy shouold be informed by a study of the flask_sqlalchemy documentation.

Typically you will create a Flask application and then pass that to a call to SQLAlchemy as in this example. The relevant code is shown below.

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

The db object now has the Model, Column and the various datatypes as attributes, so you can define a table/model in the following way.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

I personally am not fond of this particular access model, since it forces me to qualify the various names inside the db namespace rather than simply importing them from a module and using them unqualified, but it seems to work (at least for relatively uncomplicated databases).

If you are an experienced SQLAlchemy user you might want to consider using the standard access mechanisms, though this may render you vulnerable to subtle bugs due to unanticipated thread/web session interactions. I have also heard that it can be tricky to deploy multiple databases. I have no direct evidence of this, so please regard it as anecdotal.

Upvotes: 3

Related Questions