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

登录功能完成:

  1. js:设置return
  2. html:设置
    1. form
    2. input
  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

 

代码如下:

login.html

  {% extends 'basic.html'%}
  {% block aa %}
    <link rel="stylesheet" type="text/css" href="{{url_for('static',filename="css/login.css")  }}">
   <script language="javascript" type="text/javascript" src="{{url_for('static',filename="js/login.js")  }}"></script>

&nbsp<a href="{{ url_for('index')  }}"> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509622142069&di=e2b231bb86f22bf12f9279144deef856&imgtype=0&src=http%3A%2F%2Fm.qqzhi.com%2Fupload%2Fimg_0_2679158030D2163567386_23.jpg" width="80px"  >
</a>
    <div id=mao ><p></p>
    <div id="header"><h1 align="center">Login</h1></div>
    <div id="content" >

        <form action="{{ url_for('login')}}" method="post"><br/>



            <div class="form-group">
                <label for="uname" class="col-sm-2 control-label">Username:</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="uname" name="username"
                           placeholder="input your username"><br>
                </div>


            </div>
            <div class="form-group">
                <label for="upass" class="col-sm-2 control-label">Password:</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" id="upass" name="password"
                           placeholder="input your password"><br>
                </div>
            </div>


           <div >
            <br> &nbsp &nbsp &nbsp <input type="radio" name="role" value="stu">student&nbsp
            <input id="tea" type="radio" name="role" value="tea">teacher<br/><br/>
            </div>

            <div align="center">
            <input id="rem" type="checkbox" value="true"><span>remember me</span> &nbsp &nbsp &nbsp &nbsp<a href="http://help.clouddream.net/newsitem/277741776" target="_blank">Login problem</a><br/>
            <br>
            </div>
      <div id="error_box" ></div>
            <div align="center">
               <input id="input_box" type="submit" class="btn btn-default btn-lg active" value="登录" onclick=" return miao()">
             </div>
          </form>
</div>
</div>



  {% endblock %}

login.js

   function miao(){
         var oUname = document.getElementById("uname");
    var oUpass = document.getElementById("upass");
    var oUpass2 = document.getElementById("upass2");
    var oError = document.getElementById("error_box");
    var isError = true;
    oError.innerHTML = "<br>"
    if (oUname.value.length < 6 || oUname.value.length > 12) {
        oError.innerHTML = "用户名6-12位";
        isError = false;
        return isError;
    } else if ((oUname.value.charCodeAt(0) >= 48) && (oUname.value.charCodeAt(0) <= 57)) {
        oError.innerHTML = "first letter";
        isError = false;
        return isError;
    }
    else for (var i = 0; i < oUname.value.length; i++) {
            if (((oUname.value.charCodeAt(i) < 48) || (oUname.value.charCodeAt(i) > 57)) && ((oUname.value.charCodeAt(i) < 97) || (oUname.value.charCodeAt(i) > 122))) {
                oError.innerHTML = "only letter or number";
                isError = false;
                return isError;
            }

        }

    if (oUpass.value.length < 6 || oUpass.value.length > 12) {
        oError.innerHTML = "密码6-12位";
        return false;
    }
    else if (oUpass.value !== oUpass2.value) {
        oError.innerHTML = "两次密码不一致";
        return false;
    }
    window.alert("注册成功!")
    return true;


}
function mySwitch() {
    var oBody = document.getElementById("myBody");

    var oOnOff = document.getElementById("myOnOff");
    var ogui = document.getElementById("gui");
    if (oOnOff.src.match('bulbon')) {

        oOnOff.src = "http://www.runoob.com/images/pic_bulboff.gif";
        oBody.style.backgroundColor = "black";
        oBody.background="../static/img/h.jpg"
        oBody.style.color = "white";
        ogui.src = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509563443074&di=b1bbb3f5714a580e2211e281124636c2&imgtype=0&src=http%3A%2F%2Fpic15.nipic.com%2F20110709%2F7854247_221301558161_2.jpg";
    } else {
        oOnOff.src = "http://www.runoob.com/images/pic_bulbon.gif";
        oBody.style.backgroundColor = "white";
        oBody.style.color = "black";
        ogui.src = "";
        oBody.background="../static/img/timg1.jpg"
    }
}

config.py

import os
DEBUG=True
SECRET_KEY=os .urandom(24)

DIALECT='mysql'
DRIVER='mysqldb'
USERNAME='miaomiaoyu'
PASSWORD='201506050046'
HOST='119.23.58.9'
PORT='3306'
DATABASE='python'

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://miaomiaoyu:201506050046@119.23.58.9:3306/python?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS = False

unuitle6.py

from flask import Flask
from flask import render_template,request,redirect,url_for,session
import config

from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'user'
    # 建立一个表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)
    say = db.Column(db.String(50))

#db.create_all()

class Log(db.Model):
    __tablename__ = 'log'
    # 建立一个表log
    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)


#db.create_all()

# 添加数据
# user=User(username='yujiujiu2',password='11111')
# db.session.add(user)
# db.session.commit()
#

# 查找数据
# user=User.query.filter(User.username=='yujiujiu').first()
# print(user.username,user.password)


# 修改数据
# user=User.query.filter(User.username=='yujiujiu').first()
# user.password='666667'
# print(user.username,user.password)
# db.session.commit()


# 删除数据
# user=User.query.filter(User.username=='yujiujiu2').first()
# db.session.delete(user)
# db.session.commit()



@app.route('/')
def index():
    return render_template('basic.html')




#第1种写法,存入Log表里面的数据与User表对比

# @app.route('/login/',methods=['GET','POST'])
# def login():
#     if request.method=='GET':
#         return render_template('login.html')
#     else:
#         username=request.form.get('username')
#         password=request.form.get('password')
#
#         log=Log.query.filter(User.username==username,User.password==password).first()
#         #判断用户名是否存在
#         if log:
#             log = Log(username=username, password=password)
#             db.session.add(log)
#             db.session.commit()
#             return redirect(url_for('index'))
#
#         else:
#
#             return u' error username or password'

# 重新定向到首页

#第二种写法

@app.route('/login/',methods=['GET','POST'])
def login():
    if request.method=='GET':
        return render_template('login.html')
    else:
        usern=request.form.get('username')
        passw=request.form.get('password')

        user=User.query.filter(User.username==usern).first()
        #判断用户名是否存在
        if user:
            session['user']=usern
            session.permanent=True
            if user.password==passw:
                return redirect(url_for('index'))
            else:
                return u' password error'
        else:
            return u' username  not existed'



@app.route('/zhuce/',methods=['GET','POST'])
def zhuce():
    if request.method=='GET':
        return render_template('zhuce.html')
    else:
        username=request.form.get('username')
        password=request.form.get('password')
        say=request.form.get('say')
        user=User.query.filter(User.username==username).first()
        #判断用户名是否存在
        if user:
            return u' username existed'
        else:
            user=User(username=username,password=password,say=say)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('login'))
# 重新定向到登录页



if __name__ == '__main__':
    app.run(debug=True)

运行结果:

 

                        

 

 

posted on 2017-11-21 11:29  046余博智  阅读(438)  评论(0编辑  收藏  举报

导航