在資料頁中顯示關注者
如果用戶查看一個尚未關注用戶的資料頁,頁面中要顯示一個“Follow”(關注)按鈕,如果查看已關注用戶的資料則顯示“Unfollow”(取消關注)按鈕,並且,頁面中最好能顯示出關注者和被關注者的數量,再列出關注和被關注者的用戶列表,並在相應的用戶資料頁中顯示“Follow You”(關注了你)標誌,對用戶資料頁模板的改動如下例所示:
# app/templates/user.html
#...
{% if current_user.can(Permission.FOLLOW) and user != current_user %}
{% if not current_user.is_following(user) %}
<a href="{{ url-for('.follow', username=user.username) }}"
class="btn btn-primary">Follow</a>
{% else %}
<a href="{{ url_for'.unfollow', username = user.username) }}"
class="btn btn-default">Unfollow
</a>
{% endif %}
{% endif %}
<a href="{{ url_for('.followers', username=user.username) }}">
Followers:<span class='badge'>{{ user.followers.count() }}</span>
</a>
<a href="{{ url_for(.followed_by, username=user.username) }}">
Following:<span class="badge">{{ user.followed.count() }}</span>
</a>
{% if current_user.is_authenticated() and user != current_user and user.is_following(current_user) %}
| <span class="label label-default">Follows you</span>
{% endif %}
這次修改模板用到了4個新端點,用戶在其他用戶的資料頁中點擊”Follow”(關注)按鈕後,執行的是/follow/路由,這個路由的實現方法如下:
# app/main/views.py
#...
@main.route('/follow/<username>')
@login_required
@permission_required
def follow(username):
user = User.query.filter_by(username=username).first()
if user is None:
flash('Invalid user.')
return redirect(url_for('.index'))
if current_user.is_following(user):
flash('You are already following this user.')
return redirect(url_for('.user',username=username))
current_user.follow(user)
flash('You are now following %s.' % username)
return redirect(url_for('.user',username=username))
這個視圖函數先加載請求的用戶,確保用戶存在且當前登錄用戶還沒有關注這個用戶,然後調用User模型中定義的輔助方法follow()
,用以聯接兩個用戶 /unfollow/<username>
路由的實現方式類似
用戶在其他用戶的資料頁中點擊關注者數量後,將調用/followers/<username>
路由,這個路由的實現如下所示:
# app/main/views.py
# ...
@main.route('/followers/<username>')
def followers(username):
user = User.query.filter_by(username=username).first()
if user is None:
flash('Invalid user.')
return redirect(url_for('.index'))
page = request.args.get('page', 1, type=int)
pagination = user.follower.paginate(
page, per_page=current_app.config['FLASKY_FOLLOWERS_PER_PAGE'],
error_out=False)
follows = [{'user': item.follower, 'timestamp':item.timestamp}
for item in pagination.items]
return render_template('followers.html', user=user, title='Followers of',
endpoint = '.followers', pagination=pagination,
followers=followers)
這個函數加載並驗證請求的用戶,然後使用之前介紹的技術分頁顯示該用戶的followers關係,由於查詢關注者返回的是Follow實例列表,爲了渲染方便,我們將其轉換成一個新列表,列表中的各元素都包含user
和timestamp
字段
渲染關注者列表的模板可以寫的通用一些,以便能用來渲染關注的用戶列表和被關注的用戶列表,模板接受的參數包括用戶對象、分頁鏈接使用的端點、分頁對象和查詢結果列表
followed_by
端點的實現過程幾乎一樣,唯一的區別在於:用戶列表從user.followed
關係中獲取,傳入的模板的參數也要進行響應調整
followers.html
模板使用兩列表格實現,左邊一列用於顯示用戶名和頭像,右邊一列用於顯示Flask-Moment時間戳