Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

头像更换问题 #6

Closed
Hayabusa177 opened this issue Jan 27, 2023 · 2 comments
Closed

头像更换问题 #6

Hayabusa177 opened this issue Jan 27, 2023 · 2 comments

Comments

@Hayabusa177
Copy link

问题描述:
每次更换头像后都需要清空游览器缓存后才能显示新头像。我认为是:每次游览器请求的头像Url都是同样的,因此游览器会将其视为同样的资源,会优先从缓存中读取它

修复建议
将请求头像的Url去重化,每个请求都附上唯一的id,以防止游览器从缓存中读取资源。

@WeepingDogel
Copy link
Owner

解决方案

  1. 先创建独立的头像表
CREATE TABLE AVATARS(
    ID INTEGER PRIMARY KEY AUTOINCREMENT,
    UserName TEXT UNIQUE NOT NULL,
    Avatar TEXT NOT NULL
);
  1. 生成头像UUID
avataruUUID = str(uuid.uuid4())
  1. 注册时将默认头像转换为 UUID + 扩展名,并写入头像表
db.execute("INSERT INTO AVATARS(UserName, Avatar) VALUES(?,?)",(userName, avataruUUID + ".jpg"))
db.commit()
  1. 上传新头像时,将文件命名为 UUID + 扩展名,并删除原有的文件以便于替换,并修改数据库条目:
@bp.route("/avatar", methods=('POST','GET'))
def avatar():
    if request.method == "POST":
        UserName = session['username']
        avatarUUID = str(uuid.uuid4())
        db = get_db()
        f = request.files['file']
        extFileName = os.path.splitext(f.filename)[-1]
        if f.filename == '':
            return redirect(url_for('profile'))
        else:
            os.system("rm -rfv " + os.path.join(current_app.config['USERFILE_DIR'],session['username'] + "/*.jpg"))
            os.system("rm -rfv " + os.path.join(current_app.config['USERFILE_DIR'],session['username'] + "/*.png"))
            f.save(os.path.join(current_app.config['USERFILE_DIR'],session['username'] + "/" + avatarUUID + extFileName))
            db.execute(
                'UPDATE AVATARS SET Avatar = ? WHERE UserName = ?',
                (avatarUUID + extFileName, UserName,)
            )
            db.commit()
            return redirect(url_for('profile'))

@WeepingDogel
Copy link
Owner

Fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants