python 35 lines · 6 steps

Building a URL shortener redirect in Flask

A Flask route resolves a short slug, records the click, and redirects to the target URL.

Explained by highlit
1from datetime import datetime
2 
3from flask import Blueprint, abort, redirect, request
4from sqlalchemy import func
5 
6from .extensions import db
7from .models import ShortLink, ClickEvent
8 
9bp = Blueprint("redirects", __name__)
10 
11 
12@bp.route("/<string:slug>")
13def follow(slug):
14 link = ShortLink.query.filter_by(slug=slug).first()
15 if link is None:
16 abort(404)
17 
18 if link.expires_at and link.expires_at < datetime.utcnow():
19 abort(410)
20 
21 link.click_count = ShortLink.click_count + 1
22 link.last_clicked_at = datetime.utcnow()
23 
24 db.session.add(
25 ClickEvent(
26 link_id=link.id,
27 referrer=request.referrer,
28 user_agent=request.user_agent.string,
29 ip_address=request.headers.get("X-Forwarded-For", request.remote_addr),
30 occurred_at=datetime.utcnow(),
31 )
32 )
33 db.session.commit()
34 
35 return redirect(link.target_url, code=301)
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Validate a resource exists and hasn't expired before acting on it, using distinct HTTP codes for each failure.
  2. 2Expressing a counter update as a column arithmetic expression pushes the increment into SQL and avoids read-modify-write races.
  3. 3Capturing request metadata alongside the redirect turns a plain link follow into analytics data.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a URL shortener redirect in Flask — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code