Development of a flask-based web application's user registration function (5): flask User Registration

Source: Internet
Author: User
Tags key string

Development of a flask-based web application's user registration function (5): flask User Registration

The roles are divided into two types: common users and administrator users. At least for common users, direct DB modification is not advisable and user registration is required, start the development of user registration.

User table

First, you need to determine what information you need to provide during user registration: User Name, password, nickname, email address, birthday, gender, and self-introduction. The following describes how to modify the user model based on the information:

class User(db.Model): __tablename__="users" id=db.Column(db.Integer,primary_key=True) username=db.Column(db.String(50),unique=True,index=True) password=db.Column(db.String(50)) nickname=db.Column(db.String(50)) email=db.Column(db.String(100)) birthday=db.Column(db.DateTime) gender=db.Column(db.Integer) remark=db.Column(db.String(200)) role_id=db.Column(db.Integer,db.ForeignKey("roles.id"))

Then use the script to modify the database

Python default. py db migrate-m "Modify user table"

After you press enter, the page displays the following content:

Then change the db difference

python default.py db upgrade

The table structure in the database is as follows:

Modified successfully

Registration page

Create a new register.html template and set the logon form:

{% Extends "base.html" % }{% block content %} <! -- Specific content --> <div class = "container"> <div class = "row"> </div> <div class = "row"> <div class = "page-header"> 

Add the register route in the default. py file. The Code is as follows:

@app.route("/register",methods=["GET"])def register(): return render_template("/register.html")

Run the interface normally, and then add the post route:

@ App. route ("/register", methods = ["Post"]) def registerPost (): user = User (); user. username = request. form. get ("username", "") user. password = request. form. get ("password", "") user. birthday = request. form. get ("birthday", "") user. email = request. form. get ("email", "") user. gender = request. form. get ("gender", "") user. nickname = request. form. get ("nickname", "") user. role_id = 1 # tentatively set the public user role to 1 # judgment, where the username, password, nickname cannot be blank if (len (user. username. strip () = 0): flash ("the user name cannot be blank") return render_template ("/register.html") if (len (user. password. strip () = 0): flash ("user password cannot be blank") return render_template ("/register.html") if (len (user. nickname. strip () = 0): flash ("user nickname cannot be blank") return render_template ("/register.html") db. session. add (user); flash ("You have registered successfully") return render_template ("/register.html ")

The Code is a bit wordy and not beautiful, but the basic intent can be clearly expressed and the function can be implemented. But now the problem arises. To add a new field, you need to modify three pieces of code (html, form. get, validation), and especially html needs to be modified, and the html part is not verified. If Client verification is added, more needs to be modified. Is there any form-based optimization tool? The answer is, of course, it's the turn of wtf.

Introduce WTF form framework

As before, install the plug-in first.

pip3.6 install flask-wtf

Then introduce the required package

from flask.ext.wtf import Formfrom wtforms import StringField,PasswordField,SubmitField,RadioFieldfrom wtforms.validators import DataRequired,EqualTo,Length

Create a RegisterForm below:

Class RegisterForm (Form): username = StringField ("Enter the user name", validators = [DataRequired ()]) password = PasswordField ("enter the password ", validators = [DataRequired ()]) repassword = PasswordField ("Confirm password", validators = [login to ("password")]) nickname = StringField ("nickname ") birthday = DateField ("Date of Birth") email = StringField ("Email address", validators = [email ()]) gender = RadioField ("gender ", choices = [("0", "male"), ("1", "female")], default = 0) remark = TextAreaField ("self-introduction ") submit = SubmitField ("submit ")

Modify the register.html template:

{% Extends "base.html" % }{% block content %} <! -- Specific content -- >{% import "bootstrap/wtf.html" as wtf %} <! -- Import the bootstrap template --> <div class = "container"> <div class = "row"> </div> <div class = "row"> <div class = "page-header"> 

Execution, output result:

Leo, an error is reported to see what the output is:

Note that the red line is a CSRF error. The concept of CSRF can be directly Baidu. If you know the problem, it is actually well modified. Adding a key in the framework can effectively prevent it, in default. add a row in py:

app.config['SECRET_KEY'] = "Niu_blog String"

Key string customizable

Run the command again and the page appears:

The verification style of the validation bootstrap is included, and the default. py registration function is completed.

@ App. route ("/register", methods = ["GET", "POST"]) def register (): form = RegisterForm () if form. validate_on_submit (): user = User () user. username = form. username. data user. password = form. password. data user. birthday = form. birthday. data user. email = form. email. data user. gender = form. gender. data user. nickname = form. nickname. data user. role_id = 1 # tentatively set the public user role to 1 db. session. add (user) return render_template ("/register.html", form = form)

Note that the registerPost method has been deleted.

Run the test.

Click to submit:

Leo, why is the date format incorrect? This should be viewed from the source code:

class DateField(DateTimeField): """ Same as DateTimeField, except stores a `datetime.date`. """ def __init__(self, label=None, validators=None, format='%Y-%m-%d', **kwargs):  super(DateField, self).__init__(label, validators, format, **kwargs) def process_formdata(self, valuelist):  if valuelist:   date_str = ' '.join(valuelist)   try:    self.data = datetime.datetime.strptime(date_str, self.format).date()   except ValueError:    self.data = None    raise ValueError(self.gettext('Not a valid date value'))

This is the source code of the wtforms field, which is located in/wtforms/fields/core. line 745 of py, you can see that the supported date format is in the year-month-day format, the format is too limited, and the text box does not use the html5 date but the common text, after the solution, modify the input to and click Submit:


Note: Because the code is still returned to this page after the submission is successful and the content is injected, there is no problem with the display. Check the database:

The record enters the database normally, and the function is completed.

Improve logon page

Next we will transform the logon page to create a logon form:

Class LoginForm (Form): username = StringField ("Enter the user name", validators = [DataRequired ()]) password = PasswordField ("enter the password ") submit = SubmitField ("login ")

Modify logon template page:

{% Extends "base.html" % }{% import "bootstrap/wtf.html" as wtf % }{% block content %} <! -- Specific content --> <div class = "container"> <div class = "row"> </div> <div class = "row"> <div class = "col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 "> <div class =" page-header "> 

Route modification method:

@ App. route ("/login", methods = ["GET", "POST"]) def login (): form = LoginForm () if form. validate_on_submit (): username = form. username. data password = form. password. data user = User. query. filter_by (username = username, password = password ). first () if user is not None: session ["user"] = username return render_template ("/index.html", name = username, site_name = 'myblog ') else: flash ("the user name or password you entered is incorrect") return render_template ("/login.html", form = form) # return is still the logon page return render_template ("/login.html ", form = form)

Restart the service, run the program, enter zhangji and 123, and then log on to the homepage

Back to homepage

There is nothing on the homepage, and a normal loose blog should display the post sending button and articles after logging on, but first record the logon status, these will be described in the next chapter.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.