Search code examples
pythonmysqlflaskflask-sqlalchemyflask-admin

flask: Records are not updated immeditely


I have very simple application in which anonymous user post suggestion and moderator specify the status of the received suggestions (Status's are :0,1,2,3).

I'm using Flask-Admin for moderator with customized list-view ( i have added 4 buttons for each status)

from flask import Flask,request,url_for,redirect
from Admin.Admin import  admin,init_login
from Model import db,suggestion,User
import geoip2.webservice

app = Flask(__name__)
app.config.from_pyfile('Config.cfg')
db.init_app(app)
app.config['SQLALCHEMY_POOL_SIZE'] = 100
app.config['SQLALCHEMY_POOL_RECYCLE'] = 100



init_login(app)
admin.init_app(app)
IPclient = geoip2.webservice.Client("XXX")

def UpdateRecord(ID,status):
            try:
                    Record = suggestion.query.filter_by(id=ID).first()
                    Record.Flag=status
                    db.session.commit()
            except Exception, r:
                    raise r
                    #db.session.flush()
                    #Record = suggestion.query.filter_by(id=id).first_or_404()
                    #Record.Flag=1
                    #db.session.commit()


@app.route('/')
def index():

    return redirect("sometime ... ")



@app.route("/XXXX/Favorite/<int:id>")
def favorite(id):
    UpdateRecord(id,1)
    return redirect(url_for("admin.index")+"Favsuggestion")



@app.route("/XXXX/Archive/<int:id>")
def archive(id):
    UpdateRecord(id,2)
    return redirect(url_for("admin.index")+"Arcsuggestion")



@app.route("/WSC/Published/<int:id>")
def published(id):
    UpdateRecord(id,3)
    return redirect(url_for("admin.index")+"Pubsuggestion")


@app.route("/suggest",methods=["GET","POST"])
def suggest():
    try:
        db.session.flush()
        suggestionString=request.form.get('suggestionString')
        IpAddress=request.remote_addr
        IPresponse = IPclient.city(IpAddress)

        Country=IPresponse.country.name
        City=IPresponse.city.name
        if len(suggestionString)>0:
            suggestRecord = suggestion(suggestionString,Country,City,IpAddress)
            db.session.add(suggestRecord)
            db.session.commit()
    except Exception,e:return str(e)
    return redirect("http://site/thankyou")





@app.teardown_appcontext
def shutdown_session(response_or_exc):
    try: 
        if response_or_exc is None:
            db.session.commit()
    finally:
        db.session.remove()
    return response_or_exc

here's my configuration :

# -*- coding: utf-8 -*-
#NOTE:Replace bands with DB name
DEBUG = False
SECRET_KEY='key'
SQLALCHEMY_DATABASE_URI='mysql://user:pass@localhost/sugeestion?charset=utf8'

the problem is that when moderator change suggestion status by clicking button the page reload but status doesn't change after few seconds i refresh then suggestion status will be changed

Update - 2 may 2016: i have checked the log and i found 2 errors happening related to DB

OperationalError: (_mysql_exceptions.OperationalError) (2006, 'MySQL server has gone away') [SQL: u'SELECT `User`.id AS `User_id`, `User`.`Username` AS `User_Username`, `User`.`Password` AS `User_Password`, `User`.`Permission` AS `User_Permission` \\nFROM `User` \\nWHERE `User`.id = %s'] [parameters: (1,)], referer: http://TheWebSite

and

StatementError: (sqlalchemy.exc.InvalidRequestError) Can't reconnect until invalid transaction is rolled back [SQL: u'SELECT count(%s) AS count_1 \\nFROM `suggestion` \\nWHERE `suggestion`.`Flag` = %s'] [parameters: [immutabledict({})]], referer: http://TheWebSite

Solution

  • well ,

    for data consistency:

    we hired consultant and i turned to be that we need to add db.commit() at the beginning of get_query in each customized admin ModelView class which we didn't suspect at all .

    for the error we still didn't fixed it yet , we are playing with the parameters but nothing worked so far.