### Installation Source: https://github.com/mikeckennedy/content-types/blob/main/README.md Install the content-types library using uv. ```bash uv pip install content-types ``` -------------------------------- ### Install Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/INDEX.md Installs the content-types library using pip. ```bash pip install content-types ``` -------------------------------- ### Installation Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Install the content-types library and CLI tool using pip, uv, or pipx. ```bash # Python library pip install content-types # or uv pip install content-types # CLI tool uv tool install content-types # or pipx install content-types ``` -------------------------------- ### CLI Installation Source: https://github.com/mikeckennedy/content-types/blob/main/README.md Install the content-types CLI tool using uv or pipx. ```bash uv tool install content-types ``` -------------------------------- ### CLI Tool Installation Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Install the CLI tool globally using uv or pipx. ```bash # Using uv uv tool install content-types # Or using pipx pipx install content-types ``` -------------------------------- ### CLI Example Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/module-overview.md Shows how to use the content-types package from the command line. ```bash content-types file.jpg ``` -------------------------------- ### Configuration File Types Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Examples of detecting content types for configuration files. ```python get_content_type("config.yaml") # text/yaml get_content_type("settings.toml") # application/toml get_content_type("database.ini") # text/plain get_content_type("environment.env") # text/plain get_content_type("Dockerfile") # text/plain ``` -------------------------------- ### CLI Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/README.md Example of using the content-types command-line interface. ```bash content-types image.jpg ``` -------------------------------- ### FastAPI File Serving Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/usage-examples.md Serve a file with its correct content type using FastAPI. ```python import content_types from fastapi import FastAPI, HTTPException from fastapi.responses import FileResponse from pathlib import Path app = FastAPI() FILES_DIR = Path('files') @app.get("/files/{filename}") async def get_file(filename: str): """Serve file with correct content type.""" filepath = FILES_DIR / filename if not filepath.exists(): raise HTTPException(status_code=404, detail="File not found") mime_type = content_types.get_content_type(filename) return FileResponse( filepath, media_type=mime_type, filename=filename ) ``` -------------------------------- ### Installation and Testing Source: https://github.com/mikeckennedy/content-types/blob/main/WARP.md Installs the package in editable mode and tests the CLI tool. ```bash # Install in editable mode for development pip install -e . # Test the CLI tool content-types example.jpg content-types .webp content-types --help # May not be implemented # Run comparison with Python's built-in mimetypes python samples/compare_to_builtin.py ``` -------------------------------- ### Error Message Example Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Example of the usage message when called without arguments. ```bash Usage: content-types [FILENAME_OR_EXTENSION] Example: content-types .jpg ``` -------------------------------- ### Data Science Workflow Example Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example of using content-types to determine file format for saving DataFrames, with configuration to let the extension decide the format. ```python import content_types import pandas as pd def save_dataframe(df, output_path, format='auto'): if format == 'auto': # Configuration: let extension determine format ext = output_path.split('.')[-1] mime = content_types.get_content_type(output_path) if 'parquet' in mime: df.to_parquet(output_path) elif 'csv' in mime: df.to_csv(output_path) elif 'json' in mime: df.to_json(output_path) ``` -------------------------------- ### Checking the library version Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Demonstrates two ways to retrieve the installed version of the 'content-types' library. ```python import content_types from importlib.metadata import version version_str = version('content-types') print(version_str) # e.g., "0.3.1" # Or directly from the module print(content_types.__version__) ``` -------------------------------- ### File Validation Example Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example of validating file uploads using content-types, with configuration to treat specific files as text. ```python import content_types # Configuration: text files should be treated as text ALLOWED_TYPES = { 'image/png', 'image/jpeg', 'text/csv', content_types.pdf, } def validate_upload(filename): # Configuration: use text fallback for config files mime = content_types.get_content_type( filename, treat_as_binary=False ) return mime in ALLOWED_TYPES ``` -------------------------------- ### Lookup Examples Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/extension-to-content-type.md Provides various examples of looking up MIME types for different file extensions. ```python import content_types # Text and web formats print(content_types.EXTENSION_TO_CONTENT_TYPE['json']) # "application/json" print(content_types.EXTENSION_TO_CONTENT_TYPE['html']) # "text/html" print(content_types.EXTENSION_TO_CONTENT_TYPE['css']) # "text/css" # Images print(content_types.EXTENSION_TO_CONTENT_TYPE['jpg']) # "image/jpeg" print(content_types.EXTENSION_TO_CONTENT_TYPE['png']) # "image/png" print(content_types.EXTENSION_TO_CONTENT_TYPE['webp']) # "image/webp" print(content_types.EXTENSION_TO_CONTENT_TYPE['cr2']) # "image/x-canon-cr2" # Audio & Video print(content_types.EXTENSION_TO_CONTENT_TYPE['mp3']) # "audio/mpeg" print(content_types.EXTENSION_TO_CONTENT_TYPE['flac']) # "audio/flac" print(content_types.EXTENSION_TO_CONTENT_TYPE['mp4']) # "video/mp4" print(content_types.EXTENSION_TO_CONTENT_TYPE['mkv']) # "video/x-matroska" # Programming print(content_types.EXTENSION_TO_CONTENT_TYPE['py']) # "text/x-python" print(content_types.EXTENSION_TO_CONTENT_TYPE['rs']) # "text/x-rust" print(content_types.EXTENSION_TO_CONTENT_TYPE['tsx']) # "text/tsx" print(content_types.EXTENSION_TO_CONTENT_TYPE['sol']) # "text/x-solidity" # Data Science print(content_types.EXTENSION_TO_CONTENT_TYPE['parquet']) # "application/vnd.apache.parquet" print(content_types.EXTENSION_TO_CONTENT_TYPE['ipynb']) # "application/x-ipynb+json" print(content_types.EXTENSION_TO_CONTENT_TYPE['sqlite']) # "application/vnd.sqlite3" ``` -------------------------------- ### When to use treat_as_binary=False Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example of a function to load configuration files, assuming text-based content by setting `treat_as_binary=False`. ```python import content_types # Configuration file processor def load_config(filename): mime = content_types.get_content_type( filename, treat_as_binary=False # Assume text config files ) if mime.startswith('text/'): with open(filename, 'r') as f: return f.read() ``` -------------------------------- ### get_content_type() Parameters Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example demonstrating the `treat_as_binary` parameter's effect on unknown file extensions. ```python import content_types # Default behavior: binary fallback print(content_types.get_content_type("file.unknown")) # "application/octet-stream" # Text fallback print(content_types.get_content_type("file.unknown", treat_as_binary=False)) # "text/plain" ``` -------------------------------- ### Unknown extension Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Example of querying an unknown extension, which defaults to octet-stream. ```bash content-types unknown.xyz # Outputs: application/octet-stream ``` -------------------------------- ### RAW camera formats Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Examples of querying MIME types for RAW camera formats. ```bash content-types photo.cr2 # Outputs: image/x-canon-cr2 content-types photo.nef # Outputs: image/x-nikon-nef content-types photo.dng # Outputs: image/x-adobe-dng ``` -------------------------------- ### Package Management Source: https://github.com/mikeckennedy/content-types/blob/main/WARP.md Installs the package using uv, a recommended package manager. ```bash # Install via uv (recommended in README) uv pip install content-types # Install CLI globally with uv uv tool install content-types ``` -------------------------------- ### Module-Level Defaults Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example showing how to access the library version and the internal MIME type mapping dictionary. ```python import content_types # These are always defined and cannot be modified print(content_types.__version__) # "0.3.1" (from package metadata) print(type(content_types.EXTENSION_TO_CONTENT_TYPE)) # ``` -------------------------------- ### FastAPI Integration Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Example of integrating content type detection with a FastAPI application for file downloads. ```python import content_types from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get("/download/{filename}") def download_file(filename: str): return FileResponse( f"downloads/{filename}", media_type=content_types.get_content_type(filename) ) ``` -------------------------------- ### Archive File Types Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Examples of detecting content types for archive and compression formats. ```python get_content_type("backup.zip") # application/zip get_content_type("archive.tar") # application/x-tar get_content_type("archive.tar.gz") # application/gzip get_content_type("compressed.7z") # application/x-7z-compressed ``` -------------------------------- ### Verify Python Version Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Command-line examples to check the current Python version and assert compatibility with Python 3.10+. ```bash python --version # Python 3.11.5 python -c "import sys; assert sys.version_info >= (3, 10)" # No error: version is compatible ``` -------------------------------- ### Flask File Download Handler Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/usage-examples.md Serve a file with its correct MIME type using Flask. ```python import content_types from flask import Flask, send_file, request, abort from pathlib import Path app = Flask(__name__) UPLOAD_FOLDER = Path('uploads') @app.route('/download/') def download_file(filename): """Serve file with correct MIME type.""" # Security: prevent directory traversal if '..' in filename or '/' in filename: abort(400) filepath = UPLOAD_FOLDER / filename if not filepath.exists(): abort(404) # Get MIME type mime_type = content_types.get_content_type(filename) return send_file( filepath, mimetype=mime_type, as_attachment=True, download_name=filename ) ``` -------------------------------- ### Bash/Zsh alias Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Example of creating a Bash/Zsh alias for the content-types CLI. ```bash alias mime='content-types' # Usage: mime image.jpg ``` -------------------------------- ### Programming languages Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Examples of querying MIME types for programming language files. ```bash content-types code.rs # Outputs: text/x-rust content-types code.go # Outputs: text/x-go content-types component.tsx # Outputs: text/tsx content-types contract.sol # Outputs: text/x-solidity ``` -------------------------------- ### Basic File Type Detection Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Examples of detecting content types for various file extensions. ```python get_content_type("script.py") # text/x-python get_content_type("code.rs") # text/x-rust get_content_type("app.tsx") # text/tsx get_content_type("contract.sol") # text/x-solidity ``` -------------------------------- ### Query with file extension Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Examples of querying MIME types using file extensions. ```bash content-types .jpg # Outputs: image/jpeg content-types webp # Outputs: image/webp ``` -------------------------------- ### Pipeline usage Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Examples of using the content-types CLI in shell pipelines. ```bash # Get extension from file list and look up MIME type ls *.jpg | while read file; do echo "$file: $(content-types "$file")" done # Process multiple files find . -type f | while read file; do ext="${file##*.}" echo "$file is $(content-types "$ext")" done ``` -------------------------------- ### RAW Camera Formats Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Examples of detecting content types for RAW camera image formats. ```python get_content_type("photo.cr2") # image/x-canon-cr2 get_content_type("photo.nef") # image/x-nikon-nef get_content_type("photo.arw") # image/x-sony-arw get_content_type("photo.dng") # image/x-adobe-dng ``` -------------------------------- ### Query with full filename Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Examples of querying MIME types using full filenames. ```bash content-types document.pdf # Outputs: application/pdf content-types data.parquet # Outputs: application/vnd.apache.parquet content-types notebook.ipynb # Outputs: application/x-ipynb+json ``` -------------------------------- ### Runtime Configuration Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example of configuring MIME type lookups at runtime using function parameters, demonstrating the `assume_text` helper. ```python import content_types from pathlib import Path # Configuration through parameters only def configure_mime_lookup(filename, assume_text=False): return content_types.get_content_type( filename, treat_as_binary=not assume_text ) # Usage with different configurations print(configure_mime_lookup("file.txt", assume_text=False)) # text/plain print(configure_mime_lookup("file.txt", assume_text=True)) # application/octet-stream ``` -------------------------------- ### Zero Runtime Dependencies Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example of the `dependencies` field in `pyproject.toml` showing no external runtime dependencies. ```toml # From pyproject.toml dependencies = [] ``` -------------------------------- ### Data science formats Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Examples of querying MIME types for data science formats. ```bash content-types data.parquet # Outputs: application/vnd.apache.parquet content-types analysis.ipynb # Outputs: application/x-ipynb+json content-types config.toml # Outputs: application/toml ``` -------------------------------- ### Django File Download View Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/usage-examples.md Download a file with its correct MIME type using Django. ```python import content_types from django.http import FileResponse from django.core.exceptions import SuspiciousOperation from pathlib import Path def download_file(request, filename): """Download file with correct MIME type.""" # Validate filename if '..' in filename or '/' in filename: raise SuspiciousOperation("Invalid filename") filepath = Path('media') / filename if not filepath.exists(): return HttpResponseNotFound("File not found") # Get MIME type mime_type = content_types.get_content_type(filename) response = FileResponse( open(filepath, 'rb'), content_type=mime_type ) response['Content-Disposition'] = f'attachment; filename="{filename}"' return response ``` -------------------------------- ### Common MIME Types - Audio/Video Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Convenience constants and lookup examples for common audio and video MIME types. ```python content_types.mp3 # audio/mpeg get_content_type("song.flac") # audio/flac get_content_type("movie.mp4") # video/mp4 get_content_type("video.mkv") # video/x-matroska ``` -------------------------------- ### Flask Integration Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Example of integrating content type detection with a Flask application to serve files with correct MIME types. ```python import content_types from flask import Flask, send_file app = Flask(__name__) @app.route('/files/') def serve_file(filename): return send_file( f'uploads/{filename}', mimetype=content_types.get_content_type(filename) ) ``` -------------------------------- ### Django Integration Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Example of integrating content type detection within a Django view for serving files. ```python import content_types from django.http import FileResponse def download_file(request, filename): return FileResponse( open(f'media/{filename}', 'rb'), content_type=content_types.get_content_type(filename) ) ``` -------------------------------- ### Data science formats Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/get_content_type.md Examples for common data science and configuration file formats. ```python import content_types # Scientific and analysis formats print(content_types.get_content_type("data.parquet")) # "application/vnd.apache.parquet" print(content_types.get_content_type("analysis.ipynb")) # "application/x-ipynb+json" print(content_types.get_content_type("matrix.pkl")) # "application/octet-stream" print(content_types.get_content_type("config.yaml")) # "text/yaml" print(content_types.get_content_type("settings.toml")) # "application/toml" ``` -------------------------------- ### When to use treat_as_binary=True (Default) Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example of using `get_content_type` within a Flask route for file downloads, with the default binary fallback. ```python import content_types from flask import send_file @app.route('/download/') def download_file(filename): # Safe default: unknown files treated as binary mime = content_types.get_content_type(filename) return send_file('uploads/' + filename, mimetype=mime) ``` -------------------------------- ### Query with common file types Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Examples of querying MIME types for common file types. ```bash content-types image.png # Outputs: image/png content-types script.py # Outputs: text/x-python content-types config.yaml # Outputs: text/yaml content-types archive.zip # Outputs: application/zip ``` -------------------------------- ### FastAPI Integration Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example of integrating the content-types library with FastAPI to serve files with correct MIME types. ```python import content_types from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get("/files/{filename}") async def get_file(filename: str): # Configuration: use binary fallback (default) mime_type = content_types.get_content_type(filename) return FileResponse(f"uploads/{filename}", media_type=mime_type) ``` -------------------------------- ### Using in shell scripts Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md Example of using the content-types CLI within a bash script. ```bash #!/bin/bash # Get MIME type for a file file="$1" mime_type=$(content-types "$file") echo "The MIME type for $file is: $mime_type" # Use in conditional logic if [ "$(content-types "$file")" == "application/pdf" ]; then echo "This is a PDF file" fi ``` -------------------------------- ### Upload Handler with Validation Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/usage-examples.md Handle file uploads with MIME type validation using Flask. ```python import content_types from flask import Flask, request, jsonify from pathlib import Path app = Flask(__name__) ALLOWED_MIMETYPES = { 'image/jpeg', 'image/png', 'image/webp', 'application/pdf', content_types.json, content_types.csv, } @app.route('/upload', methods=['POST']) def upload_file(): """Upload file with MIME type validation.""" if 'file' not in request.files: return jsonify({'error': 'No file provided'}), 400 file = request.files['file'] if file.filename == '': return jsonify({'error': 'No filename'}), 400 # Validate MIME type mime_type = content_types.get_content_type(file.filename) if mime_type not in ALLOWED_MIMETYPES: return jsonify({ 'error': f'File type not allowed: {mime_type}' }), 400 # Save file file.save(f'uploads/{file.filename}') return jsonify({ 'message': 'File uploaded', 'filename': file.filename, 'mime_type': mime_type }) ``` -------------------------------- ### Flask Integration Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example of integrating the content-types library with Flask to serve files with correct MIME types. ```python import content_types from flask import Flask, send_file app = Flask(__name__) @app.route('/files/') def serve_file(filename): # Configuration: use binary fallback (default) mimetype = content_types.get_content_type(filename) return send_file(f'downloads/{filename}', mimetype=mimetype) ``` -------------------------------- ### Django Integration Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Example of integrating the content-types library with Django to serve files with correct MIME types. ```python import content_types from django.http import FileResponse def download_file(request, filename): # Configuration: use binary fallback (default) mime_type = content_types.get_content_type(filename) file_obj = open(f'media/{filename}', 'rb') return FileResponse(file_obj, content_type=mime_type) ``` -------------------------------- ### CAD & Design File Types Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Examples of detecting content types for CAD and design file formats. ```python get_content_type("model.dwg") # application/acad get_content_type("design.blend") # application/x-blender get_content_type("layout.skp") # application/vnd.sketchup.skp get_content_type("graphic.psd") # image/vnd.adobe.photoshop ``` -------------------------------- ### Common MIME Types - Images Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Convenience constants and lookup examples for common image MIME types. ```python content_types.jpg # image/jpeg content_types.png # image/png content_types.webp # image/webp # Or: get_content_type("image.gif") # image/gif # get_content_type("image.svg") # image/svg+xml ``` -------------------------------- ### Common MIME Types - Documents Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Convenience constants and lookup examples for common document MIME types. ```python content_types.pdf # application/pdf get_content_type("file.docx") # application/vnd.openxmlformats-officedocument.wordprocessingml.document get_content_type("file.xlsx") # application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ``` -------------------------------- ### CLI Usage Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/INDEX.md Shows how to use the command-line interface to get the MIME type of a file. ```bash content-types image.jpg # Outputs: image/jpeg ``` -------------------------------- ### Common MIME Types - Web Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Convenience constants and lookup examples for common web MIME types. ```python content_types.json # application/json content_types.xml # application/xml get_content_type("page.html") # text/html ``` -------------------------------- ### Empty Extensions Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/errors.md Example showing that empty or missing extensions return the fallback without raising exceptions. ```python import content_types # No extension - fallback returned mime = content_types.get_content_type("noextension") print(mime) # "application/octet-stream" mime = content_types.get_content_type("") print(mime) # "application/octet-stream" mime = content_types.get_content_type(".") print(mime) # "application/octet-stream" ``` -------------------------------- ### Programming language files Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/get_content_type.md Examples for getting MIME types of various programming language source files. ```python import content_types # Modern languages print(content_types.get_content_type("script.py")) # "text/x-python" print(content_types.get_content_type("code.rs")) # "text/x-rust" print(content_types.get_content_type("program.go")) # "text/x-go" print(content_types.get_content_type("component.tsx")) # "text/tsx" print(content_types.get_content_type("smartcontract.sol")) # "text/x-solidity" ``` -------------------------------- ### Common file types Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/get_content_type.md Examples of getting MIME types for various common file types including images, documents, and data files. ```python import content_types # Images print(content_types.get_content_type("photo.png")) # "image/png" print(content_types.get_content_type("graphic.svg")) # "image/svg+xml" # Documents print(content_types.get_content_type("document.pdf")) # "application/pdf" print(content_types.get_content_type("report.docx")) # "application/vnd.openxmlformats-officedocument.wordprocessingml.document" # Data files print(content_types.get_content_type("data.parquet")) # "application/vnd.apache.parquet" print(content_types.get_content_type("notebook.ipynb")) # "application/x-ipynb+json" print(content_types.get_content_type("dataset.sql")) # "application/sql" ``` -------------------------------- ### Version Information Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/module-overview.md Code snippets to check the installed version of the content-types package using Python. ```python import content_types print(content_types.__version__) # "0.3.1" # Or using importlib from importlib.metadata import version print(version('content-types')) # "0.3.1" ``` -------------------------------- ### Detect Format and Route Processing Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/usage-examples.md Load data files based on their detected format (e.g., Parquet, CSV, JSON, Excel). ```python import content_types import pandas as pd import json def load_data_file(filepath): """Load data file based on extension.""" mime_type = content_types.get_content_type(filepath) if 'parquet' in mime_type: return pd.read_parquet(filepath) elif 'csv' in mime_type: return pd.read_csv(filepath) elif 'json' in mime_type: with open(filepath) as f: return json.load(f) elif 'xlsx' in mime_type or 'spreadsheet' in mime_type: return pd.read_excel(filepath) else: raise ValueError(f"Unsupported format: {mime_type}") # Usage data = load_data_file('data/sales.parquet') print(data.head()) ``` -------------------------------- ### Common MIME Types - Data Formats Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Convenience constants and lookup examples for common data format MIME types. ```python content_types.parquet # application/vnd.apache.parquet content_types.ipynb # application/x-ipynb+json content_types.yaml # text/yaml content_types.toml # application/toml content_types.sqlite # application/vnd.sqlite3 ``` -------------------------------- ### Unknown Extensions Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/errors.md Example showing that unknown file extensions do not raise exceptions and return a fallback MIME type. ```python import content_types # No exception raised, fallback returned mime = content_types.get_content_type("file.unknownext") print(mime) # "application/octet-stream" # Customize fallback behavior mime = content_types.get_content_type("file.unknownext", treat_as_binary=False) print(mime) # "text/plain" ``` -------------------------------- ### Import Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Import the necessary components from the content_types library. ```python import content_types from content_types import get_content_type, EXTENSION_TO_CONTENT_TYPE ``` -------------------------------- ### Smart File Handler Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/usage-examples.md A class that routes files to appropriate handlers based on their MIME type, using the content_types library to determine the type. ```python import content_types from pathlib import Path class FileHandler: """Route files to appropriate handlers based on MIME type.""" def __init__(self): self.handlers = { 'image/': self._handle_image, 'audio/': self._handle_audio, 'video/': self._handle_video, 'application/pdf': self._handle_pdf, 'text/': self._handle_text, } def handle_file(self, filepath): """Process file based on its MIME type.""" mime_type = content_types.get_content_type(filepath) # Find appropriate handler for mime_prefix, handler in self.handlers.items(): if mime_type.startswith(mime_prefix): return handler(filepath, mime_type) # Default handler return self._handle_unknown(filepath, mime_type) def _handle_image(self, filepath, mime_type): return f"Image processing: {filepath} ({mime_type})" def _handle_audio(self, filepath, mime_type): return f"Audio processing: {filepath} ({mime_type})" def _handle_video(self, filepath, mime_type): return f"Video processing: {filepath} ({mime_type})" def _handle_pdf(self, filepath, mime_type): return f"PDF processing: {filepath} ({mime_type})" def _handle_text(self, filepath, mime_type): return f"Text processing: {filepath} ({mime_type})" def _handle_unknown(self, filepath, mime_type): return f"Unknown format: {filepath} ({mime_type})" # Usage handler = FileHandler() print(handler.handle_file('image.jpg')) # Image processing: image.jpg (image/jpeg) print(handler.handle_file('song.mp3')) # Audio processing: song.mp3 (audio/mpeg) print(handler.handle_file('doc.pdf')) # PDF processing: doc.pdf (application/pdf) ``` -------------------------------- ### Flask Framework Integration Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/README.md Example of integrating the content-types library with Flask for file downloads, using `send_file` and retrieving the MIME type. ```python from flask import send_file import content_types @app.route('/download/') def download(filename): return send_file( f'files/{filename}', mimetype=content_types.get_content_type(filename) ) ``` -------------------------------- ### CLI Missing Argument Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/errors.md Example of calling the CLI without an argument, which exits with code 1 and prints usage. ```bash content-types # Prints: Usage: content-types [FILENAME_OR_EXTENSION] # Prints: Example: content-types .jpg # Exit code: 1 ``` -------------------------------- ### Batch File Processing Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/usage-examples.md Organizes files into directories based on their MIME type category (images, audio, video, applications, text, other). ```python import content_types from pathlib import Path from collections import defaultdict def organize_files(input_dir, output_dir): """Organize files by MIME type category.""" input_path = Path(input_dir) output_path = Path(output_dir) # Create category directories categories = defaultdict(list) for filepath in input_path.rglob('*'): if filepath.is_file(): mime_type = content_types.get_content_type(filepath.name) # Extract category from MIME type if mime_type.startswith('image/'): category = 'images' elif mime_type.startswith('audio/'): category = 'audio' elif mime_type.startswith('video/'): category = 'video' elif mime_type.startswith('application/'): category = 'applications' elif mime_type.startswith('text/'): category = 'text' else: category = 'other' categories[category].append(filepath) # Move files to category directories for category, files in categories.items(): category_dir = output_path / category category_dir.mkdir(parents=True, exist_ok=True) for filepath in files: filepath.rename(category_dir / filepath.name) print(f"Moved {filepath.name} to {category}/") # Usage organize_files('downloads', 'organized') ``` -------------------------------- ### Handle Unknown Extensions Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/INDEX.md Demonstrates how to handle unknown file extensions, showing both binary and text fallbacks. ```python # Binary fallback (default) mime = content_types.get_content_type("file.xyz") # "application/octet-stream" # Text fallback mime = content_types.get_content_type("file.xyz", treat_as_binary=False) # "text/plain" ``` -------------------------------- ### Main API Function Source: https://github.com/mikeckennedy/content-types/blob/main/WARP.md The main function to get the content type of a file. ```python def get_content_type(filename_or_extension: str | Path, treat_as_binary: bool = True) -> str ``` -------------------------------- ### Use Constants Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Use predefined constants for common MIME types. ```python # Direct constants for common types print(content_types.webp) # "image/webp" print(content_types.json) # "application/json" print(content_types.parquet) # "application/vnd.apache.parquet" ``` -------------------------------- ### CLI Usage Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Use the content-types CLI tool to look up MIME types. ```bash content-types image.jpg # Outputs: image/jpeg content-types .webp # Outputs: image/webp content-types data.parquet # Outputs: application/vnd.apache.parquet ``` -------------------------------- ### Exception: None Filename Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/errors.md Example of catching the 'filename cannot be None' exception. ```python import content_types try: result = content_types.get_content_type(None) except Exception as e: print(f"Error: {e}") # Error: filename cannot be None. ``` -------------------------------- ### Basic File Type Validation Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/usage-examples.md Check if a file is an image or a document using its filename. ```python import content_types from pathlib import Path def is_image(filename): """Check if file is an image.""" mime_type = content_types.get_content_type(filename) return mime_type.startswith('image/') def is_document(filename): """Check if file is a document.""" allowed_docs = { 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain', } mime_type = content_types.get_content_type(filename) return mime_type in allowed_docs # Usage print(is_image('photo.jpg')) # True print(is_image('document.pdf')) # False print(is_document('report.docx')) # True ``` -------------------------------- ### Invalid Characters Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/errors.md Example showing that special characters in filenames are handled gracefully. ```python import content_types # Special characters and spaces - still work mime = content_types.get_content_type("my file (1).jpg") print(mime) # "image/jpeg" mime = content_types.get_content_type("file@#$.txt") print(mime) # "text/plain" ``` -------------------------------- ### Handle Unknown Extensions Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Handle unknown file extensions, with options for binary or text fallback. ```python import content_types # Default: binary fallback mime = content_types.get_content_type("file.xyz") # "application/octet-stream" # Custom: text fallback mime = content_types.get_content_type("file.xyz", treat_as_binary=False) # "text/plain" ``` -------------------------------- ### CLI Configuration Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/configuration.md Illustrates the fixed behavior of the CLI tool and how to achieve custom behavior using the Python API. ```bash # CLI has fixed behavior content-types image.jpg # Output: image/jpeg # For custom behavior, use Python: python -c "import content_types; print(content_types.get_content_type('image.jpg', treat_as_binary=False))" ``` -------------------------------- ### Lookup MIME Type Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/quick-reference.md Get the MIME type from a filename, extension, or Path object. ```python # From filename mime = content_types.get_content_type("image.jpg") # "image/jpeg" # From extension mime = content_types.get_content_type(".pdf") # "application/pdf" mime = content_types.get_content_type("png") # "image/png" # From Path object from pathlib import Path mime = content_types.get_content_type(Path("doc.docx")) ``` -------------------------------- ### Usage - Forward lookup Source: https://github.com/mikeckennedy/content-types/blob/main/README.md Perform a forward lookup to get the MIME type for a given filename. ```python import content_types # Forward lookup: filename -> MIME type the_type = content_types.get_content_type("example.jpg") print(the_type) # "image/jpeg" # Works with any supported extension print(content_types.get_content_type("data.parquet")) # "application/vnd.apache.parquet" print(content_types.get_content_type("notebook.ipynb")) # "application/x-ipynb+json" print(content_types.get_content_type("photo.cr2")) # "image/x-canon-cr2" print(content_types.get_content_type("model.blend")) # "application/x-blender" print(content_types.get_content_type("contract.sol")) # "text/x-solidity" # For very common files, you have shortcuts: print(f'Content-Type for webp is {content_types.webp}.') # Content-Type for webp is image/webp. # Data science shortcuts print(content_types.parquet) # "application/vnd.apache.parquet" print(content_types.ipynb) # "application/x-ipynb+json" print(content_types.yaml) # "text/yaml" print(content_types.toml) # "application/toml" # Works with Path objects too from pathlib import Path path = Path("document.pdf") print(content_types.get_content_type(path)) # "application/pdf" ``` -------------------------------- ### Basic usage with filenames Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/get_content_type.md Demonstrates how to get the MIME type using a full filename or just an extension. ```python import content_types # Forward lookup with filename mime_type = content_types.get_content_type("image.jpg") print(mime_type) # "image/jpeg" # Works with just an extension print(content_types.get_content_type(".webp")) # "image/webp" print(content_types.get_content_type("webp")) # "image/webp" ``` -------------------------------- ### Validation Pipeline Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/errors.md Example of a function that validates a file path and retrieves its MIME type. ```python import content_types from pathlib import Path def validate_and_process(file_path): """Validate file and get MIME type.""" # Check file exists if not Path(file_path).exists(): raise FileNotFoundError(f"File not found: {file_path}") # Check not None if file_path is None: raise ValueError("File path cannot be None") # Get MIME type with fallback mime_type = content_types.get_content_type(file_path) return mime_type ``` -------------------------------- ### How to Handle Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/errors.md Example of how to handle the 'filename cannot be None' exception by checking for None before calling the function. ```python import content_types def safe_get_type(filename): if filename is None: return 'application/octet-stream' return content_types.get_content_type(filename) print(safe_get_type(None)) # "application/octet-stream" print(safe_get_type("image.jpg")) # "image/jpeg" ``` -------------------------------- ### Basic Import Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/module-overview.md Demonstrates how to import the entire content_types module and use its exports. ```python import content_types # Use all exports mime = content_types.get_content_type("image.jpg") print(content_types.webp) ``` -------------------------------- ### Command Syntax Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/api-reference/cli.md The basic command syntax for the content-types CLI. ```bash content-types FILENAME_OR_EXTENSION ``` -------------------------------- ### Validate File Type Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/INDEX.md Example of validating if a file is a PDF based on its MIME type. ```python mime = content_types.get_content_type("file.pdf") if "pdf" in mime: print("It's a PDF") ``` -------------------------------- ### Import for Type Hints Source: https://github.com/mikeckennedy/content-types/blob/main/_autodocs/module-overview.md Illustrates importing necessary modules for type hinting when using the get_content_type function. ```python from pathlib import Path import content_types def process_file(path: Path) -> str: """Return MIME type of file.""" return content_types.get_content_type(path) ```