上章的结束,若在实际开发过程中,会发现一个问题,那就首页或关注分享,是一下子按时间顺序全部显示出来,这在实际项目中不可能出现的,想想实际中的产品是如何做的?

一般来说,无非是两种,一种是使用页码,来进行分页,还有一种是js到页底自动加载,而使用页底自动加载的话,上一章实现的通过tab来区分全部和关注就不可取了,因为无法保证两个tab加载的内容数量一致,导致页面布局就无法实现,所以,这里首页参考tumblr的实现方式,删除关注分享的部分,只保留全部分享,使用js页底动态加载分页方式,同时在导航栏新增两个导航,分别为博文,和关注,使用传统页码的方式显示全部博文和已关注博文,这样是为了有些人可能会查询比较久的历史信息,所以,一个页面,一个功能如何设计,主要取决于业务需求,而不是技术需求。首先修改导航(base.html):

 <ul class="nav navbar-nav">
<li><a href="/">首页</a></li>
<li><a href="#">分享</a></li>
{% if current_user.is_authenticated %}
<li><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
aria-haspopup="true" aria-expanded="false">关注 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">分享</a></li>
<li><a href="#">用户</a></li>
</ul>
</li>
{% endif %}
</ul>

用户登录后,在首页后面会新增两个item,分别是分享和关注,其中关注是一个下拉菜单,分别是“我”关注的用户发布的分享,和“我”关注的用户

下面完成这几个页面,首先是分享页,即所有用户发布的分享,页面与之前的首页很像,首先完成视图模型:

@main.route("/post")
@main.route("/post/<int:page>")
def post(page=1):
pagination=Post.query.order_by(Post.createtime.desc()).paginate(
page,per_page=current_app.config["POSTS_PER_PAGE"],error_out=False
)
return render_template("posts.html",posts=pagination.items,pagination=pagination,endpoint=request.endpoint)

这个模型的route的意思是,既可以通过/post访问,也可以通过/post/1等类型访问,当/post访问的时候,默认访问第一页。

endpoint的意思为访问的端点,即方法的端点,针对于这个方法来说,endpoint的值为"main.post"

接下来的内容,就是本章的一个重点了,pagination对象,这个是flask-SQLAlchemy框架中的一个很重要的对象,它包含了一系列用于分页的属性,其中主要的属性如下:

has_next

是否还有下一页

has_prev

是否还有前一页

items

当前页的数据

iter_pages(left_edge=2,left_current=2,right_current=5,right_edge=2)

一个关于页面的迭代,可以有四个带有默认值的参数:

  1. left_edge 页码最左边显示的页数
  2. left_current 当前页左边显示的页数
  3. right_current 当前页右边显示的页数
  4. right_edge 页面最右边显示的页数

可能有些不好理解,举个例子,假设共100页,当前为50页,则显示如下:

1,2...48,49,50,51,52,53,54,55...99,100

next(error_out=False)

下一页的分页对象,当error_out为true时,超过页面返回404

prev(error_out=False)

上一页的分页对象

page

当前页码

prev_num

上页页码

next_num

下页页码

per_page

每页显示的记录数量

total

记录总数

还有更多属性,请查验文档

分享页的模板与首页几乎一样,同样是一个分享发布框,一个已分享列表(posts.html):

{% import "_index_post_macros.html" as macros %}
...
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-8 col-md-8 col-lg-8">
<div>
{% if current_user.is_authenticated %}
{{ wtf.quick_form(form) }}
{% endif %}
</div>
<br> <div class="tab-content">
<!--全部-->
<div id="all" role="tabpanel" class="tab-pane fade in active">
{{macros.rander_posts(posts,moment,pagination,endpoint)}}
</div>
</div>
</div>
<div class="col-md-4 col-md-4 col-lg-4">
<!--这里 当没有用户登录的时候 显示热门分享列表 稍后实现-->
{% if current_user.is_authenticated %}
<img src="http://on4ag3uf5.bkt.clouddn.com/{{current_user.headimg}}" alt="..." class="headimg img-thumbnail">
<br><br>
<p class="text-muted">我已经分享<span class="text-danger">{{ current_user.posts.count() }}</span>条心情</p>
<p class="text-muted">我已经关注了<span class="text-danger">{{ current_user.followed.count() }}</span>名好友</p>
<p class="text-muted">我已经被<span class="text-danger">{{ current_user.followers.count() }}</span>名好友关注</p>
{%endif%}
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
{{ super() }}
{{ pagedown.include_pagedown() }}
<script type="text/javascript">
$('.nav-tabs a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
</script>
{% endblock%}

并没有做过多的封装,其实完全可以把右侧在封装成为一个macro

接下来是_index_post_macros.html

{% macro rander_posts(posts,moment,pagination=None,endpoint=None) %}
{% import "_posts_page_macros.html" as macros %}
{% for post in posts %}
<div class="bs-callout
{% if loop.index % 2 ==0 %}
bs-callout-d
{% endif %}
{% if loop.last %}
bs-callout-last
{% endif %}" >
<div class="row">
<div class="col-sm-2 col-md-2">
<!--使用测试域名-->
<a class="text-left" href="{{url_for('main.user',username=post.author.username)}}">
<img src="http://on4ag3uf5.bkt.clouddn.com/{{post.author.headimg}}" alt="...">
</a>
</div>
<div class="col-sm-10 col-md-10">
<div>
<p>
{% if post.body_html%}
{{post.body_html|safe}}
{% else %}
{{post.body}}
{% endif %}
</p>
</div>
<div>
<a class="text-left" href="{{url_for('main.user',username=post.author.username)}}">{{post.author.nickname}}</a>
<span class="text-right">发表于&nbsp;{{ moment( post.createtime).fromNow(refresh=True)}}</span>
</div>
</div>
</div>
</div>
{% endfor %}
{% if pagination and endpoint %}
{{macros.rander_page(pagination,endpoint)}}
{% endif %}
{%endmacro%}

这里需要注意的一点也就是最下边新增的代码,意味着macro也可以嵌套,如果pagination和endpoint不为None,则显示页码,而_posts_page_macros.html的代码如下:

{% macro rander_page(pagination,endpoint) %}
<nav aria-label="Page navigation">
<ul class="pagination pagination-sm">
{% if pagination.has_prev %}
<li>
<a href="{{url_for(endpoint,page=pagination.page-1)}}" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
{% else %}
<li class="disabled">
<a href="#" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
{% endif %}
{% for p in pagination.iter_pages() %}
{% if p%}
{% if p ==pagination.page%}
<li class="active"><a href="#">{{p}}</a></li>
{% else %}
<li><a href="{{url_for(endpoint,page=p)}}">{{p}}</a></li>
{% endif %}
{% else %}
<li class="disabled"><a href="#">...</a></li>
{% endif %}
{% endfor %} {% if pagination.has_next %}
<li>
<a href="{{url_for(endpoint,page=pagination.page+1)}}" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
{% else %}
<li class="disabled">
<a href="#" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
{% endif %}
</ul>
</nav>
{% endmacro %}

这是一个比较典型的pagination的使用方式,完全使用了bootstrap的样式,最终的显示效果如下:

貌似内容有点少,分页我发测试,并且之后关注分页,首页动态分页都要用,所以首先要扩充一些分享内容,扩充的方式多种多样,比如实际数据,手动修改数据库,但对于python来说,它提供了一个不错的生成虚拟数据的轮子,即ForgeryPy,首先当然还是安装:

pip3.6 install ForgeryPy

然后修改Post类,添加一个静态方法(Post.py)

@staticmethod
def generate_fake():
from random import seed, randint;
from .User import User
import forgery_py;
seed()
user_count = User.query.count()
for i in range(100):
u = User.query.offset(randint(0, user_count - 1)).first()
p = Post(body=forgery_py.lorem_ipsum.sentences(randint(1, 3)),
createtime=forgery_py.date.date(True), author=u)
db.session.add(p)
db.session.commit()

几个参数说明一下:

  1. lorem_ipsum比较有趣,原意为一些排版时的占位用的无意义字符,具体解释可参考阮博的博客,sentences方法为生成普通句子,参数代表句子的数量。
  2. date的参数表示生成时间的区间,True表示生成的区间都为过去的时间

这个静态方法的使用方式为:

python manage.py shell
Post.generate_fake()

这样就会生成100条分享。

下面在看一下分享页的效果(尾页):

不考虑美工的话,效果还是可以的,不过内容都是英文的,不知道能不能有一个中文的虚拟数据生成器:)

下面是关注分享页,和这个页类似,视图模型为:

@main.route("/follow_post",methods=["GET","POST"])
@main.route("/follow_post/<int:page>",methods=["GET","POST"])
@login_required
def follow_post(page=1):
form = PostForm()
if form_util(form):
return redirect(url_for(request.endpoint)) # 跳回首页
print(form.body.data)
pagination=Post.query.select_from(Follow).filter_by(follower_id=current_user.id)\
.join(Post,Follow.followed_id == Post.author_id).paginate(
page,per_page=current_app.config["POSTS_PER_PAGE"],error_out=False
)
return render_template("posts.html",posts=pagination.items,form=form,
pagination=pagination,endpoint=request.endpoint)

注意,由于关注分享,分享和首页都有PostForm,所以把这个功能独立出来:

def form_util(form):
if form.validate_on_submit():
post = Post(body=form.body.data, author_id=current_user.id)
db.session.add(post);
return True
return False

其实我想flask应该有整个页面的某一个功能独立为一个视图模型的方式,但我没有找到,如果读者找到了别忘了留言回复

最后,关注的用户就太简单了,可以直接使用某用户关注的页面,将userid参数赋予当前用户的参数即可,最终base.html的导航部分代码为:

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="/">首页</a></li>
<li><a href="{{url_for('main.post')}}">分享</a></li>
{% if current_user.is_authenticated %}
<li><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
aria-haspopup="true" aria-expanded="false">关注 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="{{url_for('main.follow_post')}}">分享</a></li>
<li><a href="{{url_for('main.follow_list',type='followed',userid=current_user.id)}}">用户</a></li>
</ul>
</li>
{% endif %}
</ul>
<ul class="nav navbar-nav navbar-right">
{% if current_user.is_authenticated %}
<li><p class="navbar-text"><a href="#" class="navbar-link">{{current_user.username}}</a> 您好</p></li>
<li><a href="{{url_for('auth.logout')}}">登出</a></li>
{% else %}
<li><a href="{{url_for('auth.login')}}">登录</a></li>
<li><a href="{{url_for('auth.register')}}">注册</a></li>
{% endif %}
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
</div><!-- /.navbar-collapse -->

然后删除首页中tab的部分,最终代码为:

<div class="container">
<div class="row">
<div class="col-xs-12 col-md-8 col-md-8 col-lg-8">
<div>
{% if current_user.is_authenticated %}
{{ wtf.quick_form(form) }}
{% endif %}
</div>
<br>
<ul class="nav nav-tabs">
<li role="presentation" class="active"><a href="#all">最新分享</a></li>
</ul>
<div class="tab-content">
<!--全部-->
<div id="all" role="tabpanel" class="tab-pane fade in active">
{{macros.rander_posts(posts,moment)}}
</div>
</div>
</div>
<div class="col-md-4 col-md-4 col-lg-4">
<!--这里 当没有用户登录的时候 显示热门分享列表 稍后实现-->
{% if current_user.is_authenticated %}
<img src="http://on4ag3uf5.bkt.clouddn.com/{{current_user.headimg}}" alt="..." class="headimg img-thumbnail">
<br><br>
<p class="text-muted">我已经分享<span class="text-danger">{{ current_user.posts.count() }}</span>条心情</p>
<p class="text-muted">我已经关注了<span class="text-danger">{{ current_user.followed.count() }}</span>名好友</p>
<p class="text-muted">我已经被<span class="text-danger">{{ current_user.followers.count() }}</span>名好友关注</p>
{%endif%}
</div>
</div>
</div>

这时候,你可能已经发现了,首页的分享还没有进行分页,在本章的开始部分就已经解释道,首页使用动态加载的分页方式,而动态加载显然需要js的配合,使用json的方式向html中注入。这时候服务端就会面临一个问题,如何与客户端的js进行交互呢,这是下一章将要说明的问题。

一个web应用的诞生(11)--列表分页的更多相关文章

  1. 一个web应用的诞生(11)--在探首页

    就要面对本章的一个难点了,说是难点可能仅仅对于我来说,毕竟我是一个js渣,既然首页打算使用动态加载的形式,那么与后台交互的方式就要进行选择,目前比较流行的为RESTful的形式,关于RESTful的文 ...

  2. 一个web应用的诞生(1)--初识flask

    基于flask的web应用的诞生 Flask是一个非常优秀的web框架,它最大的特点就是保持一个简单而易于扩展的小核心,其他的都有用户自己掌握,并且方便替换,甚至,你可以在社区看到众多开源的,可直接用 ...

  3. 从零开始,开发一个 Web Office 套件(11):支持中文输入法(or 其它使用输入法的语言)

    这是一个系列博客,最终目的是要做一个基于 HTML Canvas 的.类似于微软 Office 的 Web Office 套件(包括:文档.表格.幻灯片--等等). 博客园:<从零开始, 开发一 ...

  4. 一个web应用的诞生--数据存储

    上一章实现了登录的部分功能,之所以说是部分功能,是因为用户名和密码写成固定值肯定是不可以的,一个整体的功能,至少需要注册,登录,密码修改等,这就需要提供一个把这些值存储到数据库的能力. 当前的主流数据 ...

  5. 一个web应用的诞生(4)--数据存储

    上一章实现了登录的部分功能,之所以说是部分功能,是因为用户名和密码写成固定值肯定是不可以的,一个整体的功能,至少需要注册,登录,密码修改等,这就需要提供一个把这些值存储到数据库的能力. 当前的主流数据 ...

  6. 一个web应用的诞生(4)

    上一章实现了登录的部分功能,之所以说是部分功能,是因为用户名和密码写成固定值肯定是不可以的,一个整体的功能,至少需要注册,登录,密码修改等,这就需要提供一个把这些值存储到数据库的能力. 当前的主流数据 ...

  7. 一个web应用的诞生(8)--博文发布

    这个系统一直号称轻博客,但貌似博客的功能还没有实现,这一章将简单的实现一个博客功能,首先,当然是为数据库创建一个博文表(models\post.py): from .. import db from ...

  8. 一个web应用的诞生(9)--回到用户

    在开始之前,我们首先根据之前的内容想象一个场景,用户张三在网上浏览,看到了这个轻博客,发现了感兴趣的内容,于是想要为大家分享一下心情,恩?发现需要注册,好,输入用户名,密码,邮箱,并上传头像后,就可以 ...

  9. 一个web应用的诞生(10)--关注好友

    下面回到首页中,使用一个账户登录,你肯定已经注意到了这里的内容: 没错,现在都是写死的一些固定信息,其中分享数量很容易就可以获取,只需要修改首页模板: <p class="text-m ...

随机推荐

  1. 微软MSBI商业智能视频

    第一讲:BI介质安装.BI基础知识讲解.BI方法论讲解.项目讲解                 1.BI基础知识讲解.BI方法论实施2.微软BI的介绍(数据仓库介绍.SSIS介绍.SSAS介绍.SS ...

  2. SQL server 数据库 ——聚合函数(一列 多行,值类型)

    聚合函数 5种函数: 1.max最大值   select max(price) from car where code='c024' 2.min最小值   select * from car wher ...

  3. KoaHub.JS用于Node.js的可移植Unix shell命令程序代码

    shelljs Portable Unix shell commands for Node.js ShellJS - Unix shell commands for Node.js     Shell ...

  4. 安装rabbitmq以及集群配置

    前言: (一些有用没用的唠叨,反正看了也不少肉,跳过也没啥) 情况是这样的:虚拟机.CentOS 6.5.免编译包安装rabbitmq集群,可不用连外网. 我原计划是安装在虚拟机上wyt1/wyt2/ ...

  5. jsp想js,action传值

    1.struts2 action如何向JSP的JS函数传值 action中定义变量 public class TestAction extends ActionSupport implements S ...

  6. Apache无法启动原因

    Apache不能启动解决办法 作者的话:遇到这个问题的时候,从网上找了很多资料,结果都是让我这个新手摸不着头绪 还好,在我长时间的查找下,还是找到了一篇文章,解决了我的烦恼,下面是我对这个文章的一些对 ...

  7. Spring 4 支持的 Java 8 特性

    Spring 框架 4 支持 Java 8 语言和 API 功能.在本文中,我们将重点放在 Spring 4 支持新的 Java 8 的功能.最重要的是 Lambda 表达式,方法引用,JSR-310 ...

  8. golang socket 分析

    socket:tcp/udp.ip构成了网络通信的基石,tcp/ip是面向连接的通信协议 要求建立连接时进行3次握手确保连接已被建立,关闭连接时需要4次通信来保证客户端和,服务端都已经关闭 在通信过程 ...

  9. JDBC(下)

    1. 预编译sql处理(防止sql注入) -- 创建数据库 CREATE DATABASE jdbc_demo DEFAULT CHARACTER SET utf8;i -- 创建表 USE jdbc ...

  10. centos mail使用外部SMTP发送邮件

    1.安装mailx yum install mailx -y 安装好后,编辑配置文件 mailx -V 12.4 7/29/08  <<mailx的版本号 rpm -qc mailx /e ...