- 登录状态的显示
- 登出
- 首页新闻排行的显示
登录状态的显示
当用户登陆后,在页面的右上角会显示用户的登录信息,未登录时显示登录/注册的信息。
在index.html中找到这部分的代码:
我们要从后端获取到用户的登陆信息,传到前端页面来显示。
index/views.py
from flask import render_template, current_app, session
from . import index_blue #导入__init__.py下的蓝图对象index_blue
from ...models import User
#首页
@index_blue.route('/')
def index():
'''首页显示'''
#通过session获取当前的用户id
user_id = session.get('user_id')
user = None
#通过id查询用户的信息
if user_id:
try:
user = User.query.get(user_id)
except Exception as e:
current_app.logger.error(e)
data = {
"user_info": user.to_dict() if user else None, #to_dict():将对象中的信息转换为字典类型
}
return render_template('news/index.html',data=data)
运行:
未登录状态:
登陆状态:
登出
实现登出,首先用户点击退出按钮,响应js中的事件,像后端发起ajax请求,在后端实现登出的逻辑。
添加点击事件logout():
在main.js中编写该事件函数的内容--ajax:
//登出
function logout() {
$.ajax({
url:'/passport/logout',
type:'post',
headers: {'X-CSRFToken': getCookie('csrf_token')},
success: function (resp) {
alert(resp.errmsg)
// window.location.reload()
window.location.href="/"; //跳转到index页面
}
})
}
在passport/views.py:
'''退出'''
@passport_blue.route('/logout',methods=['POST'])
def logout():
# 清除session中的信息
session.pop('user_id',None)
session.pop('mobile', None)
session.pop('nick_name', None)
return jsonify(errno=RET.OK,errmsg='OK')
分析:
用户点击退出按钮,进入logout(),在该函数中发起ajax请求,在views的logout函数中清除当前浏览器中的session信息(与登录时设置的信息相对应),返回成功退出的信息。
index首页的数据显示
右侧排行的显示
在学习django的时侯,在后端通过orm对数据库进行查询,传给前端页面,进行显示即可,flask与其的思想一致,但具体的查询方式有所不同。
在index/views/index():
from flask import render_template, current_app, session
from . import index_blue #导入__init__.py下的蓝图对象index_blue
#网页标签logo
from ... import constants
from ...models import User, News # 用户表
#首页
@index_blue.route('/')
def index():
'''首页显示'''
#通过session获取当前的用户id
user_id = session.get('user_id')
user = None
#通过id查询用户的信息
if user_id:
try:
user = User.query.get(user_id)
except Exception as e:
current_app.logger.error(e)
#新闻排行
news_list = []
try:
#根据点击数进行排序,并取前6个
news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
except Exception as e:
current_app.logger.error(e)
click_news_list = []
#如果该列表存在,执行前边的语句,否则执行后边的语句
for news in news_list if news_list else []:
click_news_list.append(news.to_basic_dict()) #将每个news对象,转化为字典后,加到另一个列表中
#传给前台的数据
data = {
"user_info": user.to_dict() if user else None, #to_dict():将对象中的信息转换为字典类型
"click_news_list":click_news_list,
}
return render_template('news/index.html',data=data)
分析:
1.首先获取News类根据点击数排序的前六个对象,返回一个对象列表news_list
2.遍历这个列表,把里边的每个对象转换为字典类型添加到一个新的列表中
3.添加到data中,传给前台显示
前端页面的数据填充:
在前端这块展示使用无序列表进行展示的,所以直接使用for循环即可。
<ul class="rank_list">
1.老的方式
{% for news in data.click_news_list %}
{# <li><span class="{% if loop.index == 1 %}#}
{# first#}
{# {% elif loop.index == 2 %}#}
{# second#}
{# {% elif loop.index == 3%}#}
{# third#}
{# {% endif %}">{{ loop.index }}</span><a href="#">{{ news.title }}</a></li>#}
2.新的方式
<li><span class="{{ loop.index|index_class }}">{{ loop.index }}</span><a href="#">{{ news.title }}</a></li>
{% endfor %}
</ul>
由于显示时,css样式显示有所分别--前三名有不同的css样式,
所以要在class的值上用if进行判断。
也可以使用过滤器进行解决:
过滤器步骤:
1.创建过滤器
在utils包下创建common.py文件,
common.py
##首页新闻排行的过滤器
def do_index_class(index):
if index ==1:
return 'first'
elif index == 2:
return 'second'
elif index == 3:
return 'third'
2.在app中注册该过滤器
在newsInfo/init.py中的create_app()注册:
#注册过滤器
from newsInfo.utils.common import do_index_class
app.add_template_filter(do_index_class,'index_class')
参数1:过滤器函数名,参数2:在模板中自定义使用的名字
3.使用过滤器
在html中使用
<li><span class="{{ loop.index|index_class }}">{{ loop.index }}</span><a href="#">{{ news.title }}</a></li>
运行:









网友评论