python flask web 博客實例 關(guān)注模塊 3

1 app/models.py
class Follow(db.Model):
tablename = 'follows'
follower_id = db.Column(db.Integer, db.ForeignKey('users.id'),primary_key=True)
followed_id = db.Column(db.Integer, db.ForeignKey('users.id'),primary_key=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
class User(UserMixin, db.Model):
def init(self, **kwargs):
# ...
self.follow(self)
# ...
followed = db.relationship('Follow',foreign_keys=[Follow.follower_id],backref=db.backref('follower', lazy='joined'),lazy='dynamic',cascade='all, delete-orphan')
followers = db.relationship('Follow',foreign_keys=[Follow.followed_id],backref=db.backref('followed', lazy='joined'),lazy='dynamic',cascade='all, delete-orphan')
def follow(self, user):
if not self.is_following(user):
f = Follow(follower=self, followed=user)
db.session.add(f)
def unfollow(self, user):
f = self.followed.filter_by(followed_id=user.id).first()
if f:
db.session.delete(f)
def is_following(self, user):
return self.followed.filter_by(
followed_id=user.id).first() is not None
def is_followed_by(self, user):
return self.followers.filter_by(
follower_id=user.id).first() is not None
@property
def followed_posts(self):
return Post.query.join(Follow, Follow.followed_id == Post.author_id).filter(Follow.follower_id == self.id)
@staticmethod
def add_self_follows():
for user in User.query.all():
if not user.is_following(user):
user.follow(user)
db.session.add(user)
db.session.commit()

2 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 %}

3  app/main/views.py
@app.route('/', methods = ['GET', 'POST'])
def index():
# ...
show_followed = False
if current_user.is_authenticated():
show_followed = bool(request.cookies.get('show_followed', ''))
if show_followed:
query = current_user.followed_posts
else:
query = Post.query
pagination = query.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],error_out=False)
posts = pagination.items
return render_template('index.html', form=form, posts=posts,show_followed=show_followed, pagination=pagination)
@main.route('/follow/<username>')
@login_required
@permission_required(Permission.FOLLOW)
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))
@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.followers.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,follows=follows)
@main.route('/all')
@login_required
def show_all():
resp = make_response(redirect(url_for('.index')))
resp.set_cookie('show_followed', '', max_age=30246060)
return resp
@main.route('/followed')
@login_required
def show_followed():
resp = make_response(redirect(url_for('.index')))
resp.set_cookie('show_followed', '1', max_age=30
246060)
return resp

多對多關(guān)系

image.png

image.png

image.png
image.png

image.png

級聯(lián)查詢

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末难衰,一起剝皮案震驚了整個濱河市逗栽,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌鳄虱,老刑警劉巖凭峡,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異倍踪,居然都是意外死亡索昂,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進店門癞志,熙熙樓的掌柜王于貴愁眉苦臉地迎上來框产,“玉大人,你說我怎么就攤上這事秉宿。” “怎么了膊存?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長今艺。 經(jīng)常有香客問我爵卒,道長,這世上最難降的妖魔是什么钓株? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任轴合,我火速辦了婚禮,結(jié)果婚禮上受葛,老公的妹妹穿的比我還像新娘。我一直安慰自己携栋,他們只是感情好咳秉,可當(dāng)我...
    茶點故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著向挖,像睡著了一般炕舵。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上咽筋,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天奸攻,我揣著相機與錄音,去河邊找鬼睹耐。 笑死,一個胖子當(dāng)著我的面吹牛响委,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播赘风,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼邀窃,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了蛔翅?” 一聲冷哼從身側(cè)響起位谋,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤掏父,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后赊淑,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡钾挟,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年掺出,在試婚紗的時候發(fā)現(xiàn)自己被綠了苫费。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡百框,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出柬泽,到底是詐尸還是另有隱情方椎,我是刑警寧澤,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布琳疏,位于F島的核電站,受9級特大地震影響空盼,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜台汇,卻給世界環(huán)境...
    茶點故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一篱瞎、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧俐筋,春花似錦、人聲如沸笆呆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽榕堰。三九已至屈留,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間灌危,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工沫勿, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留味混,地道東北人。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓蔓挖,卻偏偏與公主長得像馆衔,于是被迫代替她去往敵國和親怨绣。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,969評論 2 355

推薦閱讀更多精彩內(nèi)容