问题
I have a webapp that communicates with a postgres database via Flask-SQLAlchemy.
The app successfully adds/updates individual images to the database.
The calls to func1_add_image
, func2_add_image
are done via separate fetch
request from javascript code.
# in python
db = sqlalchemy(session_options={'autocommit': False})
...
@bp.route('/api/v1_2/func1_add_image', methods=['POST'])
def func1_add_image():
db.session.add(image1)
db.session.commit()
...
@bp.route('/api/v1_2/func2_add_image', methods=['POST'])
def func2_add_image():
db.session.add(image2)
db.session.commit()
...
# in javascript
let queryUrl1 = MLJ.model.getUrlBase() + 'api/v1_2/func2_add_image';
await fetch(queryUrl1, fetchData1);
...
let queryUrl2 = MLJ.model.getUrlBase() + 'api/v1_2/func2_add_image';
await fetch(queryUrl2, fetchData2);
Now, I want to add multiple images in a single commit.
So I changed the code to the following, but the images are not added/updated in the database.
# in python
db = sqlalchemy(session_options={'autocommit': False})
...
@bp.route('/api/v1_2/func1_add_image', methods=['POST'])
def func1_add_image():
db.session.add(image1)
db.session.commit()
@bp.route('/api/v1_2/func2_add_image', methods=['POST'])
def func2_add_image():
db.session.add(image2)
db.session.commit()
@bp.route('/api/v1_2/func3_commit', methods=['POST'])
def func3_commit():
db.session.commit()
...
# in javascript
let queryUrl1 = MLJ.model.getUrlBase() + 'api/v1_2/func2_add_image';
await fetch(queryUrl1, fetchData1);
...
let queryUrl2 = MLJ.model.getUrlBase() + 'api/v1_2/func2_add_image';
await fetch(queryUrl2, fetchData2);
...
let queryUrl3 = MLJ.model.getUrlBase() + 'api/v1_2/func3_commit';
await fetch(queryUrl3, fetchData3);
From what I read here
"...infrastructure to establish a single Session, associated with the request, which is correctly constructed and torn down corresponding torn down at the end of a request"
the session is created and torn down per request.
So this is probably the reason why the changes are not persisted in the database.
Using Flask-SQLAlchemy, how can I keep the session open across separate requests?
Thanks
来源:https://stackoverflow.com/questions/65927436/how-to-keep-a-session-open-across-separate-requests-with-flask-sqlalchemy