flask theme - novel website development III (registration, login)

Keywords: Database Session MySQL

The previous several articles have prepared the database and data, and now they will be developed later. Some of them may be different from others on the Internet. I did it for the first time, and all the functions have been realized. This article is about development, registration and login. First, paste the style

Front end

  • Sign in:
  • Registration:

    The front end style is shown in the figure above
  • Registration operation: the user enters the nickname, account number, password and confirm password. After confirmation, the front-end data is transferred to the background for verification. The nickname cannot exceed 10 Chinese characters. The account number is composed of pure numbers, the password cannot exceed 8 digits, the account number is unique, and the nickname is not unique.
  • Login operation: the user enters the account password, and the background verifies whether the password corresponding to the account is consistent. If the password is inconsistent, flash flash the flash message to deliver the prompt message.
Front end specific code:

New base.html as template

  • base.html
<!-- Template page, site icon, menu bar and sidebar are all defined here -->
{% extends "bootstrap/base.html" %}
<!-- Website title -->
{% block title %}{{ super() }} {% endblock %}
<!-- head -->
{% block head %}
<!-- Inherited parent class -->
{{ super() }}
<!-- Website icon, picture in static/images Under folder -->
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}"
    type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}"
    type="image/x-icon">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
{% endblock %}
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}
{% block navbar %}
{% endblock %}
<!-- Inherit other page content -->
{% block content %}
{{ super() }}
{% endblock %}

New reg.html bit registration page front end

  • reg.html
{% block head %}

<!-- Registration page -->
{% endblock %}
<link rel="stylesheet" href="/static/bootstrap.min.css"/>
{% block content %}
<html>
<body style="background-image: url('/static/images/5f7be1393c54b2920ce2677e08524d8e.jpg')">
<div class="container" style=" text-align: center; background-color: #CCCCCC; width: 500px; height: 390px;margin-top: 180px; opacity: 90%; border-radius:20px;" >
<form method="post" action="/reg" class="form" style="padding-top: 20px">
  <label style="font-size: 28px; color: #CCFFFF;">Welcome to register Angel literature</label>
    <label style="font-size: 20px; color: #FFFF99;">Professional book navigation</label><hr>
  <label style="height: 2px;">&nbsp;</label><br>
    <label style="font-size: 16px; color: #0000FF;font-family: STHeiti">Input nickname&nbsp;&nbsp;</label>
  <input type="text" name="usn" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="No more than 10 Chinese characters"><br>
   <label style="height: 10px;">&nbsp;</label><br>
  <label style="font-size: 16px; color: #0000FF;font-family: STHeiti">Input account&nbsp;&nbsp;</label>
  <input type="text" name="account" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="Pure digital composition"><br>
  <label style="height: 10px;">&nbsp;</label><br>
  <label style="font-size: 16px; color: #0000FF; font-family: STHeiti">Input password&nbsp;&nbsp;</label>
  <input type="password" name="pwd" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="No more than 8 digits"><br>
  <label style="height: 10px;">&nbsp;</label><br>
  <label style="font-size: 16px; color: #0000FF; font-family: STHeiti">Confirm password&nbsp;&nbsp;</label>
  <input type="password" name="pwd2" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="Confirm your password"><br>
  <label style="height: 2px;">&nbsp;</label><hr>
    <label style="font-family: KaiTi; color: #985f0d; font-size: 15px; ">Existing account please&nbsp;</label>
  <label style="font-size: 16px; color: #FF3300; padding-right: 50px"><a href="/login">Sign in</a></label>
  <input type="submit" value="register" style="width: 100px; text-align: center;" class="btn btn-primary">
  <!-- Backstage flash Return information of function -->
  {% for message in get_flashed_messages() %}
        {{ message }}
  {% endfor %}
</form>
</div>
</body>
</html>
{% endblock %}

New login.html login page
login.html

{% block head %}
{% endblock %}
<link rel="stylesheet" href="/static/bootstrap.min.css"/>
{% block content %}
<html>
<body style="background-image: url('/static/images/5f7be1393c54b2920ce2677e08524d8e.jpg')">
<div class="container" style=" text-align: center; background-color: #CCCCFF; width: 500px; height: 350px;margin-top: 200px; opacity: 90%; border-radius:20px;" >
<form method="post" action="/login" class="form" style="padding-top: 30px">
  <label style="font-size: 28px; color: #CCFFFF;">Welcome to login Angel literature</label>
    <label style="font-size: 20px; color: #FFFF99;">Professional book navigation</label><hr>
  <label>&nbsp;</label><br>
  <label style="font-size: 16px; color: #0000FF;font-family: STHeiti">Account number&nbsp;&nbsp;</label>
  <input type="text" name="account" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="Enter your account"><br>
  <label>&nbsp;</label><br>
  <label style="font-size: 16px; color: #0000FF; font-family: STHeiti">Password&nbsp;&nbsp;</label>
  <input type="password" name="pwd" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="Enter your password"><br>
  <label style="padding-top: 5px;">&nbsp;
      {% for message in get_flashed_messages() %}
        {{ message }}
  {% endfor %}
  </label><br><hr>
    <label style="font-family: KaiTi; color: #985f0d; font-size: 15px; ">No account please&nbsp;</label>
  <label style="font-size: 16px; color: #FF3300; padding-right: 50px; "><a href="/reg">register</a></label>
  <input type="submit" value="Sign in" style="width: 100px; text-align: center;" class="btn btn-primary">
</form>
</div>
</body>
</html>
{% endblock %}

This line of code is to receive the flash message from the back end and display it to the set position
{% for message in get_flashed_messages() %} {{ message }} {% endfor %}

back-end

First, define each table, realize database connection, use Sqlalchemy to manage the database, and first import Sqlalchemy
from flask_sqlalchemy import SQLAlchemy
If the import fails, you need to install it first
pip install flask-sqlalchemy
Configure after importing. Instantiate the object db = SQLAlchemy(app) first
Define the configuration method in flash and import it into the instance

class Config(object):
    SQLALCHEMY_DATABASE_URI = "mysql://book:book@localhost:3306/book"
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SECRET_KEY = 'bvksdcjavcvavskbaleb'
    SQLALCHEMY_POOL_SIZE = 10
    SQLALCHEMY_POOL_TIMEOUT = 10

Interpretation:

  • 1. Connect to database configuration, database MySQL: / / user name: password @ host host ip: 3306 port number / database name
  • 2. Whether to adjust according to the changes of the database
  • 3. Input the exchange code at will, and use the query operation
  • 4. Controls the number of connections that can be created after the connection pool reaches its maximum. When these extra connections are recycled to the connection pool, they will be disconnected and discarded.
  • 5. Timeout
    Load the configuration method to app.config.from object (config) in the instance app
Define user table:
class Users(db.Model):
    #Table name
    __tablename__ = 'user'
    id = db.Column(db.Integer,autoincrement=True,primary_key=True)
    #User name
    username = db.Column(db.String(50), default='The Yi River is so cold.')
    #User account
    account = db.Column(db.Integer, unique=True, nullable=False)
    #User password
    password = db.Column(db.String(50), nullable=False)
    perference = db.Column(db.String(50), nullable=True)
    major = db.Column(db.String(50), nullable=True)

Define login route and view functions:
Login, "/" is the login interface by default for entering the website, and methods is the request method for routing. GET is the default,
The request.method returns the request mode of this request. The session method is used to save user information, which is displayed on other pages. The function of the sentence user = Users.query.filter(Users.account == account, Users.password == password).first() is to query whether the account and password are consistent in the database

@app.route('/')
@app.route("/login", methods=["POST", "GET"])
def login():
    # If the request mode is POST, it has been set to POST mode in the front end
    if request.method == 'POST':
        # Get the value from the front end, including user name and password
        account = request.form.get('account')
        password = request.form.get('pwd')
        # Check whether the user exists in the user table, save the user name and password and pass them to the front end, and there is no flash prompt error message
        user = Users.query.filter(Users.account == account, Users.password == password).first()
        if user:
            username = Users.query.filter(Users.account == account, Users.password == password).first()
            session['account'] = account
            session['password'] = password
            session['username'] = username.username
            session['user_id'] = username.id
            print('User login--', username.username)
            # Extend save time
            # session.permanent = True
            # Correct account and password, redirect to home page
            return redirect(url_for("index"))
        else:
            flash("Incorrect account or password!")
    else:
        return render_template("login.html")
    return render_template("login.html")

Define the registration route and view functions:
reg, to judge and control the format of front-end data

@app.route("/reg", methods=["POST", "GET"])
def reg():
    if request.method == 'POST':
        username = request.form.get('usn')
        account = request.form.get('account')
        password = request.form.get('pwd')
        password2 = request.form.get('pwd2')
        print('User registration--', username)
        if password != password2:
            flash("The two passwords are inconsistent")
        elif len(password) > 8:
            flash("The password is too long.")
        elif len(str(username)) > 10:
            flash("Nickname too long")
        elif Users.query.filter(Users.account==account).first():
            flash("Account has been registered")
        elif str(account).isdigit():
            new_user = Users(username=username, account=account, password=password, id=None)
            db.session.add(new_user)
            db.session.commit()
            return redirect(url_for("login"))
        else:
            flash("Account number is composed of pure numbers")
    else:
        return render_template("reg.html")
    return render_template("reg.html")

OK, the above is the operation related to registration and login. If there is something wrong, please correct it

Published 4 original articles, won praise 4, visited 28
Private letter follow

Posted by diex on Sat, 22 Feb 2020 01:25:49 -0800