Getting first row from sqlalchemy

Use query.one() to get one, and exactly one result. In all other cases it will raise an exception you can handle: from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import MultipleResultsFound try: user = session.query(User).one() except MultipleResultsFound, e: print e # Deal with it except NoResultFound, e: print e # Deal with that as well There’s also … Read more

SQLAlchemy – performing a bulk upsert (if exists, update, else insert) in postgresql

There is an upsert-esque operation in SQLAlchemy: db.session.merge() After I found this command, I was able to perform upserts, but it is worth mentioning that this operation is slow for a bulk “upsert”. The alternative is to get a list of the primary keys you would like to upsert, and query the database for any … Read more

ImportError: No module named flaskext.sqlalchemy

That snippet is really old. flaskext is no more (or at least very deprecated). Refer to packages directly rather than through flaskext or flask.ext. from flask_sqlalchemy import SQLAlchemy Flask-SQLAlchemy (and most other extensions) no longer register in the flaskext namespace, and flask.ext was deprecated then removed in 1.0. The only correct way to refer to … Read more

AttributeError: ‘int’ object has no attribute ‘_sa_instance_state’

the problem is this: post = Post(body=form.body.data, timestamp=datetime.utcnow(), thread=thread.id, author=g.user.id) you want to work with ORM objects, not primary key columns: post = Post(body=form.body.data, timestamp=datetime.utcnow(), thread=thread, author=g.user) the error means that an integer is being interpreted as an ORM object.

Flask-SQLAlchemy db.create_all() raises RuntimeError working outside of application context

As of Flask-SQLAlchemy 3.0, all access to db.engine (and db.session) requires an active Flask application context. db.create_all uses db.engine, so it requires an app context. with app.app_context(): db.create_all() When Flask handles requests or runs CLI commands, a context is automatically pushed. You only need to push one manually outside of those situations, such as while … Read more

Is a SQLAlchemy query vulnerable to injection attacks?

The underlying db-api library for whatever database you’re using (sqlite3, psycopg2, etc.) escapes parameters. SQLAlchemy simply passes the statement and parameters to execute, the driver does whatever is needed. Assuming you are not writing raw SQL that includes parameters yourself, you are not vulnerable to injection. Your example is not vulnerable to injection.