python flask web 博客实例 关注模块 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) %}
class="btn btn-primary">Follow
{% else %}
class="btn btn-default">Unfollow
{% endif %}
{% endif %}

Followers: {{ user.followers.count() }}


Following: {{ user.followed.count() }}

{% if current_user.is_authenticated() and user != current_user and
user.is_following(current_user) %}
| Follows you
{% 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/')
@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/')
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

多对多关系

python flask web 博客实例 关注模块 3_第1张图片
image.png

python flask web 博客实例 关注模块 3_第2张图片
image.png

python flask web 博客实例 关注模块 3_第3张图片
image.png
python flask web 博客实例 关注模块 3_第4张图片
image.png

python flask web 博客实例 关注模块 3_第5张图片
image.png

级联查询

python flask web 博客实例 关注模块 3_第6张图片
image.png

你可能感兴趣的:(python flask web 博客实例 关注模块 3)