Build an activity feed with Flask
A basic understanding of Flask and HTML is needed to follow this tutorial.
A great way to track what users are doing in your application is to visualise their activities in a feed. This would be especially useful when creating a dashboard for your application.
In this tutorial, I will show you how to build a quick and easy realtime activity feed using Python (Flask), JavaScript and Pusher Channels. We will build a realtime blog, and a feed page which will show user activity from the blog.
Here is what the final app will look like:
Prerequisites
To follow along properly, basic knowledge of Python, Flask and JavaScript (ES6 syntax) is needed. You will also need to install Python and virtualenv locally.
Virtualenv is a tool that helps us create isolated Python environments. This makes it possible for us to install dependencies (like Flask) in an isolated environment, and not pollute our global packages directory. To install virtualenv:
pip install virtualenv
Setup and Configuration
Installing Flask
As stated earlier, we will be developing using Flask, a web framework for Python. In this step, we will activate a virtual Python environment and install Flask for use in our project.
To activate a virtual environment:
mkdir realtime-feed
cd realtime-feed
virtualenv .venv
source .venv/bin/activate
To install Flask:
pip install flask
Setting up Pusher
Pusher is a service that makes it easy for us to supercharge our web and mobile applications with realtime updates. We will be using the Channels API primarily to power our realtime blog and activity feed. Head over to Pusher.com and register for a free account, if you don’t already have one.
Next, create a Channels app on the dashboard and copy out the app credentials (App ID, Key, Secret and Cluster), as we would be needing these in our app.
Now we can install the Pusher Python library to help our backend communicate with the Pusher service:
pip install pusher
File and Folder Structure
Here is the folder structure for the app. We will only limit it to things necessary so as to avoid bloat:
├── realtime-feed
├── app.py
└── templates
├── index.html
└── feed.html
The templates folder contains our HTML files, while app.py
will house all our server-side code. One of the great things about Flask is how it allows you to set up small web projects with minimal code and very few files.
Building the backend
Next, we will write some code to display our pages and handle requests from our app. We will use Pusher to handle the management of data sent to our backend. We will broadcast events, with corresponding data on a channel, and listen for these events in our app.
Let us start by importing the needed modules and configuring the Pusher object:
# ./app.py
from flask import Flask, render_template, request, jsonify
from pusher import Pusher
import uuid
# create flask app
app = Flask(__name__)
# configure pusher object
pusher = Pusher(
app_id='YOUR_APP_ID',
key='YOUR_APP_KEY',
secret='YOUR_APP_SECRET',
cluster='YOUR_APP_CLUSTER',
ssl=True
)
In the code above, we initialise the Pusher object with the credentials gotten from the Pusher dashboard. Remember to replace YOUR_APP_ID
and similar values with the actual values for your own app.
Next we define the different routes in our app for handling requests. Updating app.py
:
# ./app.py
# index route, shows index.html view
@app.route('/')
def index():
return render_template('index.html')
# feed route, shows feed.html view
@app.route('/feed')
def feed():
return render_template('feed.html')
The first 2 routes defined serve our two app views. The index
(or home) page which shows the blog, and the feed
page which shows the activity feed.
Note: The
render_template()
function renders a template from the template folder.
Now we can define API endpoints for interacting with the blog posts:
# ./app.py
# store post
@app.route('/post', methods=['POST'])
def addPost():
data = {
'id': "post-{}".format(uuid.uuid4().hex),
'title': request.form.get('title'),
'content': request.form.get('content'),
'status': 'active',
'event_name': 'created'
}
pusher.trigger("blog", "post-added", data)
return jsonify(data)
# deactivate or delete post
@app.route('/post/<id>', methods=['PUT','DELETE'])
def updatePost(id):
data = { 'id': id }
if request.method == 'DELETE':
data['event_name'] = 'deleted'
pusher.trigger("blog", "post-deleted", data)
else:
data['event_name'] = 'deactivated'
pusher.trigger("blog", "post-deactivated", data)
return jsonify(data)
The endpoints defined above broadcast events for various actions (storing posts, deactivating posts, deleting posts) via Pusher.
We use the configured pusher
object for broadcasting events on specific channels. To broadcast an event, we use the trigger()
method with the following syntax:
pusher.trigger('a_channel', 'an_event', {'some': 'data'})
Note: You can find the docs for the Pusher Python library here.
Pusher also grants us the ability to trigger events on various types of channels including Public, Private and Presence channels. Read about them here.
Finally, to start the app in debug mode:
# ./app.py
# run Flask app in debug mode
app.run(debug=True)
You can find the full app.py
file here. In the next step, we will build the views for our app.
Creating Our App Views
The blog page
This will serve as the homepage, and is where our users will interact with blog posts (creating, deactivating and deleting them). In the index.html
file:
<!-- ./templates/index.html -->
<html>
<head>
<title>Home!</title>
<!-- import Bulma CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.0/css/bulma.min.css">
<!-- custom styles -->
<style>
#post-list .card {
margin-bottom: 10px;
}
#post-list .card.deactivated {
opacity: 0.5;
cursor: not-allowed;
}
</style>
</head>
<body>
<section class="section">
<div class="container">
<h1 class="title">Realtime Blog</h1>
<p class="subtitle">Realtime blog built with <strong><a href="https://pusher.com" target="_blank">Pusher</a></strong>!</p>
<div class="columns">
<div class="column">
<form id="post-form">
<div class="field">
<label class="label">Title</label>
<div class="control">
<input name="title" class="input" type="text" placeholder="Hello world">
</div>
</div>
<div class="field">
<label class="label">Content</label>
<div class="control">
<textarea class="textarea" name="content" rows="10" cols="10"></textarea>
</div>
</div>
<div class="field">
<button class="button is-primary">Submit</button>
</div>
</form>
</div>
<div class="column">
<div id="post-list"></div>
</div>
</div>
</div>
</section>
</body>
</html>
The above code contains the basic markup for the homepage. We imported Bulma (a cool CSS framework) to take advantage of some pre-made styles.
Next, we will define some JavaScript functions to handle our app functions and communicate with our backend:
<!-- ./templates/index.html -->
<!-- // ... -->
<script>
const form = document.querySelector('#post-form');
// makes POST request to store blog post on form submit
form.onsubmit = e => {
e.preventDefault();
fetch("/post", {
method: 'POST',
body: new FormData(form)
})
.then(r => {
form.reset();
});
}
// makes DELETE request to delete a post
function deletePost(id) {
fetch(`/post/${id}`, {
method: 'DELETE'
});
}
// makes PUT request to deactivate a post
function deactivatePost(id) {
fetch(`/post/${id}`, {
method: 'PUT'
});
}
// appends new posts to the list of blog posts on the page
function appendToList(data) {
const html = `
<div class="card" id="${data.id}">
<header class="card-header">
<p class="card-header-title">${data.title}</p>
</header>
<div class="card-content">
<div class="content">
<p>${data.content}</p>
</div>
</div>
<footer class="card-footer">
<a href="#" onclick="deactivatePost('${data.id}')" class="card-footer-item">Deactivate</a>
<a href="#" onclick="deletePost('${data.id}')" class="card-footer-item">Delete</a>
</footer>
</div>`;
let list = document.querySelector("#post-list")
list.innerHTML += html;
};
</script>
</body>
</html>
We make use of the JavaScript Fetch API to make AJAX requests to our backend. While this is great because the API is simple to use, note that it requires a polyfill for older browsers. A great alternative is axios.
Now that we have established communication with our backend, we can listen for events from Pusher, using the Pusher JavaScript client library:
<!-- ./templates/index.html -->
<!-- // ... -->
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script>
// configure pusher
const pusher = new Pusher('YOUR_APP_KEY', {
cluster: 'YOUR_APP_CLUSTER', // gotten from Pusher app dashboard
encrypted: true // optional
});
// subscribe to `blog` public channel
const channel = pusher.subscribe('blog');
channel.bind('post-added', data => {
appendToList(data);
});
channel.bind('post-deleted', data => {
const post = document.querySelector(`#${data.id}`);
post.parentNode.removeChild(post);
});
channel.bind('post-deactivated', data => {
const post = document.querySelector(`#${data.id}`);
post.classList.add('deactivated');
});
// ...
</script>
</body>
</html>
In the code block above, we import the Pusher JavaScript client library, subscribe to the channel (blog
) on which we’re publishing events from our backend, and listen for those events.
We bind
the various events we’re listening for on the channel. The bind()
method has the following syntax – channel.bind(event_name, callback_function)
. We’re listening for 3 events on the blog view - post-added
, post-deleted
and post``-deactivated
.
Now that we have finished building the blog page, we can proceed to create the feed page and listen for the same set of events.
The feed page
Finally we will build a simple page to display the events being triggered from our blog.
In the feed.html
file:
<!-- ./templates/feed.html -->
<html>
<head>
<title>Activity Feed</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.0/css/bulma.min.css">
</head>
<body>
<section class="section">
<div class="container">
<h1 class="title">Blog Realtime Activity Feed!</h1>
<div id="events"></div>
</div>
</section>
<!-- import Pusher-js library -->
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script>
// connect to Pusher
const pusher = new Pusher('YOUR_APP_KEY', {
cluster: 'YOUR_APP_CLUSTER', // gotten from Pusher app dashboard
encrypted: true // optional
});
// subscribe to blog channel
const channel = pusher.subscribe('blog');
// listen for relevant events
channel.bind('post-added', eventHandler);
channel.bind('post-deleted', eventHandler);
channel.bind('post-deactivated', eventHandler);
// handler function to show feed of events
function eventHandler (data) {
const html = `
<div class="box">
<article class="media">
<div class="media-content">
<div class="content">
<p>
<strong>Post ${data.event_name}</strong>
<small>
<i class="fa fa-${ data.event_name == 'created'
? `plus`
: data.event_name == 'deactivated' ? `ban` : `trash`
}"></i>
</small>
<br>
Post with ID [<strong>${data.id}</strong>] has been ${data.event_name}
</p>
</div>
</div>
</article>
</div>`;
let list = document.querySelector("#events")
list.innerHTML += html;
}
</script>
</body>
</html>
In the code above, we define an eventHandler()
function which acts as callback for all the events we’re listening for. The function simply gets the event which was triggered and lists it as seen in the image below:
And that’s it! To run our app:
python app.py
Conclusion
In a few easy steps, we have been able to build both a realtime blog page, and an activity feed to show events happening on the blog — this shows how well Pusher works with Flask for creating quick realtime applications.
There are many other use cases for adding realtime functionality to Python applications. Do you have any more improvements, suggestions or use cases? Let us know in the comments!
24 January 2018
by Olayinka Omole