用 Flask 來寫個輕部落格 (14) — M(V)C_實現專案首頁的模板
目錄
前文列表
實現所需要的檢視函式
- 在開始實現首頁模板之前, 我們為了除錯和顯示的方便, 首先偽造一些假資料:
- fake_data.py
import random
import datetime
from uuid import uuid4
from models import db, User, Tag, Post
user = User(id=str(uuid4()), username='jmilkfan', password='fanguiju')
db.session.add(user)
db.session.commit()
user = db.session.query(User).first()
tag_one = Tag(id=str(uuid4()), name='Python' )
tag_two = Tag(id=str(uuid4()), name='Flask')
tag_three = Tag(id=str(uuid4()), name='SQLALchemy')
tag_four = Tag(id=str(uuid4()), name='JMilkFan')
tag_list = [tag_one, tag_two, tag_three, tag_four]
s = "EXAMPLE TEXT"
for i in xrange(100):
new_post = Post(id=str(uuid4()), title="Post" + str(i))
new_post.user = user
new_post.publish_date = datetime.datetime.now()
new_post.text = s
new_post.tags = random.sample(tag_list, random.randint(1 , 3))
db.session.add(new_post)
db.session.commit()
直接在 manager shell 中匯入就能夠執行該指令碼檔案:
>>> import fake_data
home.html 的檢視函式之前博文中就已經記錄過了,現在再將必須的檢視函式程式碼貼出。
- views.py
from flask import render_template
from sqlalchemy import func
from main import app
from models import db, User, Post, Tag, Comment, posts_tags
def sidebar_data():
"""Set the sidebar function."""
# Get post of recent
recent = db.session.query(Post).order_by(
Post.publish_date.desc()
).limit(5).all()
# Get the tags and sort by count of posts.
top_tags = db.session.query(
Tag, func.count(posts_tags.c.post_id).label('total')
).join(
posts_tags
).group_by(Tag).order_by('total DESC').limit(5).all()
return recent, top_tags
@app.route('/')
@app.route('/<int:page>')
def home(page=1):
"""View function for home page"""
posts = Post.query.order_by(
Post.publish_date.desc()
).paginate(page, 10)
recent, top_tags = sidebar_data()
return render_template('home.html',
posts=posts,
recent=recent,
top_tags=top_tags)
@app.route('/post/<string:post_id>')
def post(post_id):
"""View function for post page"""
post = Post.query.get_or_404(post_id)
tags = post.tags
comments = post.comments.order_by(Comment.date.desc()).all()
recent, top_tags = sidebar_data()
return render_template('post.html',
post=post,
tags=tags,
comments=comments,
recent=recent,
top_tags=top_tags)
@app.route('/tag/<string:tag_name>')
def tag(tag_name):
"""View function for tag page"""
# Tag.qurey() 物件才有 first_or_404(),而 db.session.query(Model) 是沒有的
tag = Tag.query.filter_by(name=tag_name).first_or_404()
posts = tag.posts.order_by(Post.publish_date.desc()).all()
recent, top_tags = sidebar_data()
return render_template('tag.html',
tag=tag,
posts=posts,
recent=recent,
top_tags=top_tags)
實現 home.html 模板
- templates/home.html
<!-- Replace the TITLE of template base.html -->
{% extends "base.html"%}
{% block title %}JmilkFan's Blog{% endblock %}
<!-- Replace the BODY of template base.html -->
{% block body %}
<!-- The data object from view function: `home()` -->
<div class="row">
<div class="col-lg-9">
<!-- Get Pagination object-->
{% for post in posts.items %}
<div class="row">
<div class="col-lg-12">
<h1>{{ post.title }}</h1>
</div>
</div>
<div class="row">
<div class="col-lg-12">
{{ post.text | truncate(255) | safe }}
<!-- Set the link for read more -->
<a href="{{
url_for('post', post_id=post.id)
}}">Read More</a>
</div>
</div>
{% endfor %}
</div>
<div class="col-lg-3">
<div class="row">
<h5>Recent Posts</h5>
<ul>
{% for post in recent %}
<!-- Set the link for recent posts. -->
<li><a href="{{
url_for('post', post_id=post.id)
}}">{{ post.title }}</a></li>
{% endfor %}
</ul>
</div>
<div class="row">
<h5>Popular Tags</h5>
<ul>
{% for tag in top_tags %}
<li><a href="{{
url_for('tag', tag_name=tag[0].name)
}}">{{ tag[0].name }}</a></li>
{% endfor %}
</ul>
</div>
</div>
<!-- Call the Macro: `render_pagination` from base.html -->
{{ render_pagination(posts, 'home') }}
</div>
{% endblock %}
程式碼分析
需求:我們希望當訪問到域名 http://<ipaddress>:5000/
,即訪問部落格的 /
時,能夠正文處顯示文章列表,右上側邊欄顯示最新的 5 篇博文,右下側邊攔顯示 關聯博文數最多的 5 個標籤,並且希望每一個頁面的右側邊欄都是一致的。
按照這個需求,首先我們需要定義一個路由函式(在這裡同時也是檢視函式)
home()
來跳轉到首頁,並且首頁中具有分頁的功能,所以會定義兩個app.oute()
裝飾器。同時因為我們需要在右側邊欄顯示最新的 5 篇博文和博文關聯數最多的 5 個標籤,所以需要提供
recent/recent
資料物件,並且這些物件是高重用的,所以將其抽象成一個函式。我們還希望能夠通過右側邊攔提供的連結跳轉到具體的 post 或 tag 中,這就需要得到 posts/tags 表中的資料物件,所以會使用到檢視函式
post()/tag()
。
實現效果
- 再結合在前面博文中實現的分頁連結巨集
相關推薦
用 Flask 來寫個輕部落格 (14) — M(V)C_實現專案首頁的模板
目錄 前文列表 實現所需要的檢視函式 在開始實現首頁模板之前, 我們為了除錯和顯示的方便, 首先偽造一些假資料: fake_data.py import rand
用 Flask 來寫個輕部落格 (13) — M(V)C_WTForms 服務端表單檢驗
目錄 前文列表 用 Flask 來寫個輕部落格 (1) — 建立專案 用 Flask 來寫個輕部落格 (2) — Hello World! 用 Flask 來寫個輕部落格 (3) — (M)VC_連線 MySQL 和 SQLAlchemy
用 Flask 來寫個輕部落格 (6) — (M)VC_models 的關係(one to many)
目錄 前文列表 擴充套件閱讀 前言 models 中的關係能夠對映成為關係型資料庫表中的關係,models 中可以相互建立引用,使得相關聯的資料能夠很容易的一次性的從資料庫中取出。 一對多 首先繼續在 models
用 Flask 來寫個輕部落格 (3) — (M)VC_連線 MySQL 和 SQLAlchemy
目錄 前文列表 擴充套件閱讀 前言 大多數的應用程式在開發之前都需要先進行資料庫設計這一環節,所以本篇就先來記錄在 Flask 中如何使用 Models,也就是 MVC 模式中的 M 。 Models 模型 模型 就
用 Flask 來寫個輕部落格 (7) — (M)VC_models 的關係(many to many)
目錄 目錄 前文列表 擴充套件閱讀 前期準備 多對多 使用樣例 前文列表 擴充套件閱讀 前期準備 在實現多對多之前,我們還需要先增加一個評論(Comment) models class,而且 Comment 是 P
用 Flask 來寫個輕部落格 (5) — (M)VC_SQLAlchemy 的 CRUD 詳解
目錄 前文列表 擴充套件閱讀 SQLAlchemy 的 CRUD CRUD 提供了在 Web 應用程式中所需要的所有操作和檢視資料的基礎功能, 尤其在 REST 風格的應用中, CRUD 就能實現一切所需功能. 本篇博文主要記
用 Flask 來寫個輕部落格 (26) — 使用 Flask-Celery-Helper 實現非同步任務
目錄 前文列表 擴充套件閱讀 Celery Celery 是使用 Python 多工庫來編寫的任務佇列工具, 可以 並行 的執行任務. 我們會將執行時間較長但又不那
用 Flask 來寫個輕部落格 (16) — MV(C)_Flask Blueprint 藍圖
目錄 前文列表 擴充套件閱讀 Blueprint 藍圖 Blueprint 藍圖是一種用來擴充套件已有 Flask 應用結構的方法,通過藍圖的思想我們能夠把自己的 Application 拆分成為不同的元件。通常,一個元件代
用 Flask 來寫個輕部落格 (23) — 應用 OAuth 來實現 Facebook 第三方登入
目錄 前文列表 擴充套件閱讀 第三方登入流程 Resource Owner:資源所有者,本文中又稱”使用者”(user)。 Authorization server:認證伺服器,即服務提供商專門用來處理認證的伺服器。
用 Flask 來寫個輕部落格 (17) — MV(C)_應用藍圖來重構專案
目錄 前文列表 重構目錄結構 現在專案的目錄結構: (env) [[email protected] opt]# tree JmilkFan-s-Blog/
用 Flask 來寫個輕部落格 (24) — 使用 Flask-Login 來保護應用安全
目錄 前文列表 擴充套件閱讀 使用者登入帳號 Web上的使用者登入功能應該是最基本的功能了,但這個功能可能並沒有你所想像的那麼簡單,這是一個關係到使用者安全的功能. 在現代這樣速度的計算速度下,用窮舉法破解賬戶的密碼會是一件
用 Flask 來寫個輕部落格 (2) — Hello World!
目錄 前文列表 擴充套件閱讀 實現最簡單的 Flask 應用 建立 config.py 檔案 該檔案是整個 Flask 應用程式的配置檔案,定義我們常用的配置類 Config/ProdConfig/DevConfig
用 Flask 來寫個輕部落格 (31) — 使用 Flask-Admin 實現 FileSystem 管理
目錄 前文列表 擴充套件閱讀 編寫 FileSystem Admin 頁面 所謂的 FileSystem Admin 功能, 就是哪呢鋼構通過後臺管理頁面檢視並修改 blog 專案中, 或自定義的檔案目錄內容. 使用 F
用 Flask 來寫個輕部落格 (37) — 在 Github 上為第一階段的版本打 Tag
目錄 目錄 前文列表 打 Tag 前文列表 第一階段結語 從 2016/11/13 至今 2017/01/02 剛好 50 天, <<用 Flask 來寫個輕部落格>> 系列博文的第一階段也就算告一段
用 Flask 來寫個輕部落格 (32) — 使用 Flask-RESTful 來構建 RESTful API 之一
目錄 前文列表 擴充套件閱讀 RESTful API REST(Representational State Transfer):是一種軟體架構的設計風格,而不是一種標準。主要用於 C/S 架構的軟體設計,也能很好的支援 B
本想用python來寫個 好友發送給我指定的號,然後截屏發給好友,但是消息分割處理小毛病,還在測試
nbsp for wechat 全屏 名片 .text pict 參數 end from wxpy import * from PIL import ImageGrab import os img_path_name=‘1.jpg‘ def jiepin(img
搭建自己的部落格(三):簡單搭建首頁和詳情頁
上一篇我們建立了部落格表和標籤表以及超級使用者,那如何將建立的部落格通過網頁顯示出來呢?‘我們簡單的建立首頁和詳情頁。 1、新建html介面 首先建立在blog app下建立一個templates資料夾,這個資料夾用來放置前端頁面,注意資料夾名字必須是templates。 建立blog_list.htm
段子來了 誰說部落格不能寫段子
1. 你就是我的第一志願 因為我想上你 2.我願有一天能牽著你的手 ,去敬各位來賓的酒 3.我給你變個魔術,我變完了 我變得更喜歡你了,但你卻看不到。 4.我喜歡一個人, 那人一定很漂亮吧 !你太自戀了。 5.在遇見你之前我有兩顆心,,一顆善心 一顆噁心,,現在我只有一顆
用markdown寫的新部落格覆蓋了原有的部落格,導致原有的部落格消失了
查了一下,確實是找不到了,瀏覽量還是存在的。只有重新寫了,那是在markdown上快取的部落格,感覺是個小bug。 剛開始用csdn,不會用markdown真是一臉黑。 查了下,點(也不知道圖片上傳成功了沒)新建就可以了。也確實可以了!