Using the SQLAlchemy ORM inside an Alembic migration: how do I?

After a bit of experimentation using @velochy’s answer, I settled on something like the following pattern for using SqlAlchemy inside Alembic. This worked great for me and could probably serve as a general solution for the OP’s question: from sqlalchemy.orm.session import Session from alembic import op # Copy the model definitions into the migration script … Read more

Setting delete-orphan on SQLAlchemy relationship causes AssertionError: This AttributeImpl is not configured to track parents

OK in this case, you need to look more closely, though there is a warning here that likely should become an exception, and I’ll look into that. Here’s a working version of your example: from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base Base= declarative_base() tagging = Table(‘tagging’,Base.metadata, … Read more

Share sqlalchemy models between flask and other apps

The Flask-SQLAlchemy extension, like most Flask extensions, should be created outside the factory, then initialized in the factory using init_app. This is so that you can use the db object before an app is created. db = SQLAlchemy() def create_app(): app = Flask(__name__) db.init_app(app) return app Your Flask app, like any properly designed Python project, … Read more

SQLAlchemy can’t connect to an mssql database

If not specified in the URL, the default driver for the mssql+pyodbc dialect would be “SQL Server” [1]. That means you need to have a section that reads like this in /etc/unixODBC/odbcinst.ini: [SQL Server] Driver=/path/to/library.so It works “automatically” on Windows, because if you open Administrator Tools -> Data Sources (ODBC), you would most likely find … Read more

SQLAlchemy INSERT IGNORE

prefix_with(“TEXT”) adds arbitrary text between INSERT and the rest of the SQL. execute() accepts a list of dictionaries with the records you would like to insert or a single dictionary if you only want to insert a single record. The SQLite syntax for the behavior you’re looking for: inserter = table_object.insert().prefix_with(“OR REPLACE”) inserter.execute([{‘column1′:’value1’}, {‘column1′:’value2’}])

Setting SQLAlchemy autoincrement start value

You can achieve this by using DDLEvents. This will allow you to run additional SQL statements just after the CREATE TABLE ran. Look at the examples in the link, but I am guessing your code will look similar to below: from sqlalchemy import event from sqlalchemy import DDL event.listen( Article.__table__, “after_create”, DDL(“ALTER TABLE %(table)s AUTO_INCREMENT … Read more