python类db()的实例源码

views.py 文件源码 项目:Pycourses 作者: billz96 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def update_profile():
    username = loggedIn(session, LoggedIn)
    if username == False:
        form = LoginForm()
        return render_template('login.html', form=form)

    # AddSkillsForm, EditSkillsForm, EditAvatarForm, EditFullNameForm
    a_skills = AddSkillsForm()
    e_skills = EditSkillsForm()
    e_avatar = EditAvatarForm()
    e_flname = EditFullNameForm()
    e_descr = EditDescription()
    a_descr = AddDescription()

    form = EditProfileForm()
    if form.validate_on_submit():
        # find user by username and his/her profile by his/her id
        user = User.query.filter_by(username=username).first()
        user_profile = Profile.query.filter_by(user_id=user.id).first()

        # update current user's profile data
        user_profile.name = request.form['name']
        user_profile.surname = request.form['surname']
        user_profile.description = request.form['description']
        user_profile.skills = request.form['skills']

        # update avatar
        avatar = form.avatar.data
        filename = secure_filename(avatar.filename) # maybe it's optional because i change the filename

        rand_ID = str(randId())
        while True:
            result = Profile.query.filter_by(avatar=rand_ID).first()
            if result:
                rand_ID = str(randId())
            else:
                break

        filename = ''+rand_ID+'.jpg'
        target = path.join(APP_ROOT, 'static/avatars/') # target = project's path + /static/avatars
        if not path.isdir(target): # if target doesn't exist
            mkdir(target) # we create the target

        old_path = path.join(target, user_profile.avatar)
        new_path = path.join(target, filename)

        if user_profile.avatar != "saitama-batman.jpg":
            remove(old_path)

        avatar.save(new_path) # save the file in the target
        user_profile.avatar = filename

        # save changes in profile table
        db.session.commit()
        user_skills = user_profile.skills.split(',')
        return render_template('profile.html', username=username, user_profile=user_profile, user_skills=user_skills)

    return render_template('edit_profile.html', form=form, a_skills=a_skills, e_skills=e_skills, e_avatar=e_avatar, e_flname=e_flname, e_descr=e_descr, a_descr=a_descr)


问题


面经


文章

微信
公众号

扫码关注公众号