Wouldn't it be great if we could have some users on our blog? What if we could let anyone sign up and comment on our blog posts? In order for that to work, we would need to add authentication to our blog. This will be the final step in our Blog Capstone Project. Once we're done, it will be a fully-fledged blog website that you can publish and launch.
This is what you'll make by the end of today:
1.使用您昨天學到的知識,允許使用者轉到路線以註冊您的博客網站。您應該在名為 forms.py 中創建 WTForm,並使用 Flask-Bootstrap 來呈現 wtf quick_form。/register RegisterForm
使用者輸入的數據應用於在您的博客中創建新條目.db在表格中。User
這就是您的目標:
提示 1:您無需更改寄存器中的任何內容.html
提示2:不要擔心Flask-Login,你只是在資料庫中創建一個新使用者。我們將在下一步中登錄它們。
forms.py
class RegisterForm(FlaskForm):
name = StringField("Name", validators=[DataRequired()])
email = StringField(label = 'Email', validators=[DataRequired(), Email()])
password = PasswordField(label = 'Password', validators=[DataRequired()])
submit = SubmitField(label = 'Sign me up!')
main.py
class Users(UserMixin, db.Model):
__tablename__ = "blog_users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(1000))
def __init__(self, email, name, password):
"""初始化"""
self.email = email
self.name = name
self.password = generate_password_hash(password)
print(self.password)
def check_password(self, password):
"""檢查使用者密碼"""
print(check_password_hash(self.password, password))
return check_password_hash(self.password, password)
@app.route('/register', methods=["GET", "POST"])
def register():
form = RegisterForm()
if form.validate_on_submit():
new_user = Users(
name = form.name.data,
email = form.email.data,
password = form.password.data,
)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('get_all_posts'))
return render_template("register.html", form=form)
/login
這是您希望實現的目標: