Monday, 12 October 2020

How do I execute a MySQL stored procedure in a sqlalchemy scoped session to return a single result set of data (for flask web app)?

Most the examples I've found to call a MySQL stored proc and store results in python use the callproc method with a cursor, but the callproc method doesn't exist on a scoped_session object created with sqlalchemy. I'm using a scoped_session because I'm building a flask app that will use the session in different parts of the app (the scoped session works for simple select statement). The stored procedure makes one select and returns data. I'm using mysql.connector for the mysql driver.

I've tried the following inside of a flask route but I'm getting an error:

mysql_engine = create_engine(conn_string)
DbSession = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=mysql_engine))

@app.route('/')
def index():
    # register session
    DbSession()

    sql = 'call myStoredProc(:param);'

    # call stored procedure: getting error "Use multi=True when executing multiple statements"
    result = DbSession.execute(sql, {'param': 'param value'})
    data = [dict(r) for r in result]

    # remove session from register
    DbSession.remove()

    # pass data to template to render
    return render_template('index.html', data = data)

As shown in the code, I'm getting this error: "Use multi=True when executing multiple statements." I've learned that the mysq.connector assumes an out parameter for stored procedures so by default thinks it is a multi-statement even though the stored proc is simply running a single select query. The execute method on the DbSession does not accept options.

The suggestion in the error is to use cmd_query_iter for multiple statements but that also doesn't exist on a DbSession object.

Any suggestions on how to do this?



from How do I execute a MySQL stored procedure in a sqlalchemy scoped session to return a single result set of data (for flask web app)?

No comments:

Post a Comment