• 完成登录功能,用session记住用户名


    登录功能完成:

    1. js:设置return
    2. html:设置
      1. form
      2. input
      3. onclick="return fnLogin()"
    3. py:
      1. @app.route设置methods
      2. GET
      3. POST
        1. 读取表单数据
        2. 查询数据库
          1. 用户名密码对:
            1. 记住用户名
            2. 跳转到首页
          2. 用户名密码不对:
            1. 提示相应错误。

    session:

    1. 从`flask`中导入`session`
    2. 设置`SECRET_KEY`
    3. 操作字典一样操作`session`:增加用户名`session['username']=`username

    js:

    function myLogin() {
                var oUname=document.getElementById("uname");
                var oPass=document.getElementById("upass");
                var oError=document.getElementById("error_box");
                var isError=true;
                oError.innerHTML="<br>";
    
                if(oUname.value.length<6||oUname.value.length>20){
                    oError.innerHTML='请输入6-20位的用户名';
                    isError=false;
                 return isError;
    
                }
                if(oUname.value.charCodeAt(0)>=48&&oUname.value.charCodeAt(0)<=57){
                    oError.innerHTML='首字母不能为数字';
    
                 return isError;
                }else {
                    for (var i = 0; i < oUname.value.length; i++) {
                        if ((oUname.value.charCodeAt(i) > 122 || oUname.value.charCodeAt(i) < 97) && (oUname.value.charCodeAt(i) > 57 && oUname.value.charCodeAt(i) < 48)) {
                            oError.innerHTML = '只能输入字母或数字';
                            isNotError = false;
                            return isError;
                        }
                    }
                }
                if(oPass.value.length<6||oPass.value.length>20) {
                    oError.innerHTML = '请输入6-20位的密码';
                    return isError;
    
                }
    
            }
    function mySwitch() {
        var myele=document.getElementById("on_off")
        if(myele.src.match("u=1878009223,3806655311&fm=200&gp=0"))
        {
            myele.src="https://www.duitang.com/blog/?id=528606516"
            document.getElementById("myBody").style.background="gray"
            document.getElementById("demo").style.color="white"
    
    
        }else{
            myele.src="https://www.duitang.com/blog/?id=528606516";
            document.getElementById("myBody").style.background="white"
            document.getElementById("demo").style.color="gray"
        }
    
    }
    {% extends 'index.html' %}
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}sign_in {% endblock %}</title>
        {% block head %}
        <link  href="{{ url_for('static',filename='css/nino.css') }}" rel="stylesheet" type="text/css" >
        <script src="{{ url_for('static',filename='js/sign_in.js') }}"></script>
        {% endblock %}
    </head>
    <body>
    
        {% block main %}
        <div class="box">
            <h2>登录</h2>
             <form class="form" method="post" action="{{ url_for('sign_in') }}">
    
            <div class="input_box">
                <input id="uname" class="sign" type="text" placeholder="请输入用户名" name="username">
            </div>
            <div class="input_box">
                <input id="upass" class="sign" type="password" placeholder="请输入密码" name="password">
            </div>
    
            <div id="error_box"><br>
            </div>
            <div class="input_box">
                <input type="submit" name="commit" value="登录" class="sign-in-button" data-disable-with="登录" onclick="myLogin()">
    
                </div>
             </form>
            </div>
    
    {% endblock %}
    </body>

    config:

    import os
    
    SECRET_KEY = os.urandom(24)
    
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@127.0.0.1:3306/test?charset=utf8'
    SQLALCHEMY_TRACK_MODIFICATTONS = False
    from flask import Flask,render_template,request,redirect,url_for,session
    from flask_sqlalchemy import SQLAlchemy
    import config
    
    app = Flask(__name__)
    app.config.from_object(config)
    
    db=SQLAlchemy(app)
    
    class User(db.Model):
        __tablename__ = 'User'
        id = db.Column(db.Integer,primary_key=True,autoincrement=True)
        username = db.Column(db.String(20),nullable=False)
        password = db.Column(db.String(20),nullable=False)
        nickname = db.Column(db.String(20))
    
    db.create_all()
    
    #user=User(username='jun',password='12345')
    #db.session.add(user)
    #db.session.commit()
    
    #user=User.query.filter(User.username=='jun').first()
    #user.password='123456'
    #db.session.commit()
    #print(user.id,user.username,user.password)
    
    # user=User.query.filter(User.username=='jun').first()
    # db.session.delete(user)
    # db.session.commit()
    
    @app.route('/')
    def base():
        return render_template('base.html')
    
    @app.route('/sign_in/',methods=['GET','POST'])
    def sign_in():
        if request.method == 'GET':
            return render_template('sign_in.html')
        else:
            username = request.form.get('username')
            password = request.form.get('password')
            user = User.query.filter(User.username == username).first()
            if user:
                if user.password == password:
                    session['user']=username
                    session.permanent = True
                    return redirect(url_for('base'))
                else:
                    return '密码错误'
            else:
                return '用户名不存在'
    
    @app.route('/sign_up/',methods=['GET','POST'])
    def sign_up():
        if request.method=='GET':
            return render_template('sign_up.html')
        else:
            usern=request.form.get('username')
            nickn= request.form.get('nickname')
            passw = request.form.get('password')
            user=User.query.filter(User.username==usern).first()
            if user:
                return '该用户名已存在'
            else:
                user1=User(username=usern,nickname=nickn,password=passw)
                db.session.add(user1)
                db.session.commit()
                return redirect(url_for('sign_in'))
    
    
    @app.route('/questions/')
    def questions():
        return render_template('questions.html')
    
    
    if __name__ == '__main__':
        app.run()
  • 相关阅读:
    华为机试题01背包问题
    丑数
    动态规划(1)
    Linux 后台启动 Redis
    redis.exceptions.ResponseError: MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk.
    SQLServer从渣仔到小白
    cmder 增强型命令行工具
    总结在部署分布式爬虫环境过程中常见的若干问题
    【pymongo.errors】Cursor not found
    浅析scrapy与scrapy_redis区别
  • 原文地址:https://www.cnblogs.com/1244581939cls/p/7886955.html
Copyright © 2020-2023  润新知