pallets-eco / flask-admin

Simple and extensible administrative interface framework for Flask
https://flask-admin.readthedocs.io
BSD 3-Clause "New" or "Revised" License
5.73k stars 1.57k forks source link

Refreshing causes old values to appear #1593

Open rhymes opened 6 years ago

rhymes commented 6 years ago

Hi,

I've been noticing a weird behaviour that we can't seem to understand how to fix.

Once you edit a field in Flask Admin the values gets correctly saved to the database (I checked) but sometimes when refreshing the Flask Admin UI it displays the old values, seemingly at random.

You can see it in the following screen recording (I'm refreshing a few times).

flaskadmin

I'm using Python 3.6.3, Flask 0.12.2, flask-admin 1.5.0 and SQLAlchemy 1.1.15 and flask-sqlalchemy 2.3.2

It seems like it's not correctly refreshing the session.

I've even tried with the following but to no avail:

from flask_admin.contrib.sqla import ModelView
class BaseView(ModelView):
    def after_model_change(self, form, model, is_created):
        self.session.expire_all()
        self.session.remove()

How can I fix it?

Thank you

rhymes commented 6 years ago

After googling, reading http://docs.sqlalchemy.org/en/latest/orm/contextual.html, https://github.com/mitsuhiko/flask-sqlalchemy/issues/99 and http://flask.pocoo.org/docs/0.12/reqcontext/#callbacks-and-errors

I ended up with the following, expiring the session and removing it after each request.

Keep in mind I'm not using threading, just gunicorn with two processes.

@app.teardown_request
def teardown_request(*args, **kwargs):
    'Expire and remove the session after each request'

    from models import db
    db.session.expire_all()
    db.session.remove()

where db is my SQLAlchemy object in Flask.

I'm not sure why it isn't the default but it is working.

raju249 commented 4 years ago

How do we make it work with just SQLAlchemy and not Flask SQLAlchemy?

DazEdword commented 4 years ago

I'm encountering this issue, but only on my production environment with dockerised Flask + UWSGI + Nginx, using sqlalchemy declarative (NOT flask-sqlalchemy). Would appreciate to hear any suggestions.

killthekitten commented 3 years ago

@raju249 if you are using the application factory pattern, you could put that in the factory function. Check out how it is done by flask-sqlalchemy for inspiration.

foskamon commented 2 years ago

This is happening only when using gunicorn but the solution from @rhymes above didn't work for me. Using flask, flask-admin, flask-sqlalchemy and sqlalchemy.

JonathanBrenner commented 1 year ago

Ran into this today and @rhymes fix worked. flask==2.2.2 flask-admin==1.6.0 flask-sqlalchemy==2.5.1 sqlalchemy==1.4.41