Home > OS >  How do I "reset" the db.session that runs in a Python script that uses a database from a F
How do I "reset" the db.session that runs in a Python script that uses a database from a F

Time:11-15

I have the following code:

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, "Unknown column 'new_column' in 'field list'")

That means that db.session is not "refreshing" the database after performing the upgrade operation. Any idea how to do it ?

Thank you,

Regards.

CodePudding user response:

I ended up connecting to mysql using a mysql connector (package mysql-connector-python in pip) then connecting to the database and inserting the records I want to insert manually using mysql INSERT statements.

For reference, here is the syntax:

...
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()
  • Related