惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
S
Securelist
V
Vulnerabilities – Threatpost
C
Cyber Attacks, Cyber Crime and Cyber Security
Schneier on Security
Schneier on Security
Cyberwarzone
Cyberwarzone
Simon Willison's Weblog
Simon Willison's Weblog
Hacker News - Newest:
Hacker News - Newest: "LLM"
P
Palo Alto Networks Blog
T
Troy Hunt's Blog
SecWiki News
SecWiki News
Security Archives - TechRepublic
Security Archives - TechRepublic
T
The Blog of Author Tim Ferriss
Project Zero
Project Zero
Microsoft Security Blog
Microsoft Security Blog
The Register - Security
The Register - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
J
Java Code Geeks
F
Full Disclosure
阮一峰的网络日志
阮一峰的网络日志
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Attack and Defense Labs
Attack and Defense Labs
Know Your Adversary
Know Your Adversary
WordPress大学
WordPress大学
PCI Perspectives
PCI Perspectives
N
News | PayPal Newsroom
The Last Watchdog
The Last Watchdog
酷 壳 – CoolShell
酷 壳 – CoolShell
P
Privacy & Cybersecurity Law Blog
P
Proofpoint News Feed
V
Visual Studio Blog
C
CERT Recently Published Vulnerability Notes
H
Help Net Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
云风的 BLOG
云风的 BLOG
月光博客
月光博客
T
The Exploit Database - CXSecurity.com
I
InfoQ
大猫的无限游戏
大猫的无限游戏
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
U
Unit 42
腾讯CDC
小众软件
小众软件
V2EX - 技术
V2EX - 技术
罗磊的独立博客
Cloudbric
Cloudbric
Recorded Future
Recorded Future
IT之家
IT之家
Google DeepMind News
Google DeepMind News
C
CXSECURITY Database RSS Feed - CXSecurity.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
I Built a URL Shortener in a Week.
Om Kolhapure · 2026-06-14 · via DEV Community

Weeks 1 through 5 had a new concept every day.

Week 6 was different. One project. Six days. Start to finish.

The goal: build a URL shortener — something like bit.ly — entirely from scratch, in Python, without any web framework, database, or tutorial to follow. Design it first, build it, add analytics, write a README, ship it to GitHub, share it publicly, and improve it from feedback.

This week taught me more about how software actually gets made than any single concept lesson so far.


Day 36 — Design Before Code

The first day had no code at all.

Before touching the editor, I had to answer six questions on paper and write them up as a design document. This felt strange. I wanted to start building. But forcing myself to write Design.txt first changed how confidently I coded for the rest of the week.

Design Doc For URL Shortner

1. What it does?
-> The URL Shortner takes long URLs for e.g. https://www.examplesite.com/s?k=#435 
and converts it into a Short URL for e.g. bit.ly/5345. The URL shortner
also records the date of when the URL was generated.

2. The Data Model for each URL:
-> Each URL Will be stored as:
{
    "long_url": "https://www.examplesite.com/s?k=#435",
    "short_code": "5345",
    "created_at": "2026-11-21"
}

3. API (What users can do):
POST/long_URL(Server takes the long url and generates a short code)
GET/short_code(When a user visits the short URL, the system looks up the code 
and redirects them to the original long URL.)
Basically this is what user can do:
1. Shorten a URL
User sends: {"url": "https://very-long-link.com"}
System returns: {"short_url": "my.ly/abc123"}
2. Visit a short URL
User clicks my.ly/abc123
System looks up abc123, finds the long URL, sends user there

4. Storage method:
-> I am using JSON as a Storage method because, I am familiar with it and I 
have used JSON format in many projects. I know there are other efficient ways 
like using a database but, I am more familiar with JSON's.

5. Short Code Generation:
-> I wil use Python's random module to generate 6 characters
   I will check if the code already exists
   if the code exists I will generate it again.

6. Edge Cases:
-> Duplicate Code: Check before Saving
   Missing Code: Return "URL not found" message
   Invalid URL: Check if the URL starts with "http"
   Duplicate Long URL: If the same long URL is submitted again, I will return 
   the existing short code instead of creating a new one.

Six questions. Six answers. Before writing a single line of code.

What this gave me: I knew exactly what classes I needed, what data I was storing, what edge cases to handle, and what the user experience would feel like — before I had to think about syntax. Every day after this one was faster because of it.

The "API" section isn't a real HTTP API — this is a CLI tool. But thinking in terms of POST (shorten a URL) and GET (retrieve the original) gave the design clarity that made the functions obvious when I got there.


Day 37 — Building the CLI: JSON Storage & Core Logic

Day 37 was the main build. Everything in the design doc became Python.

The whole project lives in one class — Url — plus two standalone helper functions for reading and writing the JSON file. Here's the complete code:

import json
import random
import time
import os
import csv

class Url:

    def __init__(self, long_url):
        self.long_url = long_url
        self.short_code = None
        self.visit_counter = None
        self.created_at = time.ctime()

    def store_data(self):
        '''Saves the long_url, short_code, created_at in a dictionary'''
        data = {
            "long_url": self.long_url,
            "short_code": self.short_code,
            "created_at": self.created_at
        }
        return data

    def visit(self):
        '''implements the notion of clicking on the url'''
        self.visit_counter = 0
        while True:
            user_response = input("Do you want to visit the short URL?(yes/no): ").strip().lower()
            if user_response in ("yes", "no"):
                break
        if user_response == "yes":
            self.visit_counter += 1
            return self.visit_counter
        else:
            return

    def most_clicked(self, url):
        '''Stores the click counter with its long url in a csv file'''
        if not self.visit():
            report_data = []
            if os.path.exists("clicked_report.csv"):
                with open("clicked_report.csv") as data_file:
                    reader = csv.DictReader(data_file)
                    for row in reader:
                        report_data.append(row)
                for row_data in report_data:
                    if row_data['url'].strip() == url:
                        row_data['clicks'] = str(int(row_data['clicks']) + 1)
                with open("clicked_report.csv", "w", newline = "") as edit_file:
                    file_writer = csv.DictWriter(edit_file, fieldnames = ["url", "clicks"], lineterminator = "\n")
                    file_writer.writeheader()
                    file_writer.writerows(report_data)
                return
            with open("clicked_report.csv", "a", newline = "") as report_file:
                writer = csv.DictWriter(report_file, fieldnames = ["url", "clicks"], lineterminator = "\n")
                writer.writeheader()
                writer.writerow({"url": url, "clicks": self.visit_counter})


    def generate_code(self):
        urls = retrieve_urls()
        ls = "abcdefghijklmnopqrstuvwxyz0123456789"
        while True:
            code = "" 
            for _ in range(6):
                code += random.choice(ls)
            if code not in urls:
                self.short_code = code
                return self.short_code

    def shorten_url(self):
        data = retrieve_urls()
        for code, info in data.items():
            if info['long_url'] == self.long_url:
                self.short_code = info['short_code']
                print(f"URL already exists: bit.ly/{self.short_code}")
                self.visit()
                self.most_clicked(self.long_url)
                return 

        self.generate_code()
        print(f"bit.ly/{self.short_code}")
        self.visit()
        self.most_clicked(self.long_url)
        #Save to file
        data[self.short_code] = self.store_data()
        store_urls(data)


def main():
    while True:
        user_input = input("Enter URL: ").strip()
        if user_input.startswith("https://") or user_input.startswith("http://"):
            break
    url = Url(user_input)
    url.shorten_url()


def store_urls(url_data):
    with open("urls.json", "w") as file:
        json.dump(url_data, file, indent = 4)

def retrieve_urls():
    if os.path.exists("urls.json"):
        with open("urls.json") as urls_file:
            return json.load(urls_file)
    else:
        return {}


if __name__ == "__main__":
    main()

Four methods, two helpers, one data file. Let me walk through the logic of each piece.

generate_code()

ls = "abcdefghijklmnopqrstuvwxyz0123456789"
while True:
    code = "" 
    for _ in range(6):
        code += random.choice(ls)
    if code not in urls:
        self.short_code = code
        return self.short_code

36 characters (26 letters + 10 digits), 6 positions: that's 36⁶ = 2,176,782,336 possible codes. The while True loop keeps generating until it finds one that doesn't already exist in urls.json. In practice, for any reasonable number of URLs, this will succeed on the first try every time — but the collision check is there because the design doc said it should be.

shorten_url() — deduplication

for code, info in data.items():
    if info['long_url'] == self.long_url:
        self.short_code = info['short_code']
        print(f"URL already exists: bit.ly/{self.short_code}")
        return

Before generating anything, scan every stored URL and check if this long URL already has a code. If it does, return the existing one instead of creating a duplicate. This was edge case #4 from the design doc, and handling it here meant the rest of the program never has to think about it.

store_urls() and retrieve_urls()

def store_urls(url_data):
    with open("urls.json", "w") as file:
        json.dump(url_data, file, indent = 4)

def retrieve_urls():
    if os.path.exists("urls.json"):
        with open("urls.json") as urls_file:
            return json.load(urls_file)
    else:
        return {}

These are standalone functions rather than class methods — they don't belong to any single URL, they belong to the whole storage system. Keeping them outside the class makes that boundary clear. retrieve_urls() returns an empty dict if the file doesn't exist yet, so the first run works without any setup.

The stored JSON looks like this:

{
    "a3k9m2": {
        "long_url": "https://very-long-link.com/page?id=12345",
        "short_code": "a3k9m2",
        "created_at": "Wed Jun 10 14:32:05 2026"
    }
}


Day 38 — Analytics: Tracking Clicks in CSV

Day 38 added the analytics layer. The most_clicked() method and visit() work together to track how many times each URL is visited and write that data to clicked_report.csv.

The most_clicked() method handles three scenarios:

  1. First ever click on any URLclicked_report.csv doesn't exist yet, so create it and write the first row
  2. URL already in the report — read the file, find the row, increment the click count, rewrite the file
  3. New URL, report already exists — append a new row
def most_clicked(self, url):
    '''Stores the click counter with its long url in a csv file'''
    if not self.visit():
        report_data = []
        if os.path.exists("clicked_report.csv"):
            with open("clicked_report.csv") as data_file:
                reader = csv.DictReader(data_file)
                for row in reader:
                    report_data.append(row)
            for row_data in report_data:
                if row_data['url'].strip() == url:
                    row_data['clicks'] = str(int(row_data['clicks']) + 1)
            with open("clicked_report.csv", "w", newline = "") as edit_file:
                file_writer = csv.DictWriter(edit_file, fieldnames = ["url", "clicks"], lineterminator = "\n")
                file_writer.writeheader()
                file_writer.writerows(report_data)
            return
        with open("clicked_report.csv", "a", newline = "") as report_file:
            writer = csv.DictWriter(report_file, fieldnames = ["url", "clicks"], lineterminator = "\n")
            writer.writeheader()
            writer.writerow({"url": url, "clicks": self.visit_counter})

The click report ends up looking like this:

url,clicks
https://very-long-link.com/page?id=12345,3
https://github.com/Omk4314/progress-on-python,1

The read-modify-rewrite pattern for the CSV is the same one from Week 4's expense tracker — read everything into memory as a list of dicts, find the row to change, update it in memory, rewrite the whole file. That pattern showing up again in a completely new project confirmed that it had actually stuck.


Day 39 — README & GitHub

Day 39 was about making the project usable by someone who has never seen your code.

Writing a good README is harder than it sounds. I had to think about:

  • What does this do? (for someone who doesn't know me)
  • How do I run it? (exact commands, step by step)
  • What will they see? (concrete example output)
  • What format is the data stored in?

The README I wrote covers all of that. Here's the usage section:

$ python url_shortener.py
Enter URL: https://very-long-link.com/page?id=12345
bit.ly/a3k9m2
Do you want to visit the short URL?(yes/no): yes

And the data storage format section shows exactly what goes into urls.json and clicked_report.csv — so anyone reading the README knows what to expect without running the code first.

The repository is live:
👉 github.com/Omk4314/progress-on-python


Day 40 — Sharing & Getting Feedback

Day 40 was the most uncomfortable day of the whole month.

I posted the project publicly and asked strangers to review my code. Reddit's r/learnpython, Twitter, Discord communities. The verification criterion for this day: at least 3 people reviewed your code and you fixed something.

What I was nervous about: people pointing out everything wrong.
What actually happened: people were genuinely helpful.

The feedback I received:

  • The most_clicked() logic was fragile — if visit() returned None (user said "no"), the if not self.visit() check would call visit() again, prompting the user a second time. The condition and the call should be separated.
  • The Design.txt file being in the root directory instead of inside the url-shortner/ folder was inconsistent.
  • Suggested adding a list all URLs command and a delete command to make it a fuller CLI tool.

Sharing publicly when you're a beginner is uncomfortable. But the code review feedback was more precise and more useful than anything I could have gotten from reviewing my own work. Other people see things you've been looking at too long to notice.


Day 41 — Refactoring From Feedback

Day 41 was about taking the feedback and making the code better.

The most important fix: the double-call bug in most_clicked(). The original code called self.visit() inside the condition and then relied on self.visit_counter being set, but if the user said "no" to visiting, visit() returned None and the condition if not self.visit() triggered — which called visit() again. The fix is to call visit() once, store the result, and branch on that:

# Before (buggy)
if not self.visit():
    # ...

# After (correct)
clicked = self.visit()
if clicked:
    # user said yes — counter is set
else:
    # user said no — update existing record

I also added if __name__ == "__main__": to the main entry point — it was already there but I made sure it was at the very bottom of the file where it belongs, not accidentally inside a block.

The refactor made me re-read the whole file carefully for the first time since writing it. That rereading itself was valuable — I spotted two places where variable names were inconsistent and fixed those too.


📁 What I Built This Week

Project File Concepts Used
Design Document url-shortner/Design.txt Planning, data model, API design, edge cases
URL Shortener url-shortner/url_shortner.py OOP, JSON storage, CSV analytics, random, time, os
README url-shortner/README.md Documentation, usage examples, setup instructions

All the code is on GitHub — every week, every file:
👉 github.com/Omk4314/progress-on-python


What Actually Clicked This Week

  • Design before code is not wasted time. Every function I wrote on Day 37 mapped directly to something in Design.txt. When you know what you're building, the syntax becomes the easy part.
  • Edge cases are features, not afterthoughts. Writing them down on Day 36 meant they were handled on Day 37 — not discovered on Day 40 when someone else ran the program.
  • One project for a whole week goes deeper than one concept per day. By Day 39 I understood every line of the file. By Day 41 I could explain why each decision was made.
  • Public code review is uncomfortable and worth it. Nobody was cruel. Everyone was constructive. And the double-call bug I wouldn't have caught alone got spotted immediately.
  • time.ctime() gives a human-readable timestamp in one call. Small find, genuinely useful.
  • 36⁶ possible codes is more than 2 billion. I worked that out while writing the design doc. It's the kind of thinking you only do when you plan before building.

What I Want to Learn Next

Week 7 has some clear targets:

  • pytest — I want to write real automated tests, not just main() with print statements. The refactor week taught me how easy it is to break things you thought were working.
  • APIs — the URL shortener is a CLI tool now. The natural extension is making it serve HTTP requests. That means Flask or FastAPI, which means web.
  • Databases — I chose JSON for storage because I know it. But the design doc itself acknowledged there are better options. SQLite is the obvious next step.
  • Virtual environments and pip properly — the URL shortener uses only standard library modules, but the moment I add Flask that changes.

Six weeks in. I've gone from "Hello, World!" to a working URL shortener with click analytics and a public README. The gap between where I started and where I am now is genuinely hard to believe from the inside.

If you've built something this week — anything — put it in the comments. A URL shortener, a to-do app, a calculator. Share it. Ask for feedback. The worst that happens is someone helps you.

See you in Week 7. 🐍


Week 6 complete. First real project shipped. Code review survived. Still going.