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:

https://img-c.udemycdn.com/redactor/raw/2020-10-20_14-31-27-cced49e2e6f0ccf6aed80fdce0619e40.gif

528. 要求 1 - 註冊新使用者

1.使用您昨天學到的知識,允許使用者轉到路線以註冊您的博客網站。您應該在名為 forms.py 中創建 WTForm,並使用 Flask-Bootstrap 來呈現 wtf quick_form。/register RegisterForm

使用者輸入的數據應用於在您的博客中創建新條目.db在表格中。User

這就是您的目標:

https://img-c.udemycdn.com/redactor/raw/2020-10-20_16-04-49-0d6d659583961ce79995cac2d8251fcb.gif

提示 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)

529. 要求 2 - 登錄註冊使用者

  1. 已成功註冊(添加到資料庫中的使用者表)的用戶應該能夠前往路由使用其憑據登錄。您需要查看 Flask-Login 文件和昨天的課程才能執行此操作。/login

這是您希望實現的目標:

https://img-c.udemycdn.com/redactor/raw/2020-10-22_10-26-14-a9b88714859da2bc4f06ce0332ca820f.gif