flask专题-小说网站开发三(注册,登录)

前面几篇准备好了数据库,数据,现在开始往后开发,部分可能与网上他人使用方式不同,本人第一次做,功能都实现了,这一篇开发注册与登录,先贴样式

前端
  • 登录:
    登录
  • 注册:
    注册
    前端样式如上图
  • 注册操作:用户输入昵称,账号,密码和确认密码,确认后将前端数据传递到后台进行验证,昵称不能超过10个汉字,账号由纯数字组成,密码不能超过8位,账号唯一,昵称不唯一。
  • 登录操作:用户输入账号密码,后台验证账号所对应密码是否一致,不一致使用flash消息闪现传递提示消息。
前端具体代码:

新建base.html作为模板

  • base.html
<!-- 模板页面,网站图标,菜单栏和侧边栏都在这儿定义 -->
{% extends "bootstrap/base.html" %}
<!-- 网站标题 -->
{% block title %}{{ super() }} {% endblock %}
<!-- 头部 -->
{% block head %}
<!-- 继承父类 -->
{{ super() }}
<!-- 网站图标,图片在static/images文件夹下 -->
<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 %}
<!-- 继承其他页面内容 -->
{% block content %}
{{ super() }}
{% endblock %}

新建reg.html位注册页面前端

  • reg.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: #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;">欢迎注册Angel文学</label>
    <label style="font-size: 20px; color: #FFFF99;">专业的书籍导航</label><hr>
  <label style="height: 2px;">&nbsp;</label><br>
    <label style="font-size: 16px; color: #0000FF;font-family: STHeiti">输入昵称&nbsp;&nbsp;</label>
  <input type="text" name="usn" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="不超过10个汉字"><br>
   <label style="height: 10px;">&nbsp;</label><br>
  <label style="font-size: 16px; color: #0000FF;font-family: STHeiti">输入账号&nbsp;&nbsp;</label>
  <input type="text" name="account" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="纯数字组成"><br>
  <label style="height: 10px;">&nbsp;</label><br>
  <label style="font-size: 16px; color: #0000FF; font-family: STHeiti">输入密码&nbsp;&nbsp;</label>
  <input type="password" name="pwd" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="不超过8位数"><br>
  <label style="height: 10px;">&nbsp;</label><br>
  <label style="font-size: 16px; color: #0000FF; font-family: STHeiti">确认密码&nbsp;&nbsp;</label>
  <input type="password" name="pwd2" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="确认您的密码"><br>
  <label style="height: 2px;">&nbsp;</label><hr>
    <label style="font-family: KaiTi; color: #985f0d; font-size: 15px; ">已有账号请&nbsp;</label>
  <label style="font-size: 16px; color: #FF3300; padding-right: 50px"><a href="/login">登录</a></label>
  <input type="submit" value="注册" style="width: 100px; text-align: center;" class="btn btn-primary">
  <!-- 后台flash函数的返回信息 -->
  {% for message in get_flashed_messages() %}
        {{ message }}
  {% endfor %}
</form>
</div>
</body>
</html>
{% endblock %}

新建login.html位登录页面
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;">欢迎登录Angel文学</label>
    <label style="font-size: 20px; color: #FFFF99;">专业的书籍导航</label><hr>
  <label>&nbsp;</label><br>
  <label style="font-size: 16px; color: #0000FF;font-family: STHeiti">账号&nbsp;&nbsp;</label>
  <input type="text" name="account" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="输入您的账号"><br>
  <label>&nbsp;</label><br>
  <label style="font-size: 16px; color: #0000FF; font-family: STHeiti">密码&nbsp;&nbsp;</label>
  <input type="password" name="pwd" style="width: 250px; height: 35px; font-family: KaiTi; border-radius:20px; text-align: center;" required placeholder="输入您的密码"><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; ">没有账号请&nbsp;</label>
  <label style="font-size: 16px; color: #FF3300; padding-right: 50px; "><a href="/reg">注册</a></label>
  <input type="submit" value="登录" style="width: 100px; text-align: center;" class="btn btn-primary">
</form>
</div>
</body>
</html>
{% endblock %}

这一行代码为接收后端的闪现消息,并显示到设定位置
{% for message in get_flashed_messages() %} {{ message }} {% endfor %}

后端

先定义各表,实现数据库连接,使用SQLalchemy来管理数据库,先导入sqlalchemy
from flask_sqlalchemy import SQLAlchemy
导入失败的话需要先进行安装
pip install flask-sqlalchemy
导入之后进行配置,先进行实例化对象db = SQLAlchemy(app)
在flask中定义配置方法,导入到实例中

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

解释:

  • 1、连接数据库配置,数据库MySQL://用户名:密码@host主机ip:3306端口号/数据库名称
  • 2、是否跟随数据库的变动进行调整
  • 3、随意输入交换码,查询操作要使用
  • 4、 控制在连接池达到最大值后可以创建的连接数。当这些额外的 连接回收到连接池后将会被断开和抛弃。
  • 5、超时时间
    将配置方法加载到实例app中app.config.from_object(Config)
定义用户表:
class Users(db.Model):
    #表名
    __tablename__ = 'user'
    id = db.Column(db.Integer,autoincrement=True,primary_key=True)
    #用户名
    username = db.Column(db.String(50), default='易水寒')
    #用户账号
    account = db.Column(db.Integer, unique=True, nullable=False)
    #用户密码
    password = db.Column(db.String(50), nullable=False)
    perference = db.Column(db.String(50), nullable=True)
    major = db.Column(db.String(50), nullable=True)

定义登录路由和视图函数:
login,“/”为进入网站默认为登录界面,methods为此路由的请求方式,默认GET,
request.method返回此次请求的请求方式,session方法用来保存用户信息,在其他页面显示,user = Users.query.filter(Users.account == account, Users.password == password).first()这句话的作用为在数据库查询此账号与密码是否一致

@app.route('/')
@app.route("/login", methods=["POST", "GET"])
def login():
    # 如果请求方式为POST,已经在前端设置为POST方式
    if request.method == 'POST':
        # 获取前端传来的值,包括用户名和密码
        account = request.form.get('account')
        password = request.form.get('pwd')
        # 在用户表里查找是否存在此用户,存在保存用户名和密码传递到前端,不存在使用flash提示错误信息
        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('用户登录--', username.username)
            # 延长保存时间
            # session.permanent = True
            # 账号密码正确,重定向到首页
            return redirect(url_for("index"))
        else:
            flash("账号或密码不正确!")
    else:
        return render_template("login.html")
    return render_template("login.html")

定义注册路由和视图函数:
reg,在这里进行前端数据的判断与格式控制

@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('用户注册--', username)
        if password != password2:
            flash("两次输入密码不一致")
        elif len(password) > 8:
            flash("密码太长")
        elif len(str(username)) > 10:
            flash("昵称过长")
        elif Users.query.filter(Users.account==account).first():
            flash("账号已被注册")
        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("账号由纯数字组成")
    else:
        return render_template("reg.html")
    return render_template("reg.html")

好了,以上就是注册与登录的相关操作,若有不当之处还请指正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梅干菜扣肉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值