This place used a blueprint, because of the use of plant function must be registered to use the blueprint for the route in app
Data acquisition front-end for JSON, when the return is also a json information
auth.py
import functools from flask import ( Blueprint, g, jsonify, request, session ) from werkzeug.security import check_password_hash, generate_password_hash from app.db import get_db bp = Blueprint('auth', __name__, url_prefix='/auth') @bp.route('/register', methods=('GET', 'POST')) def register(): if request.method == 'POST': stu_id = request.json['stu_id'] username = request.json['username'] password = request.json['password'] db = get_db() error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif db.execute( 'SELECT stu_id FROM user WHERE username = ?', (username,) ).fetchone() is not None: error = 'User {} is already registered.'.format(username) return jsonify({'msg': 'error'}) if error is None: db.execute( 'INSERT INTO user (stu_id,username, password) VALUES (?, ?, ?)', (stu_id, username, generate_password_hash(password)) ) db.commit() return jsonify({'msg': 'Register success.'}) return jsonify({'msg': None}) @bp.route('/login', methods=('GET', 'POST')) def login(): if request.method == 'POST': stu_id = request.json['stu_id'] password = request.json['password'] db = get_db() error = None user = db.execute( 'SELECT * FROM user WHERE stu_id = ?', (stu_id,) ).fetchone() if user is None: error = 'Incorrect stu_id.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' return jsonify({'err': 'login failed'}) if error is None: session.clear() session['username'] = user['username'] return jsonify({'msg': 'login success.'}) return jsonify({'msg': None}) @bp.before_app_request def load_logged_in_user(): stu_id = session.get('stu_id') if stu_id is None: g.user = None else: g.user = get_db().execute( 'SELECT * FROM user WHERE stu_id = ?', (stu_id,) ).fetchone() @bp.route('/logout') def logout(): session.clear() return jsonify({'msg': 'logout success'})
Log in here to complete the registration, the learning process will be recorded later harvest