sql
bookmark_border
The queries using the most total time (needs the pg_stat_statements extension).
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT round(total_exec_time::numeric, 1) AS total_ms,
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
advanced
#postgres #performance #monitoring
bash
bookmark_border
See what is filling the disk.
df -h / # how full is the disk?
du -xh / 2>/dev/null | sort -rh | head -20 # biggest folders on this filesystem
find /var/log -type f -size +100M -exec ls -lh {} \; # big log files
journalctl --disk-usage # systemd journal size
beginner
#linux #disk #admin
javascript
bookmark_border
Let Intl format currency, numbers and dates instead of string hacks.
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const euros = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
const date = new Intl.DateTimeFormat("en-GB", { dateStyle: "medium" });
const ago = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
beginner
#intl #i18n #formatting
python
bookmark_border
Use the secrets module (never random) for passwords, tokens and reset links.
import secrets
import string
reset_token = secrets.token_urlsafe(32) # for links: /reset/<token>
api_key = "pk_" + secrets.token_hex(24)
beginner
#security #secrets #auth
javascript
bookmark_border
Build an object of arrays with reduce (works everywhere, unlike Object.groupBy).
const orders = [
{ customer: "ada", total: 30 },
{ customer: "linus", total: 12 },
{ customer: "ada", total: 8 },
];
beginner
#arrays #data #objects
python
bookmark_border
Turn a flat list into a dict of lists with collections.defaultdict.
from collections import defaultdict
orders = [
{"customer": "ada", "total": 30},
{"customer": "linus", "total": 12},
beginner
#collections #dict #data
flask
bookmark_border
Return JSON instead of HTML for API errors.
from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException
app = Flask(__name__)
beginner
#api #errors #json
sql
bookmark_border
Page through big tables without the slowdown of large OFFSET values.
-- first page
SELECT id, title, created_at FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20;
intermediate
#pagination #performance
flask
bookmark_border
Answer 401 JSON instead of redirecting to the login page.
from functools import wraps
from flask import jsonify
from flask_login import current_user
intermediate
#auth #decorators #api
flask
bookmark_border
Paginate with Flask-SQLAlchemy and keep page numbers safe.
from flask import request, render_template
@bp.get("/posts")
def posts():
beginner
#sqlalchemy #pagination #database
flask
bookmark_border
Stop brute-force attempts with Flask-Limiter.
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(key_func=get_remote_address, storage_uri="memory://") # use redis:// in production
limiter.init_app(app)
beginner
#security #rate-limit #login
python
bookmark_border
Read rows as dicts and write a filtered copy with csv.DictWriter.
import csv
import io
source = io.StringIO("name,score\nada,91\nlinus,78\ngrace,88\n") # use open("in.csv") for a file
rows = [row for row in csv.DictReader(source) if int(row["score"]) >= 80]
beginner
#csv #files #data
css
bookmark_border
Turn animations off for people who asked their system for less motion.
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
beginner
#accessibility #animation
html
bookmark_border
Serve the right size and format, and avoid layout shift.
<picture>
<source type="image/webp"
srcset="/img/hero-640.webp 640w, /img/hero-1280.webp 1280w, /img/hero-1920.webp 1920w"
sizes="(max-width: 700px) 100vw, 1200px">
<img src="/img/hero-1280.jpg"
beginner
#images #performance
sql
bookmark_border
Cumulative revenue per day with SUM() OVER.
SELECT day,
revenue,
SUM(revenue) OVER (ORDER BY day) AS running_total
FROM (
SELECT created_at::date AS day, SUM(total) AS revenue
intermediate
#window-functions #reports
javascript
bookmark_border
Process many async jobs, but only N at a time.
async function mapLimit(items, limit, worker) {
const results = new Array(items.length);
let next = 0;
async function lane() {
while (next < items.length) {
advanced
#async #promises #performance
bash
bookmark_border
Find where something is used, ignoring virtualenvs and builds.
grep -rn --include='*.py' "def create_app" .
grep -rn --exclude-dir={.git,.venv,node_modules,dist} "TODO" .
git grep -n "url_for('main.blog')" # only tracked files, very fast
beginner
#grep #search #git
flask
bookmark_border
Put the token in a meta tag and send it as X-CSRFToken from JavaScript.
# base.html
# <meta name="csrf-token" content="{{ csrf_token() }}">
# app.py
from flask_wtf import CSRFProtect
beginner
#csrf #security #javascript