Back
+20 XP
Concept

Serving Static Assets, MIME Types & Cache-Control

Web browsers demand accurate MIME types to render CSS and JS. The `mimetypes` module inspects file extensions to determine `Content-Type`, paired with `Cache-Control` headers for performance 🚀.

python
import mimetypes

# Guess MIME types automatically:
css_type, _ = mimetypes.guess_type("bundle.css")
svg_type, _ = mimetypes.guess_type("logo.svg")
wasm_type, _ = mimetypes.guess_type("engine.wasm")

print(f"CSS: {css_type} 🎨")    # text/css
print(f"SVG: {svg_type} 🖼️")    # image/svg+xml
print(f"WASM: {wasm_type} ⚡")  # application/wasm

# 39. Serving Static Assets, MIME Types & Cache-Control Web browsers demand accurate MIME types to render CSS and JS. The `mimetypes` module inspects file extensions to determine `Content-Type`, paired with `Cache-Control` headers for performance 🚀. ```python import mimetypes # Guess MIME types automatically: css_type, _ = mimetypes.guess_type("bundle.css") svg_type, _ = mimetypes.guess_type("logo.svg") wasm_type, _ = mimetypes.guess_type("engine.wasm") print(f"CSS: {css_type} 🎨") # text/css print(f"SVG: {svg_type} 🖼️") # image/svg+xml print(f"WASM: {wasm_type} ⚡") # application/wasm ``` Always send `Cache-Control: public, max-age=31536000, immutable` for hashed asset bundles to eliminate unnecessary repeat downloads! 🚀 --- ### Question Why will modern browsers refuse to execute a JavaScript file if the server returns `Content-Type: text/plain`? 🧠 - [ ] a. Strict MIME-type security checking blocks script execution unless served with a valid JS MIME type 🚀 - [ ] b. Text files are automatically deleted by the browser - [ ] c. JavaScript requires binary encoding - [ ] d. It triggers a 404 error in the operating system --- ### Challenge Import `mimetypes`. Guess the MIME type of `"index.html"` and `"main.js"`. Print both MIME types. 🎯 <details> <summary>Solution</summary> ```python import mimetypes html_type, _ = mimetypes.guess_type("index.html") js_type, _ = mimetypes.guess_type("main.js") print(html_type) print(js_type) ``` </details>

Checkpoint

Why will modern browsers refuse to execute a JavaScript file if the server returns `Content-Type: text/plain`? 🧠

Practice

Import `mimetypes`. Guess the MIME type of `"index.html"` and `"main.js"`. Print both MIME types. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks