Search code examples
pythonflaskflask-sqlalchemyflask-mysql

Takes last 20 record and show last register


So i have a problem and i dont know how to look for him.

@app.route('/',methods=['GET', 'POST'])
def index():
    if current_user.is_authenticated:
        current_user.update_on = datetime.utcnow()
        db.session.add(current_user)
        db.session.commit()
    username = db.session.query(User.username,User.avatar).order_by(User.username,User.avatar).limit(20).all()
    nicks = [x[0]for x in username]
    base = 'http://localhost:5000/profil'
    urls = ['{}/{}'.format(base,n)for n in nicks]
    return render_template("index.html",user = username,urls=urls,nicks=nicks)

This is my code in app.py, so i want takes last 20 records from mysql, and show last records in html. Last register user will be first showed, and prelast was be second... but in html show me random Users.
My HTML file:

<a href="{{urls[0] }}"><img class="img-responsive" src="{{url_for('static',filename='upload/'+ user[0].avatar|resize('40x40'))}}" alt="{{nicks[0]}}"></a>
        <a href="{{urls[1] }}"><img class="img-responsive" src="{{url_for('static',filename='upload/'+ user[1].avatar|resize('40x40'))}}" alt="{{nicks[1]}}"></a>
        <a href="{{urls[2] }}"><img class="img-responsive" src="{{url_for('static',filename='upload/'+ user[2].avatar|resize('40x40'))}}" alt="{{nicks[2]}}"></a>

I dont know how repair this error, someone can help me ? or just give me a tips ? Im was start learning programming in last week

And another problem i have with sqlalchemy.exc.OperationalError (2013, 'Lost connection to MySQL server during query') its to fast end connect, like 2min and see a error

DATABASE_URI = 'mysql://{}:{}@{}:{}/kamilos98'.format(config['user'], config['password'],config['host'], config['port'])
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

Solution

  • This:

    username = db.session.query( \
        User.username,User.avatar).order_by(User.username,User.avatar).limit(20).all()
    

    Orders by user name and avatar. Change it to:

    username = db.session.query( \
        User.username,User.avatar).order_by(User.update_on.desc(),User.username).limit(20).all()
    

    to order them by the last update time instead.