Passlib Argon2 Password Hashing
Hash passwords with Argon2id through passlib, storing algorithm parameters inline so upgrades rehash transparently on next login.
Page 43 of 50
Hash passwords with Argon2id through passlib, storing algorithm parameters inline so upgrades rehash transparently on next login.
Write files atomically with pathlib by staging content to a temp file in the same directory and renaming over the target on success.
Run Polars lazy frames so predicate pushdown, projection pruning, and streaming execution optimize the plan before any data moves.
Normalize messy form input with Pydantic field validators, trimming strings, coercing digit strings, and rejecting malformed values early.
Describe a request payload with a Pydantic model so types and constraints are enforced and clear validation errors are returned automatically.
Load typed configuration from environment variables with pydantic-settings, layering dotenv files and validating on import.
Watch MongoDB collection changes with PyMongo, persisting resume tokens so listeners recover exactly where they left off after restart.
Share async resources across tests with pytest-asyncio fixtures, scoping engine creation per session and cleaning up deterministically.
Provide a pytest fixture that creates a fresh database per test and tears it down, so tests stay independent and order does not matter.
Configure Python logging with rotation by size and backups, per-module loggers, structured formatting, and a root-level filter guard.
Implement a token bucket that refills at a steady rate and allows short bursts, a standard algorithm for shaping request traffic.
Cache async function results in Redis with a decorator, TTL expiry, single-flight locking, and JSON serialization per call signature.
Connect through Redis Sentinel for automatic failover, detecting role changes, retrying reads on replicas, and fencing split-brain writes.
Decorate a function so transient exceptions are retried a fixed number of times with growing delay, keeping call sites free of retry plumbing.
Render dynamic CLI tables with Rich Live mode, updating rows in place as background tasks progress and finishing with a clean summary.
Generate cryptographically secure tokens with the secrets module, comparing them in constant time and binding usage scope per token.
Throttle FastAPI endpoints with SlowAPI using a Redis backend, per-user limits, custom headers, and exempted internal callers.
Drive async SQLAlchemy sessions with pooled engines, per-request session scopes, and transaction guards that always release connections.
Set per-session isolation levels in SQLAlchemy, using repeatable read for consistent reports and read committed for regular traffic.
Open a SQLite connection as a context manager so transactions commit on success and roll back on error, and the connection always closes.
Define a GraphQL schema with Strawberry on FastAPI, writing typed resolvers for queries and mutations with context dependency injection.
Bind request-scoped context with structlog, so every log line carries correlation fields without threading state through call stacks.
Configure a JSON formatter so every log record carries consistent fields, making logs searchable and correlatable across services.
Guard a flaky dependency with a circuit breaker state machine, falling back to cached defaults and opening after repeated failures.
Compose retry behavior with Tenacity using stop conditions, adaptive wait strategies, custom retry predicates, and typed final errors.
Build async CLI commands with Typer, combining type-annotated options, enum choices, environment fallbacks, and per-command validation.
Configure uvicorn worker shutdown with timeout windows, draining in-flight requests and cancelling background loops cleanly on signals.
Enrich errors with anyhow context layers, converting foreign error types into chains that print root causes and section context.
Hash passwords with argon2id at tuned cost parameters, verifying in constant time with encoded salt and version metadata.
Accept multipart uploads in Axum with per-field size caps, MIME allowlists, and streaming field reads that cap total request bytes.
Stream large responses from an async generator into the response body, applying timeouts per chunk and clean cancellation.
Instrument Axum with a tower middleware layer that measures request durations, stamps request ids, and logs completions.
Build complex values step by step with consuming methods that return Self, so an incomplete configuration cannot be constructed accidentally.
Keep a fixed-capacity least-recently-used cache with the lru crate, evicting the coldest entry and promoting reads automatically.
Define a CLI interface with clap derives so arguments are parsed, validated, and documented from one struct declaration.
Define a clap CLI with typed subcommands, layered defaults, optional config file overrides, and environment variable fallbacks.
Chain pipeline stages with crossbeam bounded channels, applying backpressure from slow consumers and draining on shutdown.
Stream CSV files record by record with the csv crate, validating deserialization per row and quarantining malformed lines.
Implement the Iterator trait to produce a lazy Fibonacci sequence, showing how infinity can be represented without allocating a collection.
Compose application configuration with figment layers, joining TOML files with environment overrides and strict extraction.
Apply the governor quota-based limiter with per-key direct limiters, burst capacity, and 429 responses carrying retry timing.
Execute GraphQL queries from Rust with graphql-client, deriving response types from the query document and variables.
Render multi-stage CLI progress with indicatif: throttled bars, nested stages, log interception, and clean terminal restoration.
Chain iterator adapters to filter, map, and fold a collection lazily, expressing a transformation pipeline without intermediate vectors.
Sign and verify tokens with jsonwebtoken in Rust, validating registered claims, required fields, and clock tolerance windows.
Cache expensive computations with moka in Rust, combining TTL expiry with maximum size, entry metrics, and async loading.
Query large collections through the Rust MongoDB driver with server-side batching, cursor iteration, and aggregation pipelines.
Share mutable counters across threads with Arc for ownership and Mutex for exclusive access, avoiding data races at compile time.
Wrap primitives in newtypes so distinct identifiers and units cannot be mixed, adding validation and methods without runtime cost.
Parallelize CPU-bound aggregation with rayon par_iter, folding partitions independently and reducing partial results safely.
Manage redis-rs async connections with MultiplexedConnection, get_connection timeouts, and pubsub on a dedicated connection.
Subscribe to Redis pubsub channels with a dedicated connection, handling messages by channel name and resuming after drops.
Tune reqwest connection pooling with per-host keepalives, idle timeouts, and layered timeouts for connect, read, and total budgets.
Add retry to reqwest with retry-policies and tower middleware, restricting to idempotent methods and honoring Retry-After.
Return Result from functions and use the question-mark operator to propagate errors, keeping failure paths explicit and composable.
Derive Deserialize to load a configuration from JSON with defaults, rejecting unknown fields so typos in the config surface immediately.
Parse large JSON arrays incrementally with serde_json StreamDeserializer, yielding items as they arrive and isolating bad elements.
Write SQL with compile-time verification against a live PostgreSQL schema, keeping statements typed and migrations versioned.
Retry PostgreSQL serialization failures in sqlx transactions with bounded backoff, replaying the full unit on conflict only.
Model domain errors as thiserror enums with variant payloads, source chaining, and From conversions for ergonomic propagation.
Send messages from producer threads to a consumer over an mpsc channel, letting the receiver drain work without shared mutable state.
Bound async operations with tokio::select over a timeout future, racing work against deadlines and handling branch outcomes.
Cap concurrent tasks with a tokio semaphore through acquire_owned, applying per-key fairness and cleanup on cancellation.
Contain panics in spawned tasks with JoinHandle errors, replacing failed workers and distinguishing cancel from panic outcomes.
Race an async operation against a timer using tokio select!, so a slow future is abandoned cleanly when the deadline fires first.
Split a WebSocket stream into independent sink and stream halves, running concurrent send and receive loops with heartbeats.
Enrich tracing spans with structured field annotations, enter guards for synchronous sections, and follow-from causality links.
Bootstrap tracing with EnvFilter directives, JSON output in production, pretty console in development, and span lifecycle events.
Store heterogeneous implementations behind a Box dyn trait to select behaviour at runtime, trading monomorphisation for flexibility.
Remove duplicate natural keys and keep only the most recent row using a window function and a delete, a common cleanup before adding a unique constraint.
Diagnose slow queries with EXPLAIN ANALYZE and BUFFERS, reading scans, join strategies, and actual row estimates.
Find missing values in an id sequence by comparing each row with the previous one, a common data-integrity audit query.
Read an EXPLAIN plan to confirm whether a query uses the intended index and where a sequential scan or sort is introduced.
Paginate with the seek method on a compound cursor, comparing plans against OFFSET to show why deep pages stay fast.
Detect missing intervals in time series with LAG over generated series, then backfill gaps by carrying the last known value forward.
Compare two nullable columns without nulls silently dropping rows from a WHERE clause, using IS DISTINCT FROM instead of not-equal.
Implement classic offset pagination with a single-pass window count, page metadata, and sane caps on depth and page size.
Paginate with a WHERE clause on the last seen key instead of OFFSET, keeping each page fast and stable as new rows arrive.
Contrast string-interpolated SQL with parameterized statements, allowing safe dynamic ORDER BY through whitelisting.
Pivot monthly revenue by category using conditional aggregation, generating column lists dynamically for any date range.
Turn row values into columns with conditional aggregation, producing a wide report without a dedicated pivot operator.
Serialize critical sections across application instances with advisory locks, scoping by key and releasing on session end.
Index append-only time series with tiny BRIN blocks, comparing size against B-tree for range scans over billions of rows.
Aggregate rows into nested JSONB documents with jsonb_build_object and jsonb_agg, shaping API responses directly in SQL.
Query JSONB documents with containment operators backed by a GIN index, comparing jsonb_path_query for complex predicates.
Fetch the latest N rows per group with a LATERAL join driving an indexed subquery per outer row, avoiding giant windows.
Accelerate dashboards with materialized views, refreshing concurrently without blocking readers and tracking data staleness.
Index only live rows with a partial index over soft-deleted tables, keeping hot queries small and vacuum friendly.
Implement a database-backed sliding window rate limiter, atomically pruning old attempts and checking quota in one statement.
Implement atomic upserts with ON CONFLICT DO UPDATE, targeting partial unique indexes and guarding with WHERE conditions.
Explode product bills of materials with a recursive CTE, multiplying quantities down each assembly path and rolling up costs.
Walk a self-referencing employee table with a recursive CTE to list each person and their management depth from the top.
Walk employee hierarchies with a recursive CTE, tracking depth and reporting paths while avoiding cycles in malformed data.
Deduplicate rows keeping the newest per key with ROW_NUMBER, sweeping duplicates in one statement or blocking them upstream.
Compute a cumulative total per customer with a window frame, a pattern that replaces self-joins or application-side accumulation.
Claim a batch of jobs from a queue by locking only unlocked rows, letting concurrent workers drain the queue without blocking each other.
Insert a row or update it when the unique key already exists, in one atomic statement that avoids a race between read and write.
Compare RANK, DENSE_RANK, and ROW_NUMBER semantics on tied values, picking the right one for leaderboard and quota queries.
Compute per-account running balances with a window function ordered by transaction time, including partition isolation.
Classify async failures into retryable and fatal buckets, retrying only transient errors with backoff while surfacing permanent ones.