前篇回顧:
Flask博客項目-項目的開始(一)
Flask博客項目-Shell拓展Flask_Script(二)
Flask博客項目-數據模型的創建(三)
Flask博客項目-數據模型的擴建(四)
Flask博客項目-數據庫的遷移(五)
Jinjia是用Python實現的模版語言(模版語言:被設計來自動生成文檔的簡單文本格式)
首先,我們需要在項目根目錄中創建一個叫做 templates 的新目錄
然後,我們創建一個頁面的側邊欄信息
在main.py中加入
from sqlalchemy import func
from flask import render_template
def sidebar_data():
recent = Post.query.order_by(Post.publish_date.desc()).limit(5).all()
top_tags = db.session.query(
Tag, func.count(tags.c.p_id).label('total')
).join(tags).group_by(Tag).order_by('total DESC').limit(5).all()
return recent, top_tags
其中,func.count()函數的作用是計數排序(SQLAlchemy的func庫可以返回一個計數器,並按照使用次數對標籤進行排序)
這裏我們利用top_tags來獲取最常用標籤
然後修改我們主頁的視圖函數:
#“視圖函數”
@app.route('/')
@app.route('/<int:page>')
def home(page=1):
posts = Post.query.order_by(Post.publish_date.desc()).paginate(page,10)
recent, top_tags = sidebar_data()
return render_template('home.html', post=posts, recent=recent, top_tags=top_tags)
其中,paginate()函數的作用是,幫助我們進行分頁展示
我們只需要得到page~10頁上的數據(如果沒有傳入page參數,則默認從第一頁開始)
接着我們要寫一下我們提交文章的視圖函數:
@app.route('/post/<int:p_id>')
def post(p_id):
post = Post.query.get_or_404(p_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)
其中,get_or_404()函數的作用是,得不到我就返回404錯誤(是有點任性)
有了提交文章的視圖,當然也少不了我們標籤的視圖函數:
@app.route('/tag/<string:tag_name>')
def tag(tag_name):
tag = Tag.query.filter_by(title=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)
其中,query.filter_by()這個是條件查詢噢 (我們當然要按照標籤名來查找啦)
有了主頁以及其他頁面,當然也不能沒有用戶的個人頁面吧:
@app.route('/user/<string:username>')
def user(username):
user = Tag.query.filter_by(username=username).first_or_404()
posts = tag.posts.order_by(Post.publish_date.desc()).all()
recent, top_tags = sidebar_data()
return render_template('user.html', user=user, posts=posts, recent=recent, top_tags=top_tags)
點擊此處查看Git源碼
有了視圖函數,接下來就是處理我們的html模版啦
這個篇幅也不小,所以還是在下篇進行描述吧