简体   繁体   中英

How store a base64 image into user session in Flask

Good day. I'm starting with Flask in Python. Everything goes fine, but I have a problem with the session. The idea is to store the base64 avatar of the user into his session after he logged in. Then, in the layout just access to his avatar by <img src="data:image/png;base64,{{session.user.photo}}" /> .

The problem comes when I login, put the base64 into the session and redirect to /home . Inside /home route, I have a simple access control, if the session hasn't user key, redirect to login again . The problem is after set the session and redirect to home, the session is empty in /home, and never render the template.

@root.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        if 'user' in session:
            return redirect('/home')
        else:
            return render_template('login.html', message = None)
    else:
        username = request.form['username']
        pwd = request.form['password']
        user = User.where('username', username).where('pwd', pwd).get().first()
        if(user == None):
            return render_template('login.html', message = 'Usuario o contraseña incorrecta')
        else:
            session['user'] = {
                'id': user.id,
                'username': user.username,
                'photo': user.photo
            }
            return redirect('/home')

@root.route('/home')
def home():
    if 'user' in session: # THIS IS FALSE, SESSION IS EMPTY
        return render_template('home.html')
    else:
        return redirect(url_for('root.login', message = None))

Flask only accept small data in session? thanks.

I am sorry you shouldn't store a big image in the session.

A good way to achieve it is to store unique image id, and call url with this unique ID. Like this:

<img src = "//myview?id=513654534343543543" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM