[app.py]
...
@app.route('/stream')
@app.route('/stream/')
def stream(username=None):
template = 'stream.html'
if username and username != current_user.username:
user = models.User.select().where(models.User.username**username).get()
stream = user.posts.limit(100)
template = 'user_stream.html'
else:
stream = current_user.get_stream().limit(100)
user = current_user
if username:
template = "user_stream.html"
return render_template(template, stream=stream, user=user)
@app.route('/')
def index():
stream = models.Post.select().limit(100)
return render_template('stream.html', stream=stream)
current_user.username
LoginManager provides us with the current_user object to quickly access the current logged in user.
user.posts.limit(100)
Gets 100 posts from the user, using the ‘posts’ related name.
.limit(100)
Limits number of selected records to 100. Peewee does have other stuff for pagination.
.where( models.User.username**username )
The ** sign means LIKE, which does a comparison without caring about the case (e.g. Bashar or bashar).
current_user.get_stream()
User method that selects all posts of a certain user, using the user attribute of the Post model.
[stream.html]
{% extends "layout.html" %}
{% block content %}
{% for post in stream %}
<article>
<h2><a href="{{ url_for( 'stream', username=post.user.username ) }}">{{ post.user.username }}</a></h2>
<i class="clock"></i>
<time date-time="{{ post.timestamp }}" class="distime" datetime="
{{ post.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}">{{ post.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}</time>
<a href="#" class="view">View</a>
<div class="post">{{ post.content }}</div>
</article>
{% endfor %}
{% endblock %}
url_for( ‘stream’, username=post.user.username ) }}
How to send an argument to a route of a view, in our case the ‘stream’ view (i.e. /stream/<username>)
{{ post.timestamp }}
Print the timestamp of a post.
{{ post.timestamp.strftime(‘%Y-%m-%d %H:%M:%S’) }}
Print a formated version of post timestamp.
{{ post.content }}
Print post content.