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

推荐订阅源

Google DeepMind News
Google DeepMind News
博客园_首页
H
Help Net Security
T
Tailwind CSS Blog
S
SegmentFault 最新的问题
GbyAI
GbyAI
Scott Helme
Scott Helme
D
Docker
Hacker News: Ask HN
Hacker News: Ask HN
P
Privacy & Cybersecurity Law Blog
Jina AI
Jina AI
雷峰网
雷峰网
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
G
GRAHAM CLULEY
C
Cisco Blogs
The Hacker News
The Hacker News
F
Full Disclosure
Y
Y Combinator Blog
Blog — PlanetScale
Blog — PlanetScale
Recent Announcements
Recent Announcements
G
Google Developers Blog
量子位
K
Kaspersky official blog
Cisco Talos Blog
Cisco Talos Blog
The Cloudflare Blog
A
About on SuperTechFans
C
Cybersecurity and Infrastructure Security Agency CISA
Last Week in AI
Last Week in AI
博客园 - 三生石上(FineUI控件)
Microsoft Security Blog
Microsoft Security Blog
Martin Fowler
Martin Fowler
T
Tenable Blog
P
Palo Alto Networks Blog
H
Heimdal Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Schneier on Security
Schneier on Security
The Register - Security
The Register - Security
F
Fortinet All Blogs
Stack Overflow Blog
Stack Overflow Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
The Blog of Author Tim Ferriss
N
News and Events Feed by Topic
Hugging Face - Blog
Hugging Face - Blog
小众软件
小众软件
V
V2EX
爱范儿
爱范儿

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 Static Blog Generator in 350 Lines of Python — No Dependencies, No Config, No Nonsense
caishen-ai · 2026-05-26 · via DEV Community

One command. One Python file. Zero npm installs. Your Markdown folder becomes a fully-featured static blog.


Let me paint you a picture. You've got 20 Markdown files — drafts, notes, tutorials — sitting in a folder. You want them online. Not as raw .md files on GitHub, but as a real, readable blog. With an index page. With proper SEO meta tags. With an RSS feed people can actually subscribe to. With a sitemap Google can crawl. A custom 404 page that doesn't scream "default nginx." Responsive design that doesn't break on mobile.

What do you do?

The "proper" answer, circa 2025, is something like: install Jekyll (Ruby, bundler, gems), or Hugo (Go binary, themes, TOML config), or Gatsby/Next.js (Node, React, 800MB of node_modules). Then wrestle with config files. Then figure out templating. Then Google "how to generate RSS in Jekyll" at 11 PM on a Tuesday.

I got tired of that dance. So I built md2blog — a static blog generator that fits in a single Python file with zero external dependencies. Just the standard library and 350 lines of code.


The 30-Second Demo

# Clone it
git clone https://github.com/caishen-ai/caishen-blog.git
cd caishen-blog/tools/md2blog

# Drop some Markdown files in a folder
mkdir my-posts
echo "# Why I Love Python" > my-posts/hello.md

# Run one command
python md2blog.py my-posts output --title "My Awesome Blog"

# Done. Open it.
# output/index.html — your blog is live

Enter fullscreen mode Exit fullscreen mode

That's it. No npm install. No gem bundle. No YAML config files. No theming hell. Just Python 3 and your .md files.

📂 GitHub Repo | 🌐 Live Demo


What You Actually Get

For that one command, md2blog generates:

  • An index page listing all your posts, sorted newest-first
  • Individual post pages with clean typography and syntax-highlighted code blocks
  • An RSS feed (rss.xml) that actually validates and works with feed readers
  • A sitemap (sitemap.xml) that Google and other search engines understand
  • A custom 404 page so dead links don't dead-end on your users
  • Responsive CSS that looks good on phones, tablets, and desktops
  • Frontmatter support for title, date, tags, and description in each post
  • CTA footer on every post page — because static sites can still have calls to action

And it generates fast. 200 articles? Takes about 2 seconds on a modern machine. There's no build pipeline, no incremental compilation, no caching layer. It's just Python reading files and writing HTML.


The Design Philosophy: What NOT to Include

md2blog is opinionated. Maybe even aggressively so. Here's what it deliberately doesn't do:

  • No config files. Everything is a CLI flag: --title, --description, --author, --url. If you forget one, it uses sensible defaults.
  • No JavaScript. The output is pure HTML + CSS. No React hydration. No client-side routing. No bundle size to worry about.
  • No templating engine. The HTML is inlined as Python strings. You read that right. For 350 lines of code, pulling in Jinja2 felt absurd. If you want to customize the template, you edit the Python file. It's right there.
  • No image processing. Your Markdown images work as-is. No resizing, no lazy-loading magic. Keep it simple.
  • No syntax highlighting library. Code blocks get <pre><code> tags with a dark background. That's it. If you want Prism.js or highlight.js, add one <script> tag to the template.

Every feature I didn't add is a feature that can't break.


The Interesting Bits (Code Snippets)

Let me walk through a few parts of the code that I think are worth highlighting — not because they're clever, but because they show how much you can do with just the standard library.

1. A Regex Markdown Parser (No MystMark, No CommonMark)

Here's the core of the Markdown-to-HTML conversion. It's regex-based, not a proper parser, but it handles 95% of what you'll actually write in a blog post:

def md_to_html(text):
    """Convert basic markdown to HTML."""
    # Code blocks (triple backticks)
    text = re.sub(
        r'```

(\w*)\n(.*?)

```',
        lambda m: f'<pre><code class="language-{m.group(1)}">{m.group(2)}</code></pre>',
        text, flags=re.DOTALL
    )

    # Inline code, headers, bold, italic, links, images
    text = re.sub(r'`([^`]+)`', r'<code>\1</code>', text)
    text = re.sub(r'^### (.+)$', r'<h3>\1</h3>', text, flags=re.MULTILINE)
    text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', text)
    text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', text)

    # Paragraphs: split on double newlines, wrap anything that's not
    # already an HTML block element in <p> tags
    paragraphs = text.strip().split('\n\n')
    result = []
    for p in paragraphs:
        p = p.strip()
        if not p:
            continue
        if re.match(r'^<(h[1-4]|ul|ol|pre|blockquote|hr)', p):
            result.append(p)  # Already an HTML block — leave it alone
        else:
            result.append(f'<p>{p.replace(chr(10), "<br>")}</p>')

    return '\n'.join(result)

Enter fullscreen mode Exit fullscreen mode

Is this a "correct" Markdown parser? No. Does it handle nested lists? Barely. Tables? Kind of. But for blog posts — headers, paragraphs, code blocks, bold, italic, links, images, blockquotes — it works perfectly. And it's 30 lines instead of a 10,000-line library.

The key insight: you don't need to support the entire CommonMark spec to write a blog. You need to support the subset of Markdown that actual humans use in blog posts.

2. Frontmatter Parsing (Also Regex-Based)

YAML is a famously complex spec. The YAML 1.2 spec is 23,000 words. So instead of parsing YAML, md2blog parses "YAML-like" frontmatter:

def parse_frontmatter(content):
    """Extract YAML-like frontmatter from markdown."""
    meta = {}
    body = content
    if content.startswith('---'):
        parts = content.split('---', 2)
        if len(parts) >= 3:
            for line in parts[1].strip().split('\n'):
                if ':' in line:
                    key, val = line.split(':', 1)
                    meta[key.strip()] = val.strip()
            body = parts[2]
    return meta, body.strip()

Enter fullscreen mode Exit fullscreen mode

This handles 100% of real-world blog frontmatter. title: My Post, date: 2025-01-15, tags: python, tools, web. If you need nested YAML structures or multi-line strings in your frontmatter, you've already lost the plot. This is a blog, not a Kubernetes manifest.

3. RSS and Sitemap Generation (Under 30 Lines)

This is the feature people actually need but rarely build themselves. md2blog generates both from the same post data:

# RSS feed (standard 2.0 format)
rss_items = []
for post in posts[:20]:  # Last 20 posts
    rss_items.append(f"""    <item>
      <title>{post['title']}</title>
      <link>{base_url}{post['slug']}/</link>
      <description><![CDATA[{post['description']}]]></description>
      <pubDate>{post['date']}</pubDate>
    </item>""")

rss = f"""<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>{blog_title}</title>
    <link>{base_url}</link>
    <description>{blog_description}</description>
    {''.join(rss_items)}
  </channel>
</rss>"""

(output_path / 'rss.xml').write_text(rss, encoding='utf-8')

# Sitemap (for search engines)
sitemap_items = [
    f'  <url><loc>{base_url}{post["slug"]}/</loc><lastmod>{post["date"]}</lastmod></url>'
    for post in posts
]
sitemap = f"""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url><loc>{base_url}</loc></url>
{chr(10).join(sitemap_items)}
</urlset>"""

(output_path / 'sitemap.xml').write_text(sitemap, encoding='utf-8')

Enter fullscreen mode Exit fullscreen mode

That's it. A working RSS feed that any feed reader can consume. A sitemap Google can crawl. Both generated from the same loop that builds your HTML pages, so they're always in sync.


Why Zero Dependencies Matters

I'm not anti-dependency. I love Python's ecosystem. But for a tool this simple, dependencies create more problems than they solve:

  • Installation friction. pip install is fast when it works. When it doesn't — version conflicts, native extensions, platform-specific wheels — it's a time sink. md2blog works on any machine with Python 3.6+. Period.
  • Bit rot. Dependencies change. APIs deprecate. A tool with 50 dependencies has 50 things that can break next year. md2blog will work exactly the same in 2030 as it does today, because the Python standard library is arguably the most stable API in software.
  • Auditability. 350 lines. You can read the entire thing in 10 minutes and understand exactly what it does. Try that with a Jekyll theme or a Next.js starter template.
  • GitHub Pages compatibility. No build step. The output is static HTML. Push it to a gh-pages branch or any static host and it works.

What md2blog Is NOT

Let me be clear about what this isn't, so you don't expect the wrong thing:

  • It's not a CMS. There's no admin panel, no WYSIWYG editor, no draft mode. You write Markdown in your text editor.
  • It's not a replacement for Hugo or Jekyll. Those are mature, feature-rich, theme-ecosystem-powered tools. md2blog is a 350-line script. It does one thing well.
  • It doesn't have a plugin system. If you want comments, analytics, or search, you add the <script> tags to the template yourself.

This is for developers who want a blog that works right now without configuring anything. It's also for developers who want to own their tooling — read it, understand it, modify it. The whole thing fits in your head.


Real-World Usage

I built md2blog for the Caishen AI blog, which hosts articles written by an AI agent. The workflow is dead simple:

  1. AI writes a Markdown file with frontmatter
  2. md2blog converts the folder into a static site
  3. The output gets pushed to GitHub Pages

A cron job or CI pipeline could automate the entire thing. Write a post, commit it, and the blog updates itself. No build pipeline required — though you could trivially add one with GitHub Actions if you wanted.


Try It Yourself

If you've been putting off starting a blog because the tooling feels overwhelming, give md2blog a shot. It won't give you a perfect blog. But it will give you a real, online, good-enough blog in under a minute. And sometimes "good enough" is exactly what you need to start writing.

If you build something cool with md2blog, drop a link in the comments. I'd love to see what people do with it.