登录之后更新导航
- 用上下文处理器app_context_processor定义函数
- 获取session中保存的值
- 返回字典
- 在父模板中更新导航,插入登录状态判断代码。
- 注意用{% ... %}表示指令。
- {{ }}表示变量
- 完成注销功能。
- 清除session
- 跳转
base html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> {% block title %} {% endblock %} 啦啦啦</title> <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/base.css') }}"> <script src ="{{ url_for('static',filename='js/base.js') }}"></script> {% block head %} {% endblock %} </head> <body id="myBody"> <nav> <img id="myOnOff" onclick="mySwitch()" src="https://www.runoob.com/images/pic_bulbon.gif" height="20" width="20px"> <a href="{{ url_for('shouye') }}">首页</a> <a href="{{ url_for('wenda') }}">发布问答</a> <a href="{{ url_for('shouye') }}">听一听</a> <input type="text" name="search"> <button type="submit">看一看</button> {% if username %} <a class="right" href="#">{{ username }}</a> <a href="{{ url_for('logout') }}">注销</a> {% else %} <a class="right" href="{{ url_for('login') }}">登录</a> <a href="{{ url_for('zhuce') }}">注册</a> {% endif %} </nav> {% block main %} {% endblock %} <p class="text1">哈哈哈<br> by:厚脸皮羊 </p> </body> </html>
py页面
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) #db.create_all() @app.route('/') def base(): return render_template('base.html') @app.route('/shouye/') def shouye(): return render_template('shouye.html') @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 return redirect(url_for('shouye')) else: return u'password error' else: return u'username is 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('shouye')) @app.route('/zhuce/',methods=['GET','POST']) def zhuce(): if request.method == 'GET': return render_template('zhuce.html') else: usern = request.form.get('username') passw = request.form.get('password') user = User.query.filter(User.username == usern).first() if user: return u'username existed' else: user1 = User(username=usern, password=passw) db.session.add(user1) db.session.commit() return redirect(url_for('login')) @app.route('/wenda/') def wenda(): return render_template('wenda.html') if __name__ == '__main__': app.run(debug=True)