以下是Python Flask框架实现用户个人资料和头像的教程攻略,分为两部分:
- 用户个人资料的实现
1.1 创建用户资料模型
首先,我们需要在数据库中创建一个用户资料模型(model),用来存储用户个人信息。模型主要包括以下几个字段:用户名、电子邮箱、密码、性别、生日等等。具体实现可参考以下代码:
from flask_login import UserMixin
from datetime import datetime
from your_app_name import db, login_manager
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
gender = db.Column(db.String(6))
birthday = db.Column(db.DateTime, default=datetime.utcnow)
avatar = db.Column(db.String(20), nullable=False, default='default.jpg')
1.2 创建用户资料表单
接下来,我们需要为用户资料创建一个表单,这个表单主要包含用户资料的各项数据。用户可以通过这个表单进行修改和更新个人资料。具体实现可参考以下代码:
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, DateField, TextAreaField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from flask_login import current_user
from your_app_name.models import User
class UpdateAccountForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email', validators=[DataRequired(), Email()])
gender = SelectField('Gender', choices=[('Male', 'Male'), ('Female', 'Female')])
birthday = DateField('Birthday')
picture = FileField('Update Profile Picture', validators=[FileAllowed(['jpg', 'png'])])
submit = SubmitField('Update')
def validate_username(self, username):
if username.data != current_user.username:
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('That username is taken. Please choose a different one.')
def validate_email(self, email):
if email.data != current_user.email:
user = User.query.filter_by(email=email.data).first()
if user:
raise ValidationError('That email is taken. Please choose a different one.')
1.3 创建用户资料视图
最后,我们需要为用户资料创建一个视图(view),让用户能够在网页上查看和修改自己的个人信息。具体实现可参考以下代码:
from flask import render_template, url_for, flash, redirect, request
from flask_login import login_required, current_user
from your_app_name import app, db, bcrypt
from your_app_name.forms import UpdateAccountForm
from your_app_name.models import User
@app.route('/account', methods=['GET', 'POST'])
@login_required
def account():
form = UpdateAccountForm()
if form.validate_on_submit():
if form.picture.data:
picture_file = save_picture(form.picture.data)
current_user.avatar = picture_file
current_user.username = form.username.data
current_user.email = form.email.data
current_user.gender = form.gender.data
current_user.birthday = form.birthday.data
db.session.commit()
flash('Your account has been updated!', 'success')
return redirect(url_for('account'))
elif request.method == 'GET':
form.username.data = current_user.username
form.email.data = current_user.email
form.gender.data = current_user.gender
form.birthday.data = current_user.birthday
image_file = url_for('static', filename='profile_pics/' + current_user.avatar)
return render_template('account.html', title='Account',
image_file=image_file, form=form)
- 用户头像的实现
2.1 保存用户头像
用户头像(avatar)一般是以图片的形式呈现,因此我们需要一个保存用户头像的功能,以保证用户更新或上传头像后,程序能够正常保存并显示最新的头像。
import os
import secrets
from PIL import Image
from flask import current_app
def save_picture(form_picture):
random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_picture.filename)
picture_filename = random_hex + f_ext
picture_path = os.path.join(current_app.root_path, 'static/profile_pics', picture_filename)
output_size = (125, 125)
i = Image.open(form_picture)
i.thumbnail(output_size)
i.save(picture_path)
return picture_filename
2.2 修改用户资料表单
用户头像的上传和更新是通过表单实现的,因此我们需要在UpdateAccountForm中添加picture字段:
class UpdateAccountForm(FlaskForm):
# ...
picture = FileField('Update Profile Picture', validators=[FileAllowed(['jpg', 'png'])])
submit = SubmitField('Update')
2.3 修改用户资料视图
最后,在account视图中添加保存用户头像的逻辑和显示头像的代码:
from your_app_name.utils import save_picture
# ...
@app.route('/account', methods=['GET', 'POST'])
@login_required
def account():
form = UpdateAccountForm()
if form.validate_on_submit():
if form.picture.data:
picture_file = save_picture(form.picture.data)
current_user.avatar = picture_file
# ...
image_file = url_for('static', filename='profile_pics/' + current_user.avatar)
return render_template('account.html', title='Account',
image_file=image_file, form=form)
至此,Python Flask框架实现用户个人资料和头像的教程攻略就结束了。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python的Flask框架中实现登录用户的个人资料和头像的教程 - Python技术站