This page demonstrates all the advanced code block features available in Material for MkDocs, including annotations, line highlighting, custom themes, and interactive elements.
defadvanced_data_processor(data_source:str,options:dict)->dict:# Configuration and validation (highlighted)ifnotdata_sourceornotisinstance(options,dict):raiseValueError("Invalid input parameters")# Initialize processing pipelineprocessor=DataProcessor(options)# Important line# Process data in chunks (highlighted section)results=[]forchunkinprocessor.chunk_data(data_source):processed_chunk=processor.transform(chunk)results.append(processed_chunk)# Aggregate and return resultsreturnprocessor.aggregate(results)
# Multi-stage Docker build for productionFROMnode:18-alpineASbuilder#(1)!
WORKDIR/app # (2)!# Copy package filesCOPYpackage*.json./#(3)!
RUNnpmci--only=production#(4)!
# Copy source code and buildCOPY..#(5)!
RUNnpmrunbuild#(6)!
# Production stageFROMnginx:alpine# (7)!# Copy built applicationCOPY--from=builder/app/dist/usr/share/nginx/html#(8)!
# Copy custom nginx configurationCOPYnginx.conf/etc/nginx/nginx.conf#(9)!
EXPOSE80 # (10)!CMD["nginx","-g","daemon off;"]#(11)!
Base Image Selection
Using Node.js 18 Alpine for smaller image size and security.
# Check image sizesdockerimagesnode:18-alpine
dockerimagesnode:18# Compare with full image
Working Directory
Sets the working directory inside the container where all operations will occur.
Package Files First
Copy package files before source code to leverage Docker layer caching:
!!! tip "Docker Layer Caching"
Package files change less frequently than source code, so copying them first allows Docker to cache the npm install step.
Production Dependencies
npm ci is faster and more reliable than npm install for production builds.
Source Code Copy
Copy all source files. Uses .dockerignore to exclude unnecessary files.
Build Process
Compile TypeScript, bundle assets, optimize for production.
Production Server
Nginx Alpine provides a minimal, secure web server for serving static files.
Multi-stage Copy
Copy built assets from builder stage to production stage, keeping final image small.
fromfastapiimportFastAPI,HTTPException,Dependsfromsqlalchemy.ormimportSessionfromtypingimportList,OptionalfrommodelsimportUser,UserCreate,UserResponsefromdatabaseimportget_dbapp=FastAPI(title="User Management API")@app.get("/users/{user_id}",response_model=UserResponse)asyncdefget_user(user_id:str,db:Session=Depends(get_db)):"""Retrieve a specific user by ID."""user=db.query(User).filter(User.id==user_id).first()ifnotuser:raiseHTTPException(status_code=404,detail="User not found")returnuser@app.post("/users/",response_model=UserResponse,status_code=201)asyncdefcreate_user(user_data:UserCreate,db:Session=Depends(get_db)):"""Create a new user."""# Check if user already existsexisting_user=db.query(User).filter(User.email==user_data.email).first()ifexisting_user:raiseHTTPException(status_code=400,detail="Email already registered")# Create new userdb_user=User(**user_data.dict())db.add(db_user)db.commit()db.refresh(db_user)returndb_user@app.get("/users/",response_model=List[UserResponse])asyncdeflist_users(skip:int=0,limit:int=100,active_only:bool=False,db:Session=Depends(get_db)):"""List users with optional filtering."""query=db.query(User)ifactive_only:query=query.filter(User.is_active==True)users=query.offset(skip).limit(limit).all()returnusers
-- Create users table with comprehensive fieldsCREATETABLEusers(idUUIDPRIMARYKEYDEFAULTgen_random_uuid(),emailVARCHAR(255)UNIQUENOTNULL,nameVARCHAR(100)NOTNULL,password_hashVARCHAR(255)NOTNULL,is_activeBOOLEANDEFAULTtrue,is_verifiedBOOLEANDEFAULTfalse,profile_image_urlTEXT,last_login_atTIMESTAMPWITHTIMEZONE,created_atTIMESTAMPWITHTIMEZONEDEFAULTNOW(),updated_atTIMESTAMPWITHTIMEZONEDEFAULTNOW());-- Create optimized indexesCREATEINDEXidx_users_emailONusers(email);CREATEINDEXidx_users_activeONusers(is_active)WHEREis_active=true;CREATEINDEXidx_users_created_atONusers(created_at);-- Create user roles tableCREATETABLEuser_roles(idSERIALPRIMARYKEY,user_idUUIDNOTNULLREFERENCESusers(id)ONDELETECASCADE,role_nameVARCHAR(50)NOTNULL,granted_atTIMESTAMPWITHTIMEZONEDEFAULTNOW(),granted_byUUIDREFERENCESusers(id));-- Create index for role lookupsCREATEINDEXidx_user_roles_user_idONuser_roles(user_id);CREATEINDEXidx_user_roles_role_nameONuser_roles(role_name);-- Add trigger for updated_at timestampCREATEORREPLACEFUNCTIONupdate_updated_at_column()RETURNSTRIGGERAS$$BEGINNEW.updated_at=NOW();RETURNNEW;END;$$language'plpgsql';CREATETRIGGERupdate_users_updated_atBEFOREUPDATEONusersFOREACHROWEXECUTEFUNCTIONupdate_updated_at_column();
importpytestfromfastapi.testclientimportTestClientfromsqlalchemyimportcreate_enginefromsqlalchemy.ormimportsessionmakerfromapi.mainimportappfromdatabaseimportget_db,Base# Test database setupSQLALCHEMY_DATABASE_URL="sqlite:///./test.db"engine=create_engine(SQLALCHEMY_DATABASE_URL,connect_args={"check_same_thread":False})TestingSessionLocal=sessionmaker(autocommit=False,autoflush=False,bind=engine)defoverride_get_db():"""Override database dependency for testing."""try:db=TestingSessionLocal()yielddbfinally:db.close()app.dependency_overrides[get_db]=override_get_dbclient=TestClient(app)@pytest.fixture(autouse=True)defsetup_database():"""Create and clean up test database."""Base.metadata.create_all(bind=engine)yieldBase.metadata.drop_all(bind=engine)deftest_create_user():"""Test user creation endpoint."""user_data={"name":"Test User","email":"test@example.com","password":"testpassword123"}response=client.post("/users/",json=user_data)assertresponse.status_code==201data=response.json()assertdata["email"]==user_data["email"]assertdata["name"]==user_data["name"]assert"id"indataassert"password"notindata# Ensure password is not returneddeftest_get_user():"""Test user retrieval endpoint."""# First create a useruser_data={"name":"Test User","email":"test@example.com","password":"testpassword123"}create_response=client.post("/users/",json=user_data)user_id=create_response.json()["id"]# Then retrieve itresponse=client.get(f"/users/{user_id}")assertresponse.status_code==200data=response.json()assertdata["id"]==user_idassertdata["email"]==user_data["email"]deftest_list_users():"""Test user listing with pagination."""# Create multiple usersforiinrange(5):user_data={"name":f"User {i}","email":f"user{i}@example.com","password":"testpassword123"}client.post("/users/",json=user_data)# Test paginationresponse=client.get("/users/?skip=2&limit=2")assertresponse.status_code==200data=response.json()assertlen(data)==2```</div>### Configuration Files```yamltitle="docker-compose.yml"linenums="1"hl_lines="5-7 12-14 25-27"version:'3.8'services:web:build:context:.dockerfile:Dockerfileports:-"8000:8000"environment:-DATABASE_URL=postgresql://app_user:secure_password@db:5432/app_db-REDIS_URL=redis://redis:6379/0-SECRET_KEY=${SECRET_KEY}-DEBUG=falsedepends_on:db:condition:service_healthyredis:condition:service_startedvolumes:-./logs:/app/logsrestart:unless-stoppednetworks:-app-networkdb:image:postgres:14-alpineenvironment:POSTGRES_DB:app_dbPOSTGRES_USER:app_userPOSTGRES_PASSWORD:secure_passwordvolumes:-postgres_data:/var/lib/postgresql/data-./init.sql:/docker-entrypoint-initdb.d/init.sqlhealthcheck:test:["CMD-SHELL","pg_isready -U app_user -d app_db"]interval:10stimeout:5sretries:5ports:-"5432:5432"networks:-app-networkredis:image:redis:7-alpinecommand:redis-server--appendonlyyesvolumes:-redis_data:/dataports:-"6379:6379"networks:-app-networknginx:image:nginx:alpineports:-"80:80"-"443:443"volumes:-./nginx.conf:/etc/nginx/nginx.conf-./ssl:/etc/nginx/ssldepends_on:-webnetworks:-app-networkvolumes:postgres_data:redis_data:networks:app-network:driver:bridge
classPerformanceMonitor{constructor(options={}){this.metrics=newMap();this.observers=[];// Initialize performance observersif('PerformanceObserver'inwindow){this.initResourceObserver();this.initNavigationObserver();this.initMeasureObserver();this.initLongTaskObserver();}// Configuration optionsthis.config={enableUserTiming:true,enableResourceTiming:true,sampleRate:options.sampleRate||0.1,maxEntries:options.maxEntries||1000,...options};// Automatically collect Core Web Vitalsthis.collectCoreWebVitals();}initResourceObserver(){constobserver=newPerformanceObserver((list)=>{for(constentryoflist.getEntries()){this.recordResourceTiming(entry);}});observer.observe({entryTypes:['resource']});this.observers.push(observer);}initNavigationObserver(){constobserver=newPerformanceObserver((list)=>{for(constentryoflist.getEntries()){this.recordNavigationTiming(entry);}});observer.observe({entryTypes:['navigation']});this.observers.push(observer);}collectCoreWebVitals(){// Largest Contentful Paint (LCP)newPerformanceObserver((entryList)=>{constentries=entryList.getEntries();constlastEntry=entries[entries.length-1];this.recordMetric('LCP',lastEntry.startTime);}).observe({entryTypes:['largest-contentful-paint']});// First Input Delay (FID)newPerformanceObserver((entryList)=>{for(constentryofentryList.getEntries()){constfid=entry.processingStart-entry.startTime;this.recordMetric('FID',fid);}}).observe({entryTypes:['first-input']});// Cumulative Layout Shift (CLS)letclsValue=0;newPerformanceObserver((entryList)=>{for(constentryofentryList.getEntries()){if(!entry.hadRecentInput){clsValue+=entry.value;}}this.recordMetric('CLS',clsValue);}).observe({entryTypes:['layout-shift']});}recordMetric(name,value,labels={}){consttimestamp=performance.now();constmetric={name,value,timestamp,labels,url:window.location.href,userAgent:navigator.userAgent};if(!this.metrics.has(name)){this.metrics.set(name,[]);}constmetrics=this.metrics.get(name);metrics.push(metric);// Limit the number of stored metricsif(metrics.length>this.config.maxEntries){metrics.shift();}// Send to analytics if sample rate allowsif(Math.random()<this.config.sampleRate){this.sendToAnalytics(metric);}}asyncsendToAnalytics(metric){try{awaitfetch('/api/analytics/performance',{method:'POST',headers:{'Content-Type':'application/json',},body:JSON.stringify(metric),keepalive:true});}catch(error){console.warn('Failed to send performance metric:',error);}}getMetrics(name){returnthis.metrics.get(name)||[];}getAllMetrics(){constresult={};for(const[key,value]ofthis.metrics){result[key]=value;}returnresult;}destroy(){// Clean up observersthis.observers.forEach(observer=>observer.disconnect());this.observers=[];this.metrics.clear();}}// Initialize performance monitoringconstperformanceMonitor=newPerformanceMonitor({sampleRate:0.1,maxEntries:500});// Export for global usewindow.performanceMonitor=performanceMonitor;
/* Custom dark theme for code blocks */[data-md-color-scheme="slate"].highlight{background-color:#0d1117;color:#c9d1d9;}[data-md-color-scheme="slate"].highlight.hll{background-color:#1c2128;}[data-md-color-scheme="slate"].highlight.c{color:#8b949e;font-style:italic;}[data-md-color-scheme="slate"].highlight.k{color:#ff7b72;}[data-md-color-scheme="slate"].highlight.s{color:#a5d6ff;}