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

 

登录功能完成:

1.js:设置return

function fnLogin() {
            var oUname=document.getElementById("uname");
            var oUpass=document.getElementById("upass");
            var oError=document.getElementById("error_box");
            var isError=true;
            oError.innerHTML="<br>"

             //uname
            if ((oUname.value.length < 6) || (oUname.value.length > 20)) {
                oError.innerHTML = "用户名要6-20位";
                isError=false;
                return isError;
            }else if ((oUname.value.charCodeAt(0)>=48)&&(oUname.value.charCodeAt(0)<=57)){
                oError.innerHTML="首字母必须是字母";
                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="用户名只能是字母和数字";
                        isNotError=false;
                        return isError;
                    }
                }
            }
            //upass
            if ((oUpass.value.length < 6 )|| (oUpass.value.length > 20)) {
                oError.innerHTML = "密码要6-20位";
                isError=false;
                return isError;
            }
            return isError;
    window.alert("登录成功!")
        }

 

2.html:设置

  1. form
  2. input
{% extends'base.html' %}
{% block title %}登录{% endblock %}
{% block head %}
    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/login.css') }}">
    <script src="{{ url_for('static',filename='/js/login.js')}}"></script>
{% endblock %}

{% block main %}

<div class="box">
    <h2>登录</h2>
    <form action="{{ url_for('login') }}" method="post">
    <div class="input_box">
        <input id="uname" type="text"placeholder="请输入用户名" name="username">
        <input id="unickname" type="text"placeholder="请输入昵称" name="nickname">
    </div>

    <div class="input_box">
        <input  id="upass" type="password"placeholder="请输入密码" name="password">
    </div>

    <div class="input_box">
        <a href="{{ url_for('enroll') }}">没有账号?立即注册</a>
    </div>

    <div id="error_box"><br></div>
    <div class="input_box">
        <button class="button" onclick="fnLogin()">登录</button>
    </div>
    </form>
</div>
{% endblock %}

 

3.py:

  1. @app.route设置methods
  2. GET
  3. POST
    1. 读取表单数据
    2. 查询数据库
      1. 用户名密码对:
        1. 记住用户名
        2. 跳转到首页
      2. 用户名密码不对:
        1. 提示相应错误。
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(50))

# db.create_all()
# 首页
@app.route('/')
def index():
    return render_template('base.html')

#登录
@app.route('/login/',methods={'GET','POST'})
def login():
    if request.method=='GET':
        return render_template('login.html')
    else:
        username = request.form.get('username')  # 获取form中的数据
        password = request.form.get('password')
        nickname = request.form.get('nickname')
        user = User.query.filter(User.username == username).first()
        if user:
            if user.password==password:
                session['user'] = username
                session.permanent=True
                return redirect(url_for('index'))  # 返回到首页
        else:
            return u'error username or password' #输出错误


#注册
@app.route('/enroll/',methods={'GET','POST'})
def enroll():
    if request.method=='GET':
        return render_template('enroll.html')
    else:
        username=request.form.get('username')# 获取form中的数据
        password=request.form.get('password')
        nickname=request.form.get('nickname')
        user = User.query.filter(User.username == username).first()
        if user:
            return u'username existed'
        else:
            user = User(username=username, password=password, nickname=nickname)
            db.session.add(user)#数据库操作
            db.session.commit()
            return redirect(url_for('login'))# 重定向到登录页


 #提问
@app.route('/questions/')
def questions():
    return render_template('questions.html')


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

 

session:

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


SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@127.0.0.1:3306/mis_db?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS = False

1.网页运行结果:

成功运行跳转到首页:

 

 

2.数据库运行结果:

 

 

 

posted @ 2017-11-21 09:59  031庄园  阅读(408)  评论(0编辑  收藏  举报