【学习笔记】Flask Web Application简单的登录页面

Flask Web Application

Flask Web Application代码

安装flask环境

pip install flask

pip install flask-login

pip install flask-sqlalchemy

创建项目总文件夹flask web application

子文件夹website

  • 子文件夹static

    • 配置index.js
  function deleteNote(noteId) {
    fetch("/delete-note", {
      method: "POST",
      body: JSON.stringify({ noteId: noteId }),
    }).then((_res) => {
      window.location.href = "/";
    });
  }
  • 子文件夹templates

    • 配置base.html
  
  
    
      
      
      
            
      {% block title %}主页{% endblock %}
    
    
            
      {% with messages = get_flashed_messages(with_categories=true) %} {% if
      messages %} {% for category, message in messages %} {% if category ==
      '错误' %}
      
      {% else %}
      
      {% endif %} {% endfor %} {% endif %} {% endwith %}          
      
{% block content %} {% endblock %}
  • 配置home.html
  {% extends "base.html" %} {% block title %}主页{% endblock %} {% block content
  %}
  
  
  
  

记录内容

    {% for note in user.notes %}
  • {{ note.data }}
  • {% endfor %}

{% endblock %}
  • 配置login.html
  {% extends "base.html" %} {% block title %}登入{% endblock %} {% block content
  %}
  

登入


{% endblock %}
  • 配置sign_up.html
  {% extends "base.html" %} {% block title %}注册{% endblock %} {% block
  content %}
  

注册


{% endblock %}
  • 子文件init.py

    • 配置init.py
  from flask import Flask
  from flask_sqlalchemy import SQLAlchemy
  from os import path
  from flask_login import LoginManager
  
  db = SQLAlchemy()
  DB_NAME = "database.db"     
  
  def create_app():
      app = Flask(__name__)
      app.config['SECRET_KEY'] = 'become a developer'
      app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
      db.init_app(app)    
      from .views import views
      from .author import author          
      app.register_blueprint(views, url_prefix='/')
      app.register_blueprint(author, url_prefix='/')          
      from .models import User, Note          
      create_database(app)        
      login_manager = LoginManager()
      login_manager.login_view = 'author.login'
      login_manager.init_app(app)         
      @login_manager.user_loader
      def load_user(id):
          return User.query.get(int(id))          
      return app      
  
  def create_database(app):
      if not path.exists('website/' + DB_NAME):
          db.create_all(app=app)
          print('成功创建数据库!')
  • 子文件author.py

    • 配置author.py
  from flask import Blueprint, render_template, request, flash, redirect, url_for
  from .models import User
  from werkzeug.security import generate_password_hash, check_password_hash
  from . import db
  from flask_login import login_user, login_required, logout_user, current_user
  
  author = Blueprint('author', __name__)      
  
  @author.route('/login', methods=['GET', 'POST'])
  def login():
      if request.method == 'POST':
          email = request.form.get('email')
          password = request.form.get('password')     
          user = User.query.filter_by(email=email).first()
          if user:
              if check_password_hash(user.password, password):
                  flash('登录成功!', category='成功')
                  login_user(user, remember=True)
                  return redirect(url_for('views.home'))
              else:
                  flash('密码错误,请重试!', category='错误')
          else:
              flash('邮箱不存在!', category='错误')          
      return render_template("login.html", user=current_user)
  
  @author.route('/logout')
  @login_required
  def logout():
      logout_user()
      return redirect(url_for('author.login'))
  
  @author.route('/sign-up', methods=['GET', 'POST'])
  def sign_up():
      if request.method == 'POST':
          email = request.form.get('email')
          first_name = request.form.get('firstName')
          password1 = request.form.get('password1')
          password2 = request.form.get('password2')
  
          user = User.query.filter_by(email=email).first()
          if user:
              flash('邮箱已存在', category='错误')
          elif len(email) < 4:
              flash('邮箱至少包含3个字符.', category='错误')
          elif len(first_name) < 2:
              flash('请输入您的姓名(至少包含1个字符)', category='错误')
          elif password1 != password2:
              flash('密码不匹配', category='错误')
          elif len(password1) < 7:
              flash('请输入至少7位以上的密码.', category='错误')
          else:
              new_user = User(email=email, first_name=first_name, password=generate_password_hash(
                  password1, method='sha256'))
              db.session.add(new_user)
              db.session.commit()
              login_user(new_user, remember=True)
              flash('成功创建账户!', category='成功')
              return redirect(url_for('views.home'))
      
      return render_template("sign_up.html", user=current_user)
  • 子文件models.py

    • 配置models.py
  from . import db
  from flask_login import UserMixin
  from sqlalchemy.sql import func
  
  
  class Note(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      data = db.Column(db.String(10000))
      date = db.Column(db.DateTime(timezone=True), default=func.now())
      user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
  
  
  class User(db.Model, UserMixin):
      id = db.Column(db.Integer, primary_key=True)
      email = db.Column(db.String(150), unique=True)
      password = db.Column(db.String(150))
      first_name = db.Column(db.String(150))
      notes = db.relationship('Note')
  • 子文件views.py

    • 配置views.py
  from flask import Blueprint, render_template, request, flash, jsonify
  from flask_login import login_required, current_user
  from .models import Note
  from . import db
  import json
  
  views = Blueprint('views', __name__)
  
  @views.route('/', methods=['GET', 'POST'])
  @login_required
  def home():
      if request.method == 'POST':
          note = request.form.get('note')
  
          if len(note) < 1:
              flash('请输入内容!', category='错误')
          else:
              new_note = Note(data=note, user_id=current_user.id)
              db.session.add(new_note)
              db.session.commit()
              flash('成功添加记录!', category='成功')
      
      return render_template("home.html", user=current_user)
  
  @views.route('/delete-note', methods=['POST'])
  def delete_note():
      note = json.loads(request.data)
      noteId = note['noteId']
      note = Note.query.get(noteId)
      if note:
          if note.user_id == current_user.id:
              db.session.delete(note)
              db.session.commit()
  
      return jsonify({})
  • 子文件main.py
    • 配置main.py

      from website import create_app   
      app = create_app()   
      if __name__=='__main__':
          app.run(debug=True)
      

运行 python main.py

run_main

访问127.0.0.1:5000

页面展示

login
sign_up
home

你可能感兴趣的:(【学习笔记】Flask Web Application简单的登录页面)