我如何 "reset" db.session 在 Python 脚本中运行,该脚本使用来自 Flask 应用程序的数据库?

How do I "reset" the db.session that runs in a Python script that uses a database from a Flask App?

我有以下代码:

from flask_migrate import upgrade

app = create_app()

with app.app_context():
    # Merge branch into master and then upgrade the database
    os.system("git pull origin BRANCH-B")
    
    # Upgrade the database (equivalent to flask db upgrade)
    # Assume here that a new column was added called: new_column
    upgrade()
    
    # Adding a row to the database using a Model object and complying with the
    # NEW database rows and format (after upgrade)
    model = Model(id=1, new_column = "test")
    
    # Above line gives an error

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1054, "'field list' 中的未知列 'new_column'")

这意味着 db.session 在执行升级操作后没有“刷新”数据库。知道怎么做吗?

谢谢,

此致。

我最终使用 mysql 连接器(包 mysql-connector-python in pip)连接到 mysql,然后连接到数据库并插入我想插入的记录手动使用 mysql INSERT 语句。

作为参考,语法如下:

...
import mysql.connector

def insert_new_records():
    app = create_app()
    with app.app_context():
        cnx = mysql.connector.connect(
            user=app.config['SQL_USERNAME'], 
            password=app.config['SQL_PASSWORD'], 
            port=app.config['SQL_PORT'],
            database=app.config['DATABASE']
        )
        cursor = cnx.cursor()

        insert_stmt = (
          "INSERT INTO table (id, new_column) "
          "VALUES (%s, %s)"
        )

        # Insert new rows
        id = 1
        new_column = "test" # Could be any Python datatype
        data = (id, new_column)
        cursor.execute(insert_stmt, data)
        cnx.commit()