登录之后更新导航

  1. 用上下文处理器app_context_processor定义函数
    1. 获取session中保存的值
    2. 返回字典
  2. 在父模板中更新导航,插入登录状态判断代码。、
    1. 注意用{% ... %}表示指令。
    2. {{ }}表示变量
  3. 完成注销功能。
    1. 清除session
    2. 跳转

代码如下:

basic.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
     <script language="javascript" type="text/javascript" src="{{url_for('static',filename="js/basic.js")  }}"></script>
    <link rel="stylesheet" type="text/css" href="{{url_for('static',filename="css/basic.css")  }}">
    <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body  id="myBody" background="{{url_for('static',filename="img/timg1.jpg")  }}">


<ul class="nav nav-pills">
    <li class="active"><a href="{{ url_for('index')  }}"><h2>Home</h2></a></li>
    <li><a href="#"><h2>PHP</h2></a></li>
    <li><a href="#"><h2>JAVA</h2></a></li>
    <li><a href="#"><h2>C++</h2></a></li>
    <li class="dropdown">
        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
            <h2>更多</h2><span class="caret"></span>
        </a>
        <ul class="dropdown-menu">
            <li><a href="#"><h2>python</h2></a></li>
            <li><a href="#"><h2>html</h2></a></li>
            <li><a href="#"><h2>jsp</h2></a></li>

        </ul>
    </li>
<li><a href="#"><h2>......&nbsp</h2></a></li>
<li>
      <input class="d1" type="text" placeholder="搜索从这里开始...">
      <button  class="b" type="submit">搜索</button></li>

    <li><img id="myOnOff" onclick="mySwitch()" src="http://www.runoob.com/images/pic_bulbon.gif" width="40px">&nbsp;</li>


    {% if username %}

    <li><a href="#"><h2>{{ username }}</h2></a></li>
    <li><a href="{{ url_for('logout') }}"><h2>注销</h2></a></li>
    {% else %}
    <li><a href="{{ url_for('login') }}"><h2>登录</h2></a></li>
    <li><a href="{{ url_for('zhuce') }}"><h2>注册</h2></a></li>
    {% endif %}
    <li><a href="#"><h2>联系我</h2></a></li>
</ul>


<img id="gui" onclick="mySwitch()" src="" width="1700px">

{% block aa %}{% endblock %}
<p><h1>此处是用户名:{{username }}</h1></p>
<div id="didao">

    <div class="img"><a href="http://www.baidu.com"><img src="http://scimg.jb51.net/allimg/140408/10-14040QG01GU.jpg"></a><div class="desc"></div><a href="http://www.baidu.com">更多搜索</a></div>
    <div class="img"><a href="http://www.baidu.com"><img src="http://imgstore.cdn.sogou.com/app/a/100540002/800197.jpg"></a><div class="desc"></div><a href="http://www.gzcc.cn/">教务系统</a></div>
    <div class="img"><a href="http://www.baidu.com"><img src="http://4493bz.1985t.com/uploads/allimg/150625/1-1506251F320.jpg"></a><div class="desc"></div><a href="http://bbs.tianya.cn/">友情论坛</a></div>
    <div class="img"><a href="http://www.baidu.com"><img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510223061&di=bc9ea322068f5f0311fb2ab6fe9db29a&imgtype=jpg&er=1&src=http%3A%2F%2Fwww.005.tv%2Fuploads%2Fallimg%2F160920%2F103J12649-15.jpg"></a><div class="desc"></div><a href="{{ url_for('index') }}">回到顶部</a></div>

</div>



<footer>
    <div class="foot">
       <div > <a href="#"> 联系我们</a> · <a href="#"> 加入我们</a> ·  <a href="#"> 品牌与徽标 </a> ·  <a href="#">帮助中心</a> · <a href="#">合作伙伴</a></div>
        <div>©2015-2017 广州商学院信息技术与工程学院 / 粤ICP备278953737号-5 / 粤公网安备2015060050046号 /   Smrz 粤公网安备201506050046号 /   Wxb  举报电话:020-66666666</div>
    </div>
</footer>
</body>
</html>

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:

            if user.password==passw:
                session['user'] = usern#字典键值
                session.permanent = True
                return redirect(url_for('index'))
            else:
                return u' password error'
        else:
            return u' username  not existed'

@app.context_processor
def mycontext():
    usern=session.get('user')
    if usern:
        return {'username':usern}
    else:
        return {}

@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index'))





@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)

confit.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

 

运行结果:

 

 

posted on 2017-11-24 09:48  046余博智  阅读(349)  评论(0编辑  收藏  举报

导航