repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ageitgey/face_recognition | https://github.com/ageitgey/face_recognition/blob/2e2dccea9dd0ce730c8d464d0f67c6eebb40c9d1/examples/facerec_from_video_file.py | examples/facerec_from_video_file.py | import face_recognition
import cv2
# This is a demo of running face recognition on a video file and saving the results to a new video file.
#
# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.
# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this
# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.
# Open the input movie file
input_movie = cv2.VideoCapture("hamilton_clip.mp4")
length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))
# Create an output movie file (make sure resolution/frame rate matches input video!)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
output_movie = cv2.VideoWriter('output.avi', fourcc, 29.97, (640, 360))
# Load some sample pictures and learn how to recognize them.
lmm_image = face_recognition.load_image_file("lin-manuel-miranda.png")
lmm_face_encoding = face_recognition.face_encodings(lmm_image)[0]
al_image = face_recognition.load_image_file("alex-lacamoire.png")
al_face_encoding = face_recognition.face_encodings(al_image)[0]
known_faces = [
lmm_face_encoding,
al_face_encoding
]
# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
frame_number = 0
while True:
# Grab a single frame of video
ret, frame = input_movie.read()
frame_number += 1
# Quit when the input video file ends
if not ret:
break
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_frame = frame[:, :, ::-1]
# Find all the faces and face encodings in the current frame of video
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
# See if the face is a match for the known face(s)
match = face_recognition.compare_faces(known_faces, face_encoding, tolerance=0.50)
# If you had more than 2 faces, you could make this logic a lot prettier
# but I kept it simple for the demo
name = None
if match[0]:
name = "Lin-Manuel Miranda"
elif match[1]:
name = "Alex Lacamoire"
face_names.append(name)
# Label the results
for (top, right, bottom, left), name in zip(face_locations, face_names):
if not name:
continue
# Draw a box around the face
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
# Draw a label with a name below the face
cv2.rectangle(frame, (left, bottom - 25), (right, bottom), (0, 0, 255), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)
# Write the resulting image to the output video file
print("Writing frame {} / {}".format(frame_number, length))
output_movie.write(frame)
# All done!
input_movie.release()
cv2.destroyAllWindows()
| python | MIT | 2e2dccea9dd0ce730c8d464d0f67c6eebb40c9d1 | 2026-01-04T14:39:09.099486Z | false |
ageitgey/face_recognition | https://github.com/ageitgey/face_recognition/blob/2e2dccea9dd0ce730c8d464d0f67c6eebb40c9d1/examples/facerec_ipcamera_knn.py | examples/facerec_ipcamera_knn.py | """
This is an example of using the k-nearest-neighbors (KNN) algorithm for face recognition.
When should I use this example?
This example is useful when you wish to recognize a large set of known people,
and make a prediction for an unknown person in a feasible computation time.
Algorithm Description:
The knn classifier is first trained on a set of labeled (known) faces and can then predict the person
in a live stream by finding the k most similar faces (images with closet face-features under euclidean distance)
in its training set, and performing a majority vote (possibly weighted) on their label.
For example, if k=3, and the three closest face images to the given image in the training set are one image of Biden
and two images of Obama, The result would be 'Obama'.
* This implementation uses a weighted vote, such that the votes of closer-neighbors are weighted more heavily.
Usage:
1. Prepare a set of images of the known people you want to recognize. Organize the images in a single directory
with a sub-directory for each known person.
2. Then, call the 'train' function with the appropriate parameters. Make sure to pass in the 'model_save_path' if you
want to save the model to disk so you can re-use the model without having to re-train it.
3. Call 'predict' and pass in your trained model to recognize the people in a live video stream.
NOTE: This example requires scikit-learn, opencv and numpy to be installed! You can install it with pip:
$ pip3 install scikit-learn
$ pip3 install numpy
$ pip3 install opencv-contrib-python
"""
import cv2
import math
from sklearn import neighbors
import os
import os.path
import pickle
from PIL import Image, ImageDraw
import face_recognition
from face_recognition.face_recognition_cli import image_files_in_folder
import numpy as np
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'JPG'}
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False):
"""
Trains a k-nearest neighbors classifier for face recognition.
:param train_dir: directory that contains a sub-directory for each known person, with its name.
(View in source code to see train_dir example tree structure)
Structure:
<train_dir>/
├── <person1>/
│ ├── <somename1>.jpeg
│ ├── <somename2>.jpeg
│ ├── ...
├── <person2>/
│ ├── <somename1>.jpeg
│ └── <somename2>.jpeg
└── ...
:param model_save_path: (optional) path to save model on disk
:param n_neighbors: (optional) number of neighbors to weigh in classification. Chosen automatically if not specified
:param knn_algo: (optional) underlying data structure to support knn.default is ball_tree
:param verbose: verbosity of training
:return: returns knn classifier that was trained on the given data.
"""
X = []
y = []
# Loop through each person in the training set
for class_dir in os.listdir(train_dir):
if not os.path.isdir(os.path.join(train_dir, class_dir)):
continue
# Loop through each training image for the current person
for img_path in image_files_in_folder(os.path.join(train_dir, class_dir)):
image = face_recognition.load_image_file(img_path)
face_bounding_boxes = face_recognition.face_locations(image)
if len(face_bounding_boxes) != 1:
# If there are no people (or too many people) in a training image, skip the image.
if verbose:
print("Image {} not suitable for training: {}".format(img_path, "Didn't find a face" if len(face_bounding_boxes) < 1 else "Found more than one face"))
else:
# Add face encoding for current image to the training set
X.append(face_recognition.face_encodings(image, known_face_locations=face_bounding_boxes)[0])
y.append(class_dir)
# Determine how many neighbors to use for weighting in the KNN classifier
if n_neighbors is None:
n_neighbors = int(round(math.sqrt(len(X))))
if verbose:
print("Chose n_neighbors automatically:", n_neighbors)
# Create and train the KNN classifier
knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance')
knn_clf.fit(X, y)
# Save the trained KNN classifier
if model_save_path is not None:
with open(model_save_path, 'wb') as f:
pickle.dump(knn_clf, f)
return knn_clf
def predict(X_frame, knn_clf=None, model_path=None, distance_threshold=0.5):
"""
Recognizes faces in given image using a trained KNN classifier
:param X_frame: frame to do the prediction on.
:param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.
:param model_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.
:param distance_threshold: (optional) distance threshold for face classification. the larger it is, the more chance
of mis-classifying an unknown person as a known one.
:return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].
For faces of unrecognized persons, the name 'unknown' will be returned.
"""
if knn_clf is None and model_path is None:
raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")
# Load a trained KNN model (if one was passed in)
if knn_clf is None:
with open(model_path, 'rb') as f:
knn_clf = pickle.load(f)
X_face_locations = face_recognition.face_locations(X_frame)
# If no faces are found in the image, return an empty result.
if len(X_face_locations) == 0:
return []
# Find encodings for faces in the test image
faces_encodings = face_recognition.face_encodings(X_frame, known_face_locations=X_face_locations)
# Use the KNN model to find the best matches for the test face
closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)
are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]
# Predict classes and remove classifications that aren't within the threshold
return [(pred, loc) if rec else ("unknown", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]
def show_prediction_labels_on_image(frame, predictions):
"""
Shows the face recognition results visually.
:param frame: frame to show the predictions on
:param predictions: results of the predict function
:return opencv suited image to be fitting with cv2.imshow fucntion:
"""
pil_image = Image.fromarray(frame)
draw = ImageDraw.Draw(pil_image)
for name, (top, right, bottom, left) in predictions:
# enlarge the predictions for the full sized image.
top *= 2
right *= 2
bottom *= 2
left *= 2
# Draw a box around the face using the Pillow module
draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255))
# There's a bug in Pillow where it blows up with non-UTF-8 text
# when using the default bitmap font
name = name.encode("UTF-8")
# Draw a label with a name below the face
text_width, text_height = draw.textsize(name)
draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 255), outline=(0, 0, 255))
draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255))
# Remove the drawing library from memory as per the Pillow docs.
del draw
# Save image in open-cv format to be able to show it.
opencvimage = np.array(pil_image)
return opencvimage
if __name__ == "__main__":
print("Training KNN classifier...")
classifier = train("knn_examples/train", model_save_path="trained_knn_model.clf", n_neighbors=2)
print("Training complete!")
# process one frame in every 30 frames for speed
process_this_frame = 29
print('Setting cameras up...')
# multiple cameras can be used with the format url = 'http://username:password@camera_ip:port'
url = 'http://admin:admin@192.168.0.106:8081/'
cap = cv2.VideoCapture(url)
while 1 > 0:
ret, frame = cap.read()
if ret:
# Different resizing options can be chosen based on desired program runtime.
# Image resizing for more stable streaming
img = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
process_this_frame = process_this_frame + 1
if process_this_frame % 30 == 0:
predictions = predict(img, model_path="trained_knn_model.clf")
frame = show_prediction_labels_on_image(frame, predictions)
cv2.imshow('camera', frame)
if ord('q') == cv2.waitKey(10):
cap.release()
cv2.destroyAllWindows()
exit(0)
| python | MIT | 2e2dccea9dd0ce730c8d464d0f67c6eebb40c9d1 | 2026-01-04T14:39:09.099486Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/run.py | run.py | #!/usr/bin/env python3
"""
🚀 N8N Workflows Search Engine Launcher
Start the advanced search system with optimized performance.
"""
import sys
import os
import argparse
def print_banner():
"""Print application banner."""
print("🚀 n8n-workflows Advanced Search Engine")
print("=" * 50)
def check_requirements() -> bool:
"""Check if required dependencies are installed."""
missing_deps = []
try:
import sqlite3
except ImportError:
missing_deps.append("sqlite3")
try:
import uvicorn
except ImportError:
missing_deps.append("uvicorn")
try:
import fastapi
except ImportError:
missing_deps.append("fastapi")
if missing_deps:
print(f"❌ Missing dependencies: {', '.join(missing_deps)}")
print("💡 Install with: pip install -r requirements.txt")
return False
print("✅ Dependencies verified")
return True
def setup_directories():
"""Create necessary directories."""
directories = ["database", "static", "workflows"]
for directory in directories:
os.makedirs(directory, exist_ok=True)
print("✅ Directories verified")
def setup_database(force_reindex: bool = False, skip_index: bool = False) -> str:
"""Setup and initialize the database."""
from workflow_db import WorkflowDatabase
db_path = "database/workflows.db"
print(f"🔄 Setting up database: {db_path}")
db = WorkflowDatabase(db_path)
# Skip indexing in CI mode or if explicitly requested
if skip_index:
print("⏭️ Skipping workflow indexing (CI mode)")
stats = db.get_stats()
print(f"✅ Database ready: {stats['total']} workflows")
return db_path
# Check if database has data or force reindex
stats = db.get_stats()
if stats["total"] == 0 or force_reindex:
print("📚 Indexing workflows...")
index_stats = db.index_all_workflows(force_reindex=True)
print(f"✅ Indexed {index_stats['processed']} workflows")
# Show final stats
final_stats = db.get_stats()
print(f"📊 Database contains {final_stats['total']} workflows")
else:
print(f"✅ Database ready: {stats['total']} workflows")
return db_path
def start_server(host: str = "127.0.0.1", port: int = 8000, reload: bool = False):
"""Start the FastAPI server."""
print(f"🌐 Starting server at http://{host}:{port}")
print(f"📊 API Documentation: http://{host}:{port}/docs")
print(f"🔍 Workflow Search: http://{host}:{port}/api/workflows")
print()
print("Press Ctrl+C to stop the server")
print("-" * 50)
# Configure database path
os.environ["WORKFLOW_DB_PATH"] = "database/workflows.db"
# Start uvicorn with better configuration
import uvicorn
uvicorn.run(
"api_server:app",
host=host,
port=port,
reload=reload,
log_level="info",
access_log=False, # Reduce log noise
)
def main():
"""Main entry point with command line arguments."""
sys.stdout.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="N8N Workflows Search Engine",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python run.py # Start with default settings
python run.py --port 3000 # Start on port 3000
python run.py --host 0.0.0.0 # Accept external connections
python run.py --reindex # Force database reindexing
python run.py --dev # Development mode with auto-reload
""",
)
parser.add_argument(
"--host", default="127.0.0.1", help="Host to bind to (default: 127.0.0.1)"
)
parser.add_argument(
"--port", type=int, default=8000, help="Port to bind to (default: 8000)"
)
parser.add_argument(
"--reindex", action="store_true", help="Force database reindexing"
)
parser.add_argument(
"--dev", action="store_true", help="Development mode with auto-reload"
)
parser.add_argument(
"--skip-index",
action="store_true",
help="Skip workflow indexing (useful for CI/testing)",
)
args = parser.parse_args()
# Also check environment variable for CI mode
ci_mode = os.environ.get("CI", "").lower() in ("true", "1", "yes")
skip_index = args.skip_index or ci_mode
print_banner()
# Check dependencies
if not check_requirements():
sys.exit(1)
# Setup directories
setup_directories()
# Setup database
try:
setup_database(force_reindex=args.reindex, skip_index=skip_index)
except Exception as e:
print(f"❌ Database setup error: {e}")
sys.exit(1)
# Start server
try:
start_server(host=args.host, port=args.port, reload=args.dev)
except KeyboardInterrupt:
print("\n👋 Server stopped!")
except Exception as e:
print(f"❌ Server error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/test_workflows.py | test_workflows.py | #!/usr/bin/env python3
"""
Test Sample Workflows
Validate that our upgraded workflows are working properly
"""
import json
from pathlib import Path
def test_sample_workflows():
"""Test sample workflows to ensure they're working"""
print("🔍 Testing sample workflows...")
samples = []
categories = ["Manual", "Webhook", "Schedule", "Http", "Code"]
for category in categories:
category_path = Path("workflows") / category
if category_path.exists():
workflow_files = list(category_path.glob("*.json"))[
:2
] # Test first 2 from each category
for workflow_file in workflow_files:
try:
with open(workflow_file, "r", encoding="utf-8") as f:
data = json.load(f)
# Validate basic structure
has_name = "name" in data and data["name"]
has_nodes = "nodes" in data and isinstance(data["nodes"], list)
has_connections = "connections" in data and isinstance(
data["connections"], dict
)
samples.append(
{
"file": str(workflow_file),
"name": data.get("name", "Unnamed"),
"nodes": len(data.get("nodes", [])),
"connections": len(data.get("connections", {})),
"has_name": has_name,
"has_nodes": has_nodes,
"has_connections": has_connections,
"valid": has_name and has_nodes and has_connections,
"category": category,
}
)
except Exception as e:
samples.append(
{
"file": str(workflow_file),
"error": str(e),
"valid": False,
"category": category,
}
)
print(f"\n📊 Tested {len(samples)} sample workflows:")
print("=" * 60)
valid_count = 0
for sample in samples:
if sample["valid"]:
print(
f"✅ {sample['name']} ({sample['category']}) - {sample['nodes']} nodes, {sample['connections']} connections"
)
valid_count += 1
else:
print(
f"❌ {sample['file']} - Error: {sample.get('error', 'Invalid structure')}"
)
print(f"\n🎯 Result: {valid_count}/{len(samples)} workflows are valid and ready!")
# Category breakdown
category_stats = {}
for sample in samples:
category = sample.get("category", "unknown")
if category not in category_stats:
category_stats[category] = {"valid": 0, "total": 0}
category_stats[category]["total"] += 1
if sample["valid"]:
category_stats[category]["valid"] += 1
print("\n📁 Category Breakdown:")
for category, stats in category_stats.items():
success_rate = (
(stats["valid"] / stats["total"]) * 100 if stats["total"] > 0 else 0
)
print(f" {category}: {stats['valid']}/{stats['total']} ({success_rate:.1f}%)")
return valid_count, len(samples)
if __name__ == "__main__":
valid_count, total_count = test_sample_workflows()
if valid_count == total_count:
print("\n🎉 ALL SAMPLE WORKFLOWS ARE VALID! 🎉")
elif valid_count > total_count * 0.8:
print(f"\n✅ Most workflows are valid ({valid_count}/{total_count})")
else:
print(f"\n⚠️ Some workflows need attention ({valid_count}/{total_count})")
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/workflow_db.py | workflow_db.py | #!/usr/bin/env python3
"""
Fast N8N Workflow Database
SQLite-based workflow indexer and search engine for instant performance.
"""
import sqlite3
import json
import os
import datetime
import hashlib
from typing import Dict, List, Any, Optional, Tuple
from pathlib import Path
class WorkflowDatabase:
"""High-performance SQLite database for workflow metadata and search."""
def __init__(self, db_path: str = None):
# Use environment variable if no path provided
if db_path is None:
db_path = os.environ.get("WORKFLOW_DB_PATH", "workflows.db")
self.db_path = db_path
self.workflows_dir = "workflows"
self.init_database()
def init_database(self):
"""Initialize SQLite database with optimized schema and indexes."""
conn = sqlite3.connect(self.db_path)
conn.execute("PRAGMA journal_mode=WAL") # Write-ahead logging for performance
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA cache_size=10000")
conn.execute("PRAGMA temp_store=MEMORY")
# Create main workflows table
conn.execute("""
CREATE TABLE IF NOT EXISTS workflows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
workflow_id TEXT,
active BOOLEAN DEFAULT 0,
description TEXT,
trigger_type TEXT,
complexity TEXT,
node_count INTEGER DEFAULT 0,
integrations TEXT, -- JSON array
tags TEXT, -- JSON array
created_at TEXT,
updated_at TEXT,
file_hash TEXT,
file_size INTEGER,
analyzed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Create FTS5 table for full-text search
conn.execute("""
CREATE VIRTUAL TABLE IF NOT EXISTS workflows_fts USING fts5(
filename,
name,
description,
integrations,
tags,
content=workflows,
content_rowid=id
)
""")
# Create indexes for fast filtering
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_trigger_type ON workflows(trigger_type)"
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_complexity ON workflows(complexity)"
)
conn.execute("CREATE INDEX IF NOT EXISTS idx_active ON workflows(active)")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_node_count ON workflows(node_count)"
)
conn.execute("CREATE INDEX IF NOT EXISTS idx_filename ON workflows(filename)")
# Create triggers to keep FTS table in sync
conn.execute("""
CREATE TRIGGER IF NOT EXISTS workflows_ai AFTER INSERT ON workflows BEGIN
INSERT INTO workflows_fts(rowid, filename, name, description, integrations, tags)
VALUES (new.id, new.filename, new.name, new.description, new.integrations, new.tags);
END
""")
conn.execute("""
CREATE TRIGGER IF NOT EXISTS workflows_ad AFTER DELETE ON workflows BEGIN
INSERT INTO workflows_fts(workflows_fts, rowid, filename, name, description, integrations, tags)
VALUES ('delete', old.id, old.filename, old.name, old.description, old.integrations, old.tags);
END
""")
conn.execute("""
CREATE TRIGGER IF NOT EXISTS workflows_au AFTER UPDATE ON workflows BEGIN
INSERT INTO workflows_fts(workflows_fts, rowid, filename, name, description, integrations, tags)
VALUES ('delete', old.id, old.filename, old.name, old.description, old.integrations, old.tags);
INSERT INTO workflows_fts(rowid, filename, name, description, integrations, tags)
VALUES (new.id, new.filename, new.name, new.description, new.integrations, new.tags);
END
""")
conn.commit()
conn.close()
def get_file_hash(self, file_path: str) -> str:
"""Get MD5 hash of file for change detection."""
hash_md5 = hashlib.md5()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def format_workflow_name(self, filename: str) -> str:
"""Convert filename to readable workflow name."""
# Remove .json extension
name = filename.replace(".json", "")
# Split by underscores
parts = name.split("_")
# Skip the first part if it's just a number
if len(parts) > 1 and parts[0].isdigit():
parts = parts[1:]
# Convert parts to title case and join with spaces
readable_parts = []
for part in parts:
# Special handling for common terms
if part.lower() == "http":
readable_parts.append("HTTP")
elif part.lower() == "api":
readable_parts.append("API")
elif part.lower() == "webhook":
readable_parts.append("Webhook")
elif part.lower() == "automation":
readable_parts.append("Automation")
elif part.lower() == "automate":
readable_parts.append("Automate")
elif part.lower() == "scheduled":
readable_parts.append("Scheduled")
elif part.lower() == "triggered":
readable_parts.append("Triggered")
elif part.lower() == "manual":
readable_parts.append("Manual")
else:
# Capitalize first letter
readable_parts.append(part.capitalize())
return " ".join(readable_parts)
def analyze_workflow_file(self, file_path: str) -> Optional[Dict[str, Any]]:
"""Analyze a single workflow file and extract metadata."""
try:
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
except (json.JSONDecodeError, UnicodeDecodeError) as e:
print(f"Error reading {file_path}: {str(e)}")
return None
filename = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
file_hash = self.get_file_hash(file_path)
# Extract basic metadata
workflow = {
"filename": filename,
"name": self.format_workflow_name(filename),
"workflow_id": data.get("id", ""),
"active": data.get("active", False),
"nodes": data.get("nodes", []),
"connections": data.get("connections", {}),
"tags": data.get("tags", []),
"created_at": data.get("createdAt", ""),
"updated_at": data.get("updatedAt", ""),
"file_hash": file_hash,
"file_size": file_size,
}
# Use JSON name if available and meaningful, otherwise use formatted filename
json_name = data.get("name", "").strip()
if (
json_name
and json_name != filename.replace(".json", "")
and not json_name.startswith("My workflow")
):
workflow["name"] = json_name
# If no meaningful JSON name, use formatted filename (already set above)
# Analyze nodes
node_count = len(workflow["nodes"])
workflow["node_count"] = node_count
# Determine complexity
if node_count <= 5:
complexity = "low"
elif node_count <= 15:
complexity = "medium"
else:
complexity = "high"
workflow["complexity"] = complexity
# Find trigger type and integrations
trigger_type, integrations = self.analyze_nodes(workflow["nodes"])
workflow["trigger_type"] = trigger_type
workflow["integrations"] = list(integrations)
# Use JSON description if available, otherwise generate one
json_description = data.get("description", "").strip()
if json_description:
workflow["description"] = json_description
else:
workflow["description"] = self.generate_description(
workflow, trigger_type, integrations
)
return workflow
def analyze_nodes(self, nodes: List[Dict]) -> Tuple[str, set]:
"""Analyze nodes to determine trigger type and integrations."""
trigger_type = "Manual"
integrations = set()
# Enhanced service mapping for better recognition
service_mappings = {
# Messaging & Communication
"telegram": "Telegram",
"telegramTrigger": "Telegram",
"discord": "Discord",
"slack": "Slack",
"whatsapp": "WhatsApp",
"mattermost": "Mattermost",
"teams": "Microsoft Teams",
"rocketchat": "Rocket.Chat",
# Email
"gmail": "Gmail",
"mailjet": "Mailjet",
"emailreadimap": "Email (IMAP)",
"emailsendsmt": "Email (SMTP)",
"outlook": "Outlook",
# Cloud Storage
"googledrive": "Google Drive",
"googledocs": "Google Docs",
"googlesheets": "Google Sheets",
"dropbox": "Dropbox",
"onedrive": "OneDrive",
"box": "Box",
# Databases
"postgres": "PostgreSQL",
"mysql": "MySQL",
"mongodb": "MongoDB",
"redis": "Redis",
"airtable": "Airtable",
"notion": "Notion",
# Project Management
"jira": "Jira",
"github": "GitHub",
"gitlab": "GitLab",
"trello": "Trello",
"asana": "Asana",
"mondaycom": "Monday.com",
# AI/ML Services
"openai": "OpenAI",
"anthropic": "Anthropic",
"huggingface": "Hugging Face",
# Social Media
"linkedin": "LinkedIn",
"twitter": "Twitter/X",
"facebook": "Facebook",
"instagram": "Instagram",
# E-commerce
"shopify": "Shopify",
"stripe": "Stripe",
"paypal": "PayPal",
# Analytics
"googleanalytics": "Google Analytics",
"mixpanel": "Mixpanel",
# Calendar & Tasks
"googlecalendar": "Google Calendar",
"googletasks": "Google Tasks",
"cal": "Cal.com",
"calendly": "Calendly",
# Forms & Surveys
"typeform": "Typeform",
"googleforms": "Google Forms",
"form": "Form Trigger",
# Development Tools
"webhook": "Webhook",
"httpRequest": "HTTP Request",
"graphql": "GraphQL",
"sse": "Server-Sent Events",
# Utility nodes (exclude from integrations)
"set": None,
"function": None,
"code": None,
"if": None,
"switch": None,
"merge": None,
"split": None,
"stickynote": None,
"stickyNote": None,
"wait": None,
"schedule": None,
"cron": None,
"manual": None,
"stopanderror": None,
"noop": None,
"noOp": None,
"error": None,
"limit": None,
"aggregate": None,
"summarize": None,
"filter": None,
"sort": None,
"removeDuplicates": None,
"dateTime": None,
"extractFromFile": None,
"convertToFile": None,
"readBinaryFile": None,
"readBinaryFiles": None,
"executionData": None,
"executeWorkflow": None,
"executeCommand": None,
"respondToWebhook": None,
}
for node in nodes:
node_type = node.get("type", "")
node_name = node.get("name", "").lower()
# Determine trigger type
if "webhook" in node_type.lower() or "webhook" in node_name:
trigger_type = "Webhook"
elif "cron" in node_type.lower() or "schedule" in node_type.lower():
trigger_type = "Scheduled"
elif "trigger" in node_type.lower() and trigger_type == "Manual":
if "manual" not in node_type.lower():
trigger_type = "Webhook"
# Extract integrations with enhanced mapping
service_name = None
# Handle n8n-nodes-base nodes
if node_type.startswith("n8n-nodes-base."):
raw_service = node_type.replace("n8n-nodes-base.", "").lower()
raw_service = raw_service.replace("trigger", "")
service_name = service_mappings.get(
raw_service, raw_service.title() if raw_service else None
)
# Handle @n8n/ namespaced nodes
elif node_type.startswith("@n8n/"):
raw_service = (
node_type.split(".")[-1].lower()
if "." in node_type
else node_type.lower()
)
raw_service = raw_service.replace("trigger", "")
service_name = service_mappings.get(
raw_service, raw_service.title() if raw_service else None
)
# Handle custom nodes
elif "-" in node_type or "@" in node_type:
# Try to extract service name from custom node names like "n8n-nodes-youtube-transcription-kasha.youtubeTranscripter"
parts = node_type.lower().split(".")
for part in parts:
if "youtube" in part:
service_name = "YouTube"
break
elif "telegram" in part:
service_name = "Telegram"
break
elif "discord" in part:
service_name = "Discord"
break
elif "calcslive" in part:
service_name = "CalcsLive"
break
# Also check node names for service hints (but avoid false positives)
for service_key, service_value in service_mappings.items():
if service_key in node_name and service_value:
# Avoid false positive: "cal" in calcslive-related terms should not match "Cal.com"
if service_key == "cal" and any(
term in node_name.lower()
for term in ["calcslive", "calc", "calculation"]
):
continue
service_name = service_value
break
# Add to integrations if valid service found
if service_name and service_name not in ["None", None]:
integrations.add(service_name)
# Determine if complex based on node variety and count
if len(nodes) > 10 and len(integrations) > 3:
trigger_type = "Complex"
return trigger_type, integrations
def generate_description(
self, workflow: Dict, trigger_type: str, integrations: set
) -> str:
"""Generate a descriptive summary of the workflow."""
name = workflow["name"]
node_count = workflow["node_count"]
# Start with trigger description
trigger_descriptions = {
"Webhook": "Webhook-triggered automation that",
"Scheduled": "Scheduled automation that",
"Complex": "Complex multi-step automation that",
}
desc = trigger_descriptions.get(trigger_type, "Manual workflow that")
# Add functionality based on name and integrations
if integrations:
main_services = list(integrations)[:3]
if len(main_services) == 1:
desc += f" integrates with {main_services[0]}"
elif len(main_services) == 2:
desc += f" connects {main_services[0]} and {main_services[1]}"
else:
desc += f" orchestrates {', '.join(main_services[:-1])}, and {main_services[-1]}"
# Add workflow purpose hints from name
name_lower = name.lower()
if "create" in name_lower:
desc += " to create new records"
elif "update" in name_lower:
desc += " to update existing data"
elif "sync" in name_lower:
desc += " to synchronize data"
elif "notification" in name_lower or "alert" in name_lower:
desc += " for notifications and alerts"
elif "backup" in name_lower:
desc += " for data backup operations"
elif "monitor" in name_lower:
desc += " for monitoring and reporting"
else:
desc += " for data processing"
desc += f". Uses {node_count} nodes"
if len(integrations) > 3:
desc += f" and integrates with {len(integrations)} services"
return desc + "."
def index_all_workflows(self, force_reindex: bool = False) -> Dict[str, int]:
"""Index all workflow files. Only reprocesses changed files unless force_reindex=True."""
if not os.path.exists(self.workflows_dir):
print(f"Warning: Workflows directory '{self.workflows_dir}' not found.")
return {"processed": 0, "skipped": 0, "errors": 0}
workflows_path = Path(self.workflows_dir)
json_files = [str(p) for p in workflows_path.rglob("*.json")]
if not json_files:
print(f"Warning: No JSON files found in '{self.workflows_dir}' directory.")
return {"processed": 0, "skipped": 0, "errors": 0}
print(f"Indexing {len(json_files)} workflow files...")
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
stats = {"processed": 0, "skipped": 0, "errors": 0}
for file_path in json_files:
filename = os.path.basename(file_path)
try:
# Check if file needs to be reprocessed
if not force_reindex:
current_hash = self.get_file_hash(file_path)
cursor = conn.execute(
"SELECT file_hash FROM workflows WHERE filename = ?",
(filename,),
)
row = cursor.fetchone()
if row and row["file_hash"] == current_hash:
stats["skipped"] += 1
continue
# Analyze workflow
workflow_data = self.analyze_workflow_file(file_path)
if not workflow_data:
stats["errors"] += 1
continue
# Insert or update in database
conn.execute(
"""
INSERT OR REPLACE INTO workflows (
filename, name, workflow_id, active, description, trigger_type,
complexity, node_count, integrations, tags, created_at, updated_at,
file_hash, file_size, analyzed_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
""",
(
workflow_data["filename"],
workflow_data["name"],
workflow_data["workflow_id"],
workflow_data["active"],
workflow_data["description"],
workflow_data["trigger_type"],
workflow_data["complexity"],
workflow_data["node_count"],
json.dumps(workflow_data["integrations"]),
json.dumps(workflow_data["tags"]),
workflow_data["created_at"],
workflow_data["updated_at"],
workflow_data["file_hash"],
workflow_data["file_size"],
),
)
stats["processed"] += 1
except Exception as e:
print(f"Error processing {file_path}: {str(e)}")
stats["errors"] += 1
continue
conn.commit()
conn.close()
print(
f"✅ Indexing complete: {stats['processed']} processed, {stats['skipped']} skipped, {stats['errors']} errors"
)
return stats
def search_workflows(
self,
query: str = "",
trigger_filter: str = "all",
complexity_filter: str = "all",
active_only: bool = False,
limit: int = 50,
offset: int = 0,
) -> Tuple[List[Dict], int]:
"""Fast search with filters and pagination."""
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
# Build WHERE clause
where_conditions = []
params = []
if active_only:
where_conditions.append("w.active = 1")
if trigger_filter != "all":
where_conditions.append("w.trigger_type = ?")
params.append(trigger_filter)
if complexity_filter != "all":
where_conditions.append("w.complexity = ?")
params.append(complexity_filter)
# Use FTS search if query provided
if query.strip():
# FTS search with ranking
base_query = """
SELECT w.*, rank
FROM workflows_fts fts
JOIN workflows w ON w.id = fts.rowid
WHERE workflows_fts MATCH ?
"""
params.insert(0, query)
else:
# Regular query without FTS
base_query = """
SELECT w.*, 0 as rank
FROM workflows w
WHERE 1=1
"""
if where_conditions:
base_query += " AND " + " AND ".join(where_conditions)
# Count total results
count_query = f"SELECT COUNT(*) as total FROM ({base_query}) t"
cursor = conn.execute(count_query, params)
total = cursor.fetchone()["total"]
# Get paginated results
if query.strip():
base_query += " ORDER BY rank"
else:
base_query += " ORDER BY w.analyzed_at DESC"
base_query += f" LIMIT {limit} OFFSET {offset}"
cursor = conn.execute(base_query, params)
rows = cursor.fetchall()
# Convert to dictionaries and parse JSON fields
results = []
for row in rows:
workflow = dict(row)
workflow["integrations"] = json.loads(workflow["integrations"] or "[]")
# Parse tags and convert dict tags to strings
raw_tags = json.loads(workflow["tags"] or "[]")
clean_tags = []
for tag in raw_tags:
if isinstance(tag, dict):
# Extract name from tag dict if available
clean_tags.append(tag.get("name", str(tag.get("id", "tag"))))
else:
clean_tags.append(str(tag))
workflow["tags"] = clean_tags
results.append(workflow)
conn.close()
return results, total
def get_stats(self) -> Dict[str, Any]:
"""Get database statistics."""
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
# Basic counts
cursor = conn.execute("SELECT COUNT(*) as total FROM workflows")
total = cursor.fetchone()["total"]
cursor = conn.execute(
"SELECT COUNT(*) as active FROM workflows WHERE active = 1"
)
active = cursor.fetchone()["active"]
# Trigger type breakdown
cursor = conn.execute("""
SELECT trigger_type, COUNT(*) as count
FROM workflows
GROUP BY trigger_type
""")
triggers = {row["trigger_type"]: row["count"] for row in cursor.fetchall()}
# Complexity breakdown
cursor = conn.execute("""
SELECT complexity, COUNT(*) as count
FROM workflows
GROUP BY complexity
""")
complexity = {row["complexity"]: row["count"] for row in cursor.fetchall()}
# Node stats
cursor = conn.execute("SELECT SUM(node_count) as total_nodes FROM workflows")
total_nodes = cursor.fetchone()["total_nodes"] or 0
# Unique integrations count
cursor = conn.execute(
"SELECT integrations FROM workflows WHERE integrations != '[]'"
)
all_integrations = set()
for row in cursor.fetchall():
integrations = json.loads(row["integrations"])
all_integrations.update(integrations)
conn.close()
return {
"total": total,
"active": active,
"inactive": total - active,
"triggers": triggers,
"complexity": complexity,
"total_nodes": total_nodes,
"unique_integrations": len(all_integrations),
"last_indexed": datetime.datetime.now().isoformat(),
}
def get_service_categories(self) -> Dict[str, List[str]]:
"""Get service categories for enhanced filtering."""
return {
"messaging": [
"Telegram",
"Discord",
"Slack",
"WhatsApp",
"Mattermost",
"Microsoft Teams",
"Rocket.Chat",
],
"email": ["Gmail", "Mailjet", "Email (IMAP)", "Email (SMTP)", "Outlook"],
"cloud_storage": [
"Google Drive",
"Google Docs",
"Google Sheets",
"Dropbox",
"OneDrive",
"Box",
],
"database": [
"PostgreSQL",
"MySQL",
"MongoDB",
"Redis",
"Airtable",
"Notion",
],
"project_management": [
"Jira",
"GitHub",
"GitLab",
"Trello",
"Asana",
"Monday.com",
],
"ai_ml": ["OpenAI", "Anthropic", "Hugging Face", "CalcsLive"],
"social_media": ["LinkedIn", "Twitter/X", "Facebook", "Instagram"],
"ecommerce": ["Shopify", "Stripe", "PayPal"],
"analytics": ["Google Analytics", "Mixpanel"],
"calendar_tasks": [
"Google Calendar",
"Google Tasks",
"Cal.com",
"Calendly",
],
"forms": ["Typeform", "Google Forms", "Form Trigger"],
"development": [
"Webhook",
"HTTP Request",
"GraphQL",
"Server-Sent Events",
"YouTube",
],
}
def search_by_category(
self, category: str, limit: int = 50, offset: int = 0
) -> Tuple[List[Dict], int]:
"""Search workflows by service category."""
categories = self.get_service_categories()
if category not in categories:
return [], 0
services = categories[category]
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
# Build OR conditions for all services in category
service_conditions = []
params = []
for service in services:
service_conditions.append("integrations LIKE ?")
params.append(f'%"{service}"%')
where_clause = " OR ".join(service_conditions)
# Count total results
count_query = f"SELECT COUNT(*) as total FROM workflows WHERE {where_clause}"
cursor = conn.execute(count_query, params)
total = cursor.fetchone()["total"]
# Get paginated results
query = f"""
SELECT * FROM workflows
WHERE {where_clause}
ORDER BY analyzed_at DESC
LIMIT {limit} OFFSET {offset}
"""
cursor = conn.execute(query, params)
rows = cursor.fetchall()
# Convert to dictionaries and parse JSON fields
results = []
for row in rows:
workflow = dict(row)
workflow["integrations"] = json.loads(workflow["integrations"] or "[]")
raw_tags = json.loads(workflow["tags"] or "[]")
clean_tags = []
for tag in raw_tags:
if isinstance(tag, dict):
clean_tags.append(tag.get("name", str(tag.get("id", "tag"))))
else:
clean_tags.append(str(tag))
workflow["tags"] = clean_tags
results.append(workflow)
conn.close()
return results, total
def main():
"""Command-line interface for workflow database."""
import argparse
parser = argparse.ArgumentParser(description="N8N Workflow Database")
parser.add_argument("--index", action="store_true", help="Index all workflows")
parser.add_argument("--force", action="store_true", help="Force reindex all files")
parser.add_argument("--search", help="Search workflows")
parser.add_argument("--stats", action="store_true", help="Show database statistics")
args = parser.parse_args()
db = WorkflowDatabase()
if args.index:
stats = db.index_all_workflows(force_reindex=args.force)
print(f"Indexed {stats['processed']} workflows")
elif args.search:
results, total = db.search_workflows(args.search, limit=10)
print(f"Found {total} workflows:")
for workflow in results:
print(
f" - {workflow['name']} ({workflow['trigger_type']}, {workflow['node_count']} nodes)"
)
elif args.stats:
stats = db.get_stats()
print("Database Statistics:")
print(f" Total workflows: {stats['total']}")
print(f" Active: {stats['active']}")
print(f" Total nodes: {stats['total_nodes']}")
print(f" Unique integrations: {stats['unique_integrations']}")
print(f" Trigger types: {stats['triggers']}")
else:
parser.print_help()
if __name__ == "__main__":
main()
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/api_server.py | api_server.py | #!/usr/bin/env python3
"""
FastAPI Server for N8N Workflow Documentation
High-performance API with sub-100ms response times.
"""
from fastapi import FastAPI, HTTPException, Query, BackgroundTasks, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from pydantic import BaseModel, field_validator
from typing import Optional, List, Dict, Any
import json
import os
import re
import urllib.parse
from pathlib import Path
import uvicorn
import time
from collections import defaultdict
from workflow_db import WorkflowDatabase
# Initialize FastAPI app
app = FastAPI(
title="N8N Workflow Documentation API",
description="Fast API for browsing and searching workflow documentation",
version="2.0.0",
)
# Security: Rate limiting storage
rate_limit_storage = defaultdict(list)
MAX_REQUESTS_PER_MINUTE = 60 # Configure as needed
# Add middleware for performance
app.add_middleware(GZipMiddleware, minimum_size=1000)
# Security: Configure CORS properly - restrict origins in production
# For local development, you can use localhost
# For production, replace with your actual domain
ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://localhost:8000",
"http://localhost:8080",
"https://zie619.github.io", # GitHub Pages
"https://n8n-workflows-1-xxgm.onrender.com", # Community deployment
]
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS, # Security fix: Restrict origins
allow_credentials=True,
allow_methods=["GET", "POST"], # Security fix: Only allow needed methods
allow_headers=["Content-Type", "Authorization"], # Security fix: Restrict headers
)
# Initialize database
db = WorkflowDatabase()
# Security: Helper function for rate limiting
def check_rate_limit(client_ip: str) -> bool:
"""Check if client has exceeded rate limit."""
current_time = time.time()
# Clean old entries
rate_limit_storage[client_ip] = [
timestamp
for timestamp in rate_limit_storage[client_ip]
if current_time - timestamp < 60
]
# Check rate limit
if len(rate_limit_storage[client_ip]) >= MAX_REQUESTS_PER_MINUTE:
return False
# Add current request
rate_limit_storage[client_ip].append(current_time)
return True
# Security: Helper function to validate and sanitize filenames
def validate_filename(filename: str) -> bool:
"""
Validate filename to prevent path traversal attacks.
Returns True if filename is safe, False otherwise.
"""
# Decode URL encoding multiple times to catch encoded traversal attempts
decoded = filename
for _ in range(3): # Decode up to 3 times to catch nested encodings
try:
decoded = urllib.parse.unquote(decoded, errors="strict")
except:
return False # Invalid encoding
# Check for path traversal patterns
dangerous_patterns = [
"..", # Parent directory
"..\\", # Windows parent directory
"../", # Unix parent directory
"\\", # Backslash (Windows path separator)
"/", # Forward slash (Unix path separator)
"\x00", # Null byte
"\n",
"\r", # Newlines
"~", # Home directory
":", # Drive letter or stream (Windows)
"|",
"<",
">", # Shell redirection
"*",
"?", # Wildcards
"$", # Variable expansion
";",
"&", # Command separators
]
for pattern in dangerous_patterns:
if pattern in decoded:
return False
# Check for absolute paths
if decoded.startswith("/") or decoded.startswith("\\"):
return False
# Check for Windows drive letters
if len(decoded) >= 2 and decoded[1] == ":":
return False
# Only allow alphanumeric, dash, underscore, and .json extension
if not re.match(r"^[a-zA-Z0-9_\-]+\.json$", decoded):
return False
# Additional check: filename should end with .json
if not decoded.endswith(".json"):
return False
return True
# Startup function to verify database
@app.on_event("startup")
async def startup_event():
"""Verify database connectivity on startup."""
try:
stats = db.get_stats()
if stats["total"] == 0:
print("⚠️ Warning: No workflows found in database. Run indexing first.")
else:
print(f"✅ Database connected: {stats['total']} workflows indexed")
except Exception as e:
print(f"❌ Database connection failed: {e}")
raise
# Response models
class WorkflowSummary(BaseModel):
id: Optional[int] = None
filename: str
name: str
active: bool
description: str = ""
trigger_type: str = "Manual"
complexity: str = "low"
node_count: int = 0
integrations: List[str] = []
tags: List[str] = []
created_at: Optional[str] = None
updated_at: Optional[str] = None
class Config:
# Allow conversion of int to bool for active field
validate_assignment = True
@field_validator("active", mode="before")
@classmethod
def convert_active(cls, v):
if isinstance(v, int):
return bool(v)
return v
class SearchResponse(BaseModel):
workflows: List[WorkflowSummary]
total: int
page: int
per_page: int
pages: int
query: str
filters: Dict[str, Any]
class StatsResponse(BaseModel):
total: int
active: int
inactive: int
triggers: Dict[str, int]
complexity: Dict[str, int]
total_nodes: int
unique_integrations: int
last_indexed: str
@app.get("/")
async def root():
"""Serve the main documentation page."""
static_dir = Path("static")
index_file = static_dir / "index.html"
if not index_file.exists():
return HTMLResponse(
"""
<html><body>
<h1>Setup Required</h1>
<p>Static files not found. Please ensure the static directory exists with index.html</p>
<p>Current directory: """
+ str(Path.cwd())
+ """</p>
</body></html>
"""
)
return FileResponse(str(index_file))
@app.get("/health")
async def health_check():
"""Health check endpoint."""
return {"status": "healthy", "message": "N8N Workflow API is running"}
@app.get("/api/stats", response_model=StatsResponse)
async def get_stats():
"""Get workflow database statistics."""
try:
stats = db.get_stats()
return StatsResponse(**stats)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching stats: {str(e)}")
@app.get("/api/workflows", response_model=SearchResponse)
async def search_workflows(
q: str = Query("", description="Search query"),
trigger: str = Query("all", description="Filter by trigger type"),
complexity: str = Query("all", description="Filter by complexity"),
active_only: bool = Query(False, description="Show only active workflows"),
page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(20, ge=1, le=100, description="Items per page"),
):
"""Search and filter workflows with pagination."""
try:
offset = (page - 1) * per_page
workflows, total = db.search_workflows(
query=q,
trigger_filter=trigger,
complexity_filter=complexity,
active_only=active_only,
limit=per_page,
offset=offset,
)
# Convert to Pydantic models with error handling
workflow_summaries = []
for workflow in workflows:
try:
# Remove extra fields that aren't in the model
clean_workflow = {
"id": workflow.get("id"),
"filename": workflow.get("filename", ""),
"name": workflow.get("name", ""),
"active": workflow.get("active", False),
"description": workflow.get("description", ""),
"trigger_type": workflow.get("trigger_type", "Manual"),
"complexity": workflow.get("complexity", "low"),
"node_count": workflow.get("node_count", 0),
"integrations": workflow.get("integrations", []),
"tags": workflow.get("tags", []),
"created_at": workflow.get("created_at"),
"updated_at": workflow.get("updated_at"),
}
workflow_summaries.append(WorkflowSummary(**clean_workflow))
except Exception as e:
print(
f"Error converting workflow {workflow.get('filename', 'unknown')}: {e}"
)
# Continue with other workflows instead of failing completely
continue
pages = (total + per_page - 1) // per_page # Ceiling division
return SearchResponse(
workflows=workflow_summaries,
total=total,
page=page,
per_page=per_page,
pages=pages,
query=q,
filters={
"trigger": trigger,
"complexity": complexity,
"active_only": active_only,
},
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error searching workflows: {str(e)}"
)
@app.get("/api/workflows/{filename}")
async def get_workflow_detail(filename: str, request: Request):
"""Get detailed workflow information including raw JSON."""
try:
# Security: Validate filename to prevent path traversal
if not validate_filename(filename):
print(f"Security: Blocked path traversal attempt for filename: {filename}")
raise HTTPException(status_code=400, detail="Invalid filename format")
# Security: Rate limiting
client_ip = request.client.host if request.client else "unknown"
if not check_rate_limit(client_ip):
raise HTTPException(
status_code=429, detail="Rate limit exceeded. Please try again later."
)
# Get workflow metadata from database
workflows, _ = db.search_workflows(f'filename:"{filename}"', limit=1)
if not workflows:
raise HTTPException(
status_code=404, detail="Workflow not found in database"
)
workflow_meta = workflows[0]
# Load raw JSON from file with security checks
workflows_path = Path("workflows").resolve()
# Find the file safely
matching_file = None
for subdir in workflows_path.iterdir():
if subdir.is_dir():
target_file = subdir / filename
if target_file.exists() and target_file.is_file():
# Verify the file is actually within workflows directory
try:
target_file.resolve().relative_to(workflows_path)
matching_file = target_file
break
except ValueError:
print(
f"Security: Blocked access to file outside workflows: {target_file}"
)
continue
if not matching_file:
print(f"Warning: File {filename} not found in workflows directory")
raise HTTPException(
status_code=404,
detail=f"Workflow file '{filename}' not found on filesystem",
)
with open(matching_file, "r", encoding="utf-8") as f:
raw_json = json.load(f)
return {"metadata": workflow_meta, "raw_json": raw_json}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error loading workflow: {str(e)}")
@app.get("/api/workflows/{filename}/download")
async def download_workflow(filename: str, request: Request):
"""Download workflow JSON file with security validation."""
try:
# Security: Validate filename to prevent path traversal
if not validate_filename(filename):
print(f"Security: Blocked path traversal attempt for filename: {filename}")
raise HTTPException(status_code=400, detail="Invalid filename format")
# Security: Rate limiting
client_ip = request.client.host if request.client else "unknown"
if not check_rate_limit(client_ip):
raise HTTPException(
status_code=429, detail="Rate limit exceeded. Please try again later."
)
# Only search within the workflows directory
workflows_path = Path("workflows").resolve() # Get absolute path
# Find the file safely
json_files = []
for subdir in workflows_path.iterdir():
if subdir.is_dir():
target_file = subdir / filename
if target_file.exists() and target_file.is_file():
# Verify the file is actually within workflows directory (defense in depth)
try:
target_file.resolve().relative_to(workflows_path)
json_files.append(target_file)
except ValueError:
# File is outside workflows directory
print(
f"Security: Blocked access to file outside workflows: {target_file}"
)
continue
if not json_files:
print(f"File {filename} not found in workflows directory")
raise HTTPException(
status_code=404, detail=f"Workflow file '{filename}' not found"
)
file_path = json_files[0]
# Final security check: Ensure file is within workflows directory
try:
file_path.resolve().relative_to(workflows_path)
except ValueError:
print(
f"Security: Blocked final attempt to access file outside workflows: {file_path}"
)
raise HTTPException(status_code=403, detail="Access denied")
return FileResponse(
str(file_path), media_type="application/json", filename=filename
)
except HTTPException:
raise
except Exception as e:
print(f"Error downloading workflow {filename}: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Error downloading workflow: {str(e)}"
)
@app.get("/api/workflows/{filename}/diagram")
async def get_workflow_diagram(filename: str, request: Request):
"""Get Mermaid diagram code for workflow visualization."""
try:
# Security: Validate filename to prevent path traversal
if not validate_filename(filename):
print(f"Security: Blocked path traversal attempt for filename: {filename}")
raise HTTPException(status_code=400, detail="Invalid filename format")
# Security: Rate limiting
client_ip = request.client.host if request.client else "unknown"
if not check_rate_limit(client_ip):
raise HTTPException(
status_code=429, detail="Rate limit exceeded. Please try again later."
)
# Only search within the workflows directory
workflows_path = Path("workflows").resolve()
# Find the file safely
matching_file = None
for subdir in workflows_path.iterdir():
if subdir.is_dir():
target_file = subdir / filename
if target_file.exists() and target_file.is_file():
# Verify the file is actually within workflows directory
try:
target_file.resolve().relative_to(workflows_path)
matching_file = target_file
break
except ValueError:
print(
f"Security: Blocked access to file outside workflows: {target_file}"
)
continue
if not matching_file:
print(f"Warning: File {filename} not found in workflows directory")
raise HTTPException(
status_code=404,
detail=f"Workflow file '{filename}' not found on filesystem",
)
with open(matching_file, "r", encoding="utf-8") as f:
data = json.load(f)
nodes = data.get("nodes", [])
connections = data.get("connections", {})
# Generate Mermaid diagram
diagram = generate_mermaid_diagram(nodes, connections)
return {"diagram": diagram}
except HTTPException:
raise
except json.JSONDecodeError as e:
print(f"Error parsing JSON in {filename}: {str(e)}")
raise HTTPException(
status_code=400, detail=f"Invalid JSON in workflow file: {str(e)}"
)
except Exception as e:
print(f"Error generating diagram for {filename}: {str(e)}")
raise HTTPException(
status_code=500, detail=f"Error generating diagram: {str(e)}"
)
def generate_mermaid_diagram(nodes: List[Dict], connections: Dict) -> str:
"""Generate Mermaid.js flowchart code from workflow nodes and connections."""
if not nodes:
return "graph TD\n EmptyWorkflow[No nodes found in workflow]"
# Create mapping for node names to ensure valid mermaid IDs
mermaid_ids = {}
for i, node in enumerate(nodes):
node_id = f"node{i}"
node_name = node.get("name", f"Node {i}")
mermaid_ids[node_name] = node_id
# Start building the mermaid diagram
mermaid_code = ["graph TD"]
# Add nodes with styling
for node in nodes:
node_name = node.get("name", "Unnamed")
node_id = mermaid_ids[node_name]
node_type = node.get("type", "").replace("n8n-nodes-base.", "")
# Determine node style based on type
style = ""
if any(x in node_type.lower() for x in ["trigger", "webhook", "cron"]):
style = "fill:#b3e0ff,stroke:#0066cc" # Blue for triggers
elif any(x in node_type.lower() for x in ["if", "switch"]):
style = "fill:#ffffb3,stroke:#e6e600" # Yellow for conditional nodes
elif any(x in node_type.lower() for x in ["function", "code"]):
style = "fill:#d9b3ff,stroke:#6600cc" # Purple for code nodes
elif "error" in node_type.lower():
style = "fill:#ffb3b3,stroke:#cc0000" # Red for error handlers
else:
style = "fill:#d9d9d9,stroke:#666666" # Gray for other nodes
# Add node with label (escaping special characters)
clean_name = node_name.replace('"', "'")
clean_type = node_type.replace('"', "'")
label = f"{clean_name}<br>({clean_type})"
mermaid_code.append(f' {node_id}["{label}"]')
mermaid_code.append(f" style {node_id} {style}")
# Add connections between nodes
for source_name, source_connections in connections.items():
if source_name not in mermaid_ids:
continue
if isinstance(source_connections, dict) and "main" in source_connections:
main_connections = source_connections["main"]
for i, output_connections in enumerate(main_connections):
if not isinstance(output_connections, list):
continue
for connection in output_connections:
if not isinstance(connection, dict) or "node" not in connection:
continue
target_name = connection["node"]
if target_name not in mermaid_ids:
continue
# Add arrow with output index if multiple outputs
label = f" -->|{i}| " if len(main_connections) > 1 else " --> "
mermaid_code.append(
f" {mermaid_ids[source_name]}{label}{mermaid_ids[target_name]}"
)
# Format the final mermaid diagram code
return "\n".join(mermaid_code)
@app.post("/api/reindex")
async def reindex_workflows(
background_tasks: BackgroundTasks,
request: Request,
force: bool = False,
admin_token: Optional[str] = Query(None, description="Admin authentication token"),
):
"""Trigger workflow reindexing in the background (requires authentication)."""
# Security: Rate limiting
client_ip = request.client.host if request.client else "unknown"
if not check_rate_limit(client_ip):
raise HTTPException(
status_code=429, detail="Rate limit exceeded. Please try again later."
)
# Security: Basic authentication check
# In production, use proper authentication (JWT, OAuth, etc.)
# For now, check for environment variable or disable endpoint
expected_token = os.environ.get("ADMIN_TOKEN", None)
if not expected_token:
# If no token is configured, disable the endpoint for security
raise HTTPException(
status_code=503,
detail="Reindexing endpoint is disabled. Set ADMIN_TOKEN environment variable to enable.",
)
if admin_token != expected_token:
print(f"Security: Unauthorized reindex attempt from {client_ip}")
raise HTTPException(status_code=401, detail="Invalid authentication token")
def run_indexing():
try:
db.index_all_workflows(force_reindex=force)
print(f"Reindexing completed successfully (requested by {client_ip})")
except Exception as e:
print(f"Error during reindexing: {e}")
background_tasks.add_task(run_indexing)
return {"message": "Reindexing started in background", "requested_by": client_ip}
@app.get("/api/integrations")
async def get_integrations():
"""Get list of all unique integrations."""
try:
stats = db.get_stats()
# For now, return basic info. Could be enhanced to return detailed integration stats
return {"integrations": [], "count": stats["unique_integrations"]}
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error fetching integrations: {str(e)}"
)
@app.get("/api/categories")
async def get_categories():
"""Get available workflow categories for filtering."""
try:
# Try to load from the generated unique categories file
categories_file = Path("context/unique_categories.json")
if categories_file.exists():
with open(categories_file, "r", encoding="utf-8") as f:
categories = json.load(f)
return {"categories": categories}
else:
# Fallback: extract categories from search_categories.json
search_categories_file = Path("context/search_categories.json")
if search_categories_file.exists():
with open(search_categories_file, "r", encoding="utf-8") as f:
search_data = json.load(f)
unique_categories = set()
for item in search_data:
if item.get("category"):
unique_categories.add(item["category"])
else:
unique_categories.add("Uncategorized")
categories = sorted(list(unique_categories))
return {"categories": categories}
else:
# Last resort: return basic categories
return {"categories": ["Uncategorized"]}
except Exception as e:
print(f"Error loading categories: {e}")
raise HTTPException(
status_code=500, detail=f"Error fetching categories: {str(e)}"
)
@app.get("/api/category-mappings")
async def get_category_mappings():
"""Get filename to category mappings for client-side filtering."""
try:
search_categories_file = Path("context/search_categories.json")
if not search_categories_file.exists():
return {"mappings": {}}
with open(search_categories_file, "r", encoding="utf-8") as f:
search_data = json.load(f)
# Convert to a simple filename -> category mapping
mappings = {}
for item in search_data:
filename = item.get("filename")
category = item.get("category") or "Uncategorized"
if filename:
mappings[filename] = category
return {"mappings": mappings}
except Exception as e:
print(f"Error loading category mappings: {e}")
raise HTTPException(
status_code=500, detail=f"Error fetching category mappings: {str(e)}"
)
@app.get("/api/workflows/category/{category}", response_model=SearchResponse)
async def search_workflows_by_category(
category: str,
page: int = Query(1, ge=1, description="Page number"),
per_page: int = Query(20, ge=1, le=100, description="Items per page"),
):
"""Search workflows by service category (messaging, database, ai_ml, etc.)."""
try:
offset = (page - 1) * per_page
workflows, total = db.search_by_category(
category=category, limit=per_page, offset=offset
)
# Convert to Pydantic models with error handling
workflow_summaries = []
for workflow in workflows:
try:
clean_workflow = {
"id": workflow.get("id"),
"filename": workflow.get("filename", ""),
"name": workflow.get("name", ""),
"active": workflow.get("active", False),
"description": workflow.get("description", ""),
"trigger_type": workflow.get("trigger_type", "Manual"),
"complexity": workflow.get("complexity", "low"),
"node_count": workflow.get("node_count", 0),
"integrations": workflow.get("integrations", []),
"tags": workflow.get("tags", []),
"created_at": workflow.get("created_at"),
"updated_at": workflow.get("updated_at"),
}
workflow_summaries.append(WorkflowSummary(**clean_workflow))
except Exception as e:
print(
f"Error converting workflow {workflow.get('filename', 'unknown')}: {e}"
)
continue
pages = (total + per_page - 1) // per_page
return SearchResponse(
workflows=workflow_summaries,
total=total,
page=page,
per_page=per_page,
pages=pages,
query=f"category:{category}",
filters={"category": category},
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error searching by category: {str(e)}"
)
# Custom exception handler for better error responses
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
return JSONResponse(
status_code=500, content={"detail": f"Internal server error: {str(exc)}"}
)
# Mount static files AFTER all routes are defined
static_dir = Path("static")
if static_dir.exists():
app.mount("/static", StaticFiles(directory="static"), name="static")
print(f"✅ Static files mounted from {static_dir.absolute()}")
else:
print(f"❌ Warning: Static directory not found at {static_dir.absolute()}")
def create_static_directory():
"""Create static directory if it doesn't exist."""
static_dir = Path("static")
static_dir.mkdir(exist_ok=True)
return static_dir
def run_server(host: str = "127.0.0.1", port: int = 8000, reload: bool = False):
"""Run the FastAPI server."""
# Ensure static directory exists
create_static_directory()
# Debug: Check database connectivity
try:
stats = db.get_stats()
print(f"✅ Database connected: {stats['total']} workflows found")
if stats["total"] == 0:
print("🔄 Database is empty. Indexing workflows...")
db.index_all_workflows()
stats = db.get_stats()
except Exception as e:
print(f"❌ Database error: {e}")
print("🔄 Attempting to create and index database...")
try:
db.index_all_workflows()
stats = db.get_stats()
print(f"✅ Database created: {stats['total']} workflows indexed")
except Exception as e2:
print(f"❌ Failed to create database: {e2}")
stats = {"total": 0}
# Debug: Check static files
static_path = Path("static")
if static_path.exists():
files = list(static_path.glob("*"))
print(f"✅ Static files found: {[f.name for f in files]}")
else:
print(f"❌ Static directory not found at: {static_path.absolute()}")
print("🚀 Starting N8N Workflow Documentation API")
print(f"📊 Database contains {stats['total']} workflows")
print(f"🌐 Server will be available at: http://{host}:{port}")
print(f"📁 Static files at: http://{host}:{port}/static/")
uvicorn.run(
"api_server:app",
host=host,
port=port,
reload=reload,
access_log=True, # Enable access logs for debugging
log_level="info",
)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="N8N Workflow Documentation API Server"
)
parser.add_argument("--host", default="127.0.0.1", help="Host to bind to")
parser.add_argument("--port", type=int, default=8000, help="Port to bind to")
parser.add_argument(
"--reload", action="store_true", help="Enable auto-reload for development"
)
args = parser.parse_args()
run_server(host=args.host, port=args.port, reload=args.reload)
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/scripts/update_github_pages.py | scripts/update_github_pages.py | #!/usr/bin/env python3
"""
Update GitHub Pages Files
Fixes the hardcoded timestamp and ensures proper deployment.
Addresses Issues #115 and #129.
"""
import json
from datetime import datetime
from pathlib import Path
import re
def update_html_timestamp(html_file: str):
"""Update the timestamp in the HTML file to current date."""
file_path = Path(html_file)
if not file_path.exists():
print(f"Warning: {html_file} not found")
return False
# Read the HTML file
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Get current month and year
current_date = datetime.now().strftime("%B %Y")
# Replace the hardcoded timestamp
# Look for pattern like "Last updated: Month Year"
pattern = r'(<p class="footer-meta">Last updated:)\s*([^<]+)'
replacement = f"\\1 {current_date}"
updated_content = re.sub(pattern, replacement, content)
# Also add a meta tag with the exact timestamp for better tracking
if '<meta name="last-updated"' not in updated_content:
timestamp_meta = (
f' <meta name="last-updated" content="{datetime.now().isoformat()}">\n'
)
updated_content = updated_content.replace("</head>", f"{timestamp_meta}</head>")
# Write back the updated content
with open(file_path, "w", encoding="utf-8") as f:
f.write(updated_content)
print(f"✅ Updated timestamp in {html_file} to: {current_date}")
return True
def update_api_timestamp(api_dir: str):
"""Update timestamp in API JSON files."""
api_path = Path(api_dir)
if not api_path.exists():
api_path.mkdir(parents=True, exist_ok=True)
# Create or update a metadata file with current timestamp
metadata = {
"last_updated": datetime.now().isoformat(),
"last_updated_readable": datetime.now().strftime("%B %d, %Y at %H:%M UTC"),
"version": "2.0.1",
"deployment_type": "github_pages",
}
metadata_file = api_path / "metadata.json"
with open(metadata_file, "w", encoding="utf-8") as f:
json.dump(metadata, f, indent=2)
print(f"✅ Created metadata file: {metadata_file}")
# Update stats.json if it exists
stats_file = api_path / "stats.json"
if stats_file.exists():
with open(stats_file, "r", encoding="utf-8") as f:
stats = json.load(f)
stats["last_updated"] = datetime.now().isoformat()
with open(stats_file, "w", encoding="utf-8") as f:
json.dump(stats, f, indent=2)
print(f"✅ Updated stats file: {stats_file}")
return True
def create_github_pages_config():
"""Create necessary GitHub Pages configuration files."""
# Create/update _config.yml for Jekyll (GitHub Pages)
config_content = """# GitHub Pages Configuration
theme: null
title: N8N Workflows Repository
description: Browse and search 2000+ n8n workflow automation templates
baseurl: "/n8n-workflows"
url: "https://zie619.github.io"
# Build settings
markdown: kramdown
exclude:
- workflows/
- scripts/
- src/
- "*.py"
- requirements.txt
- Dockerfile
- docker-compose.yml
- k8s/
- helm/
- Documentation/
- context/
- database/
- static/
- templates/
- .github/
- .devcontainer/
"""
config_file = Path("docs/_config.yml")
with open(config_file, "w", encoding="utf-8") as f:
f.write(config_content)
print(f"✅ Created Jekyll config: {config_file}")
# Create .nojekyll file to bypass Jekyll processing (for pure HTML/JS site)
nojekyll_file = Path("docs/.nojekyll")
nojekyll_file.touch()
print(f"✅ Created .nojekyll file: {nojekyll_file}")
# Create a simple 404.html page
error_page_content = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 - Page Not Found</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.container {
text-align: center;
padding: 2rem;
}
h1 { font-size: 6rem; margin: 0; }
p { font-size: 1.5rem; margin: 1rem 0; }
a {
display: inline-block;
margin-top: 2rem;
padding: 1rem 2rem;
background: white;
color: #667eea;
text-decoration: none;
border-radius: 5px;
transition: transform 0.2s;
}
a:hover { transform: scale(1.05); }
</style>
</head>
<body>
<div class="container">
<h1>404</h1>
<p>Page not found</p>
<p>The n8n workflows repository has been updated.</p>
<a href="/n8n-workflows/">Go to Homepage</a>
</div>
</body>
</html>"""
error_file = Path("docs/404.html")
with open(error_file, "w", encoding="utf-8") as f:
f.write(error_page_content)
print(f"✅ Created 404 page: {error_file}")
def verify_github_pages_structure():
"""Verify that all necessary files exist for GitHub Pages deployment."""
required_files = [
"docs/index.html",
"docs/css/styles.css",
"docs/js/app.js",
"docs/js/search.js",
"docs/api/search-index.json",
"docs/api/stats.json",
"docs/api/categories.json",
"docs/api/integrations.json",
]
missing_files = []
for file_path in required_files:
if not Path(file_path).exists():
missing_files.append(file_path)
print(f"❌ Missing: {file_path}")
else:
print(f"✅ Found: {file_path}")
if missing_files:
print(f"\n⚠️ Warning: {len(missing_files)} required files are missing")
print("Run the following commands to generate them:")
print(" python workflow_db.py --index --force")
print(" python create_categories.py")
print(" python scripts/generate_search_index.py")
return False
print("\n✅ All required files present for GitHub Pages deployment")
return True
def fix_base_url_references():
"""Fix any hardcoded URLs to use relative paths for GitHub Pages."""
# Update index.html to use relative paths
index_file = Path("docs/index.html")
if index_file.exists():
with open(index_file, "r", encoding="utf-8") as f:
content = f.read()
# Replace absolute paths with relative ones
replacements = [
('href="/css/', 'href="css/'),
('src="/js/', 'src="js/'),
('href="/api/', 'href="api/'),
('fetch("/api/', 'fetch("api/'),
("fetch('/api/", "fetch('api/"),
]
for old, new in replacements:
content = content.replace(old, new)
with open(index_file, "w", encoding="utf-8") as f:
f.write(content)
print("✅ Fixed URL references in index.html")
# Update JavaScript files
js_files = ["docs/js/app.js", "docs/js/search.js"]
for js_file in js_files:
js_path = Path(js_file)
if js_path.exists():
with open(js_path, "r", encoding="utf-8") as f:
content = f.read()
# Fix API endpoint references
content = content.replace("fetch('/api/", "fetch('api/")
content = content.replace('fetch("/api/', 'fetch("api/')
content = content.replace("'/api/", "'api/")
content = content.replace('"/api/', '"api/')
with open(js_path, "w", encoding="utf-8") as f:
f.write(content)
print(f"✅ Fixed URL references in {js_file}")
def main():
"""Main function to update GitHub Pages deployment."""
print("🔧 GitHub Pages Update Script")
print("=" * 50)
# Step 1: Update timestamps
print("\n📅 Updating timestamps...")
update_html_timestamp("docs/index.html")
update_api_timestamp("docs/api")
# Step 2: Create GitHub Pages configuration
print("\n⚙️ Creating GitHub Pages configuration...")
create_github_pages_config()
# Step 3: Fix URL references
print("\n🔗 Fixing URL references...")
fix_base_url_references()
# Step 4: Verify structure
print("\n✔️ Verifying deployment structure...")
if verify_github_pages_structure():
print("\n✨ GitHub Pages setup complete!")
print("\nDeployment will be available at:")
print(" https://zie619.github.io/n8n-workflows/")
print(
"\nNote: It may take a few minutes for changes to appear after pushing to GitHub."
)
else:
print("\n⚠️ Some files are missing. Please generate them first.")
if __name__ == "__main__":
main()
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/scripts/generate_search_index.py | scripts/generate_search_index.py | #!/usr/bin/env python3
"""
Generate Static Search Index for GitHub Pages
Creates a lightweight JSON index for client-side search functionality.
"""
import json
import os
import sys
from pathlib import Path
from typing import Dict, List, Any
# Add the parent directory to path for imports
sys.path.append(str(Path(__file__).parent.parent))
from workflow_db import WorkflowDatabase
def generate_static_search_index(db_path: str, output_dir: str) -> Dict[str, Any]:
"""Generate a static search index for client-side searching."""
# Initialize database
db = WorkflowDatabase(db_path)
# Get all workflows
workflows, total = db.search_workflows(limit=10000) # Get all workflows
# Get statistics
stats = db.get_stats()
# Get categories from service mapping
categories = db.get_service_categories()
# Load existing categories from create_categories.py system
existing_categories = load_existing_categories()
# Create simplified workflow data for search
search_workflows = []
for workflow in workflows:
# Create searchable text combining multiple fields
searchable_text = " ".join(
[
workflow["name"],
workflow["description"],
workflow["filename"],
" ".join(workflow["integrations"]),
" ".join(workflow["tags"]) if workflow["tags"] else "",
]
).lower()
# Use existing category from create_categories.py system, fallback to integration-based
category = get_workflow_category(
workflow["filename"],
existing_categories,
workflow["integrations"],
categories,
)
search_workflow = {
"id": workflow["filename"].replace(".json", ""),
"name": workflow["name"],
"description": workflow["description"],
"filename": workflow["filename"],
"active": workflow["active"],
"trigger_type": workflow["trigger_type"],
"complexity": workflow["complexity"],
"node_count": workflow["node_count"],
"integrations": workflow["integrations"],
"tags": workflow["tags"],
"category": category,
"searchable_text": searchable_text,
"download_url": f"https://raw.githubusercontent.com/Zie619/n8n-workflows/main/workflows/{extract_folder_from_filename(workflow['filename'])}/{workflow['filename']}",
}
search_workflows.append(search_workflow)
# Create comprehensive search index
search_index = {
"version": "1.0",
"generated_at": stats.get("last_indexed", ""),
"stats": {
"total_workflows": stats["total"],
"active_workflows": stats["active"],
"inactive_workflows": stats["inactive"],
"total_nodes": stats["total_nodes"],
"unique_integrations": stats["unique_integrations"],
"categories": len(get_category_list(categories)),
"triggers": stats["triggers"],
"complexity": stats["complexity"],
},
"categories": get_category_list(categories),
"integrations": get_popular_integrations(workflows),
"workflows": search_workflows,
}
return search_index
def load_existing_categories() -> Dict[str, str]:
"""Load existing categories from search_categories.json created by create_categories.py."""
try:
with open("context/search_categories.json", "r", encoding="utf-8") as f:
categories_data = json.load(f)
# Convert to filename -> category mapping
category_mapping = {}
for item in categories_data:
if item.get("category"):
category_mapping[item["filename"]] = item["category"]
return category_mapping
except FileNotFoundError:
print(
"Warning: search_categories.json not found, using integration-based categorization"
)
return {}
def get_workflow_category(
filename: str,
existing_categories: Dict[str, str],
integrations: List[str],
service_categories: Dict[str, List[str]],
) -> str:
"""Get category for workflow, preferring existing assignment over integration-based."""
# First priority: Use existing category from create_categories.py system
if filename in existing_categories:
return existing_categories[filename]
# Fallback: Use integration-based categorization
return determine_category(integrations, service_categories)
def determine_category(
integrations: List[str], categories: Dict[str, List[str]]
) -> str:
"""Determine the category for a workflow based on its integrations."""
if not integrations:
return "Uncategorized"
# Check each category for matching integrations
for category, services in categories.items():
for integration in integrations:
if integration in services:
return format_category_name(category)
return "Uncategorized"
def format_category_name(category_key: str) -> str:
"""Format category key to display name."""
category_mapping = {
"messaging": "Communication & Messaging",
"email": "Communication & Messaging",
"cloud_storage": "Cloud Storage & File Management",
"database": "Data Processing & Analysis",
"project_management": "Project Management",
"ai_ml": "AI Agent Development",
"social_media": "Social Media Management",
"ecommerce": "E-commerce & Retail",
"analytics": "Data Processing & Analysis",
"calendar_tasks": "Project Management",
"forms": "Data Processing & Analysis",
"development": "Technical Infrastructure & DevOps",
}
return category_mapping.get(category_key, category_key.replace("_", " ").title())
def get_category_list(categories: Dict[str, List[str]]) -> List[str]:
"""Get formatted list of all categories."""
formatted_categories = set()
for category_key in categories.keys():
formatted_categories.add(format_category_name(category_key))
# Add categories from the create_categories.py system
additional_categories = [
"Business Process Automation",
"Web Scraping & Data Extraction",
"Marketing & Advertising Automation",
"Creative Content & Video Automation",
"Creative Design Automation",
"CRM & Sales",
"Financial & Accounting",
]
for cat in additional_categories:
formatted_categories.add(cat)
return sorted(list(formatted_categories))
def get_popular_integrations(workflows: List[Dict]) -> List[Dict[str, Any]]:
"""Get list of popular integrations with counts."""
integration_counts = {}
for workflow in workflows:
for integration in workflow["integrations"]:
integration_counts[integration] = integration_counts.get(integration, 0) + 1
# Sort by count and take top 50
sorted_integrations = sorted(
integration_counts.items(), key=lambda x: x[1], reverse=True
)[:50]
return [{"name": name, "count": count} for name, count in sorted_integrations]
def extract_folder_from_filename(filename: str) -> str:
"""Extract folder name from workflow filename."""
# Most workflows follow pattern: ID_Service_Purpose_Trigger.json
# Extract the service name as folder
parts = filename.replace(".json", "").split("_")
if len(parts) >= 2:
return parts[1].capitalize() # Second part is usually the service
return "Misc"
def save_search_index(search_index: Dict[str, Any], output_dir: str):
"""Save the search index to multiple formats for different uses."""
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Save complete index
with open(
os.path.join(output_dir, "search-index.json"), "w", encoding="utf-8"
) as f:
json.dump(search_index, f, indent=2, ensure_ascii=False)
# Save stats only (for quick loading)
with open(os.path.join(output_dir, "stats.json"), "w", encoding="utf-8") as f:
json.dump(search_index["stats"], f, indent=2, ensure_ascii=False)
# Save categories only
with open(os.path.join(output_dir, "categories.json"), "w", encoding="utf-8") as f:
json.dump(search_index["categories"], f, indent=2, ensure_ascii=False)
# Save integrations only
with open(
os.path.join(output_dir, "integrations.json"), "w", encoding="utf-8"
) as f:
json.dump(search_index["integrations"], f, indent=2, ensure_ascii=False)
print("Search index generated successfully:")
print(f" {search_index['stats']['total_workflows']} workflows indexed")
print(f" {len(search_index['categories'])} categories")
print(f" {len(search_index['integrations'])} popular integrations")
print(f" Files saved to: {output_dir}")
def main():
"""Main function to generate search index."""
# Paths
db_path = "database/workflows.db"
output_dir = "docs/api"
# Check if database exists
if not os.path.exists(db_path):
print(f"Database not found: {db_path}")
print("Run 'python run.py --reindex' first to create the database")
sys.exit(1)
try:
print("Generating static search index...")
search_index = generate_static_search_index(db_path, output_dir)
save_search_index(search_index, output_dir)
print("Static search index ready for GitHub Pages!")
except Exception as e:
print(f"Error generating search index: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/scripts/update_readme_stats.py | scripts/update_readme_stats.py | #!/usr/bin/env python3
"""
Update README.md with current workflow statistics
Replaces hardcoded numbers with live data from the database.
"""
import os
import re
import sys
from pathlib import Path
from datetime import datetime
# Add the parent directory to path for imports
sys.path.append(str(Path(__file__).parent.parent))
from workflow_db import WorkflowDatabase
def get_current_stats():
"""Get current workflow statistics from the database."""
db_path = "database/workflows.db"
if not os.path.exists(db_path):
print("Database not found. Run workflow indexing first.")
return None
db = WorkflowDatabase(db_path)
stats = db.get_stats()
# Get categories count
categories = db.get_service_categories()
return {
"total_workflows": stats["total"],
"active_workflows": stats["active"],
"inactive_workflows": stats["inactive"],
"total_nodes": stats["total_nodes"],
"unique_integrations": stats["unique_integrations"],
"categories_count": len(get_category_list(categories)),
"triggers": stats["triggers"],
"complexity": stats["complexity"],
"last_updated": datetime.now().strftime("%Y-%m-%d"),
}
def get_category_list(categories):
"""Get formatted list of all categories (same logic as search index)."""
formatted_categories = set()
# Map technical categories to display names
category_mapping = {
"messaging": "Communication & Messaging",
"email": "Communication & Messaging",
"cloud_storage": "Cloud Storage & File Management",
"database": "Data Processing & Analysis",
"project_management": "Project Management",
"ai_ml": "AI Agent Development",
"social_media": "Social Media Management",
"ecommerce": "E-commerce & Retail",
"analytics": "Data Processing & Analysis",
"calendar_tasks": "Project Management",
"forms": "Data Processing & Analysis",
"development": "Technical Infrastructure & DevOps",
}
for category_key in categories.keys():
display_name = category_mapping.get(
category_key, category_key.replace("_", " ").title()
)
formatted_categories.add(display_name)
# Add categories from the create_categories.py system
additional_categories = [
"Business Process Automation",
"Web Scraping & Data Extraction",
"Marketing & Advertising Automation",
"Creative Content & Video Automation",
"Creative Design Automation",
"CRM & Sales",
"Financial & Accounting",
]
for cat in additional_categories:
formatted_categories.add(cat)
return sorted(list(formatted_categories))
def update_readme_stats(stats):
"""Update README.md with current statistics."""
readme_path = "README.md"
if not os.path.exists(readme_path):
print("README.md not found")
return False
with open(readme_path, "r", encoding="utf-8") as f:
content = f.read()
# Define replacement patterns and their new values
replacements = [
# Main collection description
(
r"A professionally organized collection of \*\*[\d,]+\s+n8n workflows\*\*",
f"A professionally organized collection of **{stats['total_workflows']:,} n8n workflows**",
),
# Total workflows in various contexts
(
r"- \*\*[\d,]+\s+workflows\*\* with meaningful",
f"- **{stats['total_workflows']:,} workflows** with meaningful",
),
# Statistics section
(
r"- \*\*Total Workflows\*\*: [\d,]+",
f"- **Total Workflows**: {stats['total_workflows']:,}",
),
(
r"- \*\*Active Workflows\*\*: [\d,]+ \([\d.]+%",
f"- **Active Workflows**: {stats['active_workflows']:,} ({(stats['active_workflows'] / stats['total_workflows'] * 100):.1f}%",
),
(
r"- \*\*Total Nodes\*\*: [\d,]+ \(avg [\d.]+ nodes",
f"- **Total Nodes**: {stats['total_nodes']:,} (avg {(stats['total_nodes'] / stats['total_workflows']):.1f} nodes",
),
(
r"- \*\*Unique Integrations\*\*: [\d,]+ different",
f"- **Unique Integrations**: {stats['unique_integrations']:,} different",
),
# Update complexity/trigger distribution
(
r"- \*\*Complex\*\*: [\d,]+ workflows \([\d.]+%\)",
f"- **Complex**: {stats['triggers'].get('Complex', 0):,} workflows ({(stats['triggers'].get('Complex', 0) / stats['total_workflows'] * 100):.1f}%)",
),
(
r"- \*\*Webhook\*\*: [\d,]+ workflows \([\d.]+%\)",
f"- **Webhook**: {stats['triggers'].get('Webhook', 0):,} workflows ({(stats['triggers'].get('Webhook', 0) / stats['total_workflows'] * 100):.1f}%)",
),
(
r"- \*\*Manual\*\*: [\d,]+ workflows \([\d.]+%\)",
f"- **Manual**: {stats['triggers'].get('Manual', 0):,} workflows ({(stats['triggers'].get('Manual', 0) / stats['total_workflows'] * 100):.1f}%)",
),
(
r"- \*\*Scheduled\*\*: [\d,]+ workflows \([\d.]+%\)",
f"- **Scheduled**: {stats['triggers'].get('Scheduled', 0):,} workflows ({(stats['triggers'].get('Scheduled', 0) / stats['total_workflows'] * 100):.1f}%)",
),
# Update total in current collection stats
(
r"\*\*Total Workflows\*\*: [\d,]+ automation",
f"**Total Workflows**: {stats['total_workflows']:,} automation",
),
(
r"\*\*Active Workflows\*\*: [\d,]+ \([\d.]+% active",
f"**Active Workflows**: {stats['active_workflows']:,} ({(stats['active_workflows'] / stats['total_workflows'] * 100):.1f}% active",
),
(
r"\*\*Total Nodes\*\*: [\d,]+ \(avg [\d.]+ nodes",
f"**Total Nodes**: {stats['total_nodes']:,} (avg {(stats['total_nodes'] / stats['total_workflows']):.1f} nodes",
),
(
r"\*\*Unique Integrations\*\*: [\d,]+ different",
f"**Unique Integrations**: {stats['unique_integrations']:,} different",
),
# Categories count
(
r"Our system automatically categorizes workflows into [\d]+ service categories",
f"Our system automatically categorizes workflows into {stats['categories_count']} service categories",
),
# Update any "2000+" references
(r"2000\+", f"{stats['total_workflows']:,}+"),
(r"2,000\+", f"{stats['total_workflows']:,}+"),
# Search across X workflows
(
r"Search across [\d,]+ workflows",
f"Search across {stats['total_workflows']:,} workflows",
),
# Instant search across X workflows
(
r"Instant search across [\d,]+ workflows",
f"Instant search across {stats['total_workflows']:,} workflows",
),
]
# Apply all replacements
updated_content = content
replacements_made = 0
for pattern, replacement in replacements:
old_content = updated_content
updated_content = re.sub(pattern, replacement, updated_content)
if updated_content != old_content:
replacements_made += 1
# Write back to file
with open(readme_path, "w", encoding="utf-8") as f:
f.write(updated_content)
print("README.md updated with current statistics:")
print(f" - Total workflows: {stats['total_workflows']:,}")
print(f" - Active workflows: {stats['active_workflows']:,}")
print(f" - Total nodes: {stats['total_nodes']:,}")
print(f" - Unique integrations: {stats['unique_integrations']:,}")
print(f" - Categories: {stats['categories_count']}")
print(f" - Replacements made: {replacements_made}")
return True
def main():
"""Main function to update README statistics."""
try:
print("Getting current workflow statistics...")
stats = get_current_stats()
if not stats:
print("Failed to get statistics")
sys.exit(1)
print("Updating README.md...")
success = update_readme_stats(stats)
if success:
print("README.md successfully updated with latest statistics!")
else:
print("Failed to update README.md")
sys.exit(1)
except Exception as e:
print(f"Error updating README stats: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/src/user_management.py | src/user_management.py | #!/usr/bin/env python3
"""
User Management System for N8N Workflows
Multi-user access control and authentication.
"""
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, EmailStr
from typing import List, Optional
import sqlite3
import hashlib
import secrets
import jwt
from datetime import datetime, timedelta
import os
# Configuration - Use environment variables for security
SECRET_KEY = os.environ.get("JWT_SECRET_KEY", secrets.token_urlsafe(32))
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# Security
security = HTTPBearer()
class User(BaseModel):
id: Optional[int] = None
username: str
email: EmailStr
full_name: str
role: str = "user"
active: bool = True
created_at: Optional[str] = None
class UserCreate(BaseModel):
username: str
email: EmailStr
full_name: str
password: str
role: str = "user"
class UserLogin(BaseModel):
username: str
password: str
class UserUpdate(BaseModel):
full_name: Optional[str] = None
email: Optional[EmailStr] = None
role: Optional[str] = None
active: Optional[bool] = None
class Token(BaseModel):
access_token: str
token_type: str
expires_in: int
class UserManager:
def __init__(self, db_path: str = "users.db"):
self.db_path = db_path
self.init_database()
def init_database(self):
"""Initialize user database."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
full_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
role TEXT DEFAULT 'user',
active BOOLEAN DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_login TIMESTAMP
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
token_hash TEXT UNIQUE NOT NULL,
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_permissions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
resource TEXT NOT NULL,
action TEXT NOT NULL,
granted BOOLEAN DEFAULT 1,
FOREIGN KEY (user_id) REFERENCES users (id)
)
""")
conn.commit()
conn.close()
# Create default admin user if none exists
self.create_default_admin()
def create_default_admin(self):
"""Create default admin user if none exists."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM users WHERE role = 'admin'")
admin_count = cursor.fetchone()[0]
if admin_count == 0:
# Use environment variable or generate secure random password
admin_password = os.environ.get("ADMIN_PASSWORD", secrets.token_urlsafe(16))
password_hash = self.hash_password(admin_password)
cursor.execute(
"""
INSERT INTO users (username, email, full_name, password_hash, role)
VALUES (?, ?, ?, ?, ?)
""",
(
"admin",
"admin@n8n-workflows.com",
"System Administrator",
password_hash,
"admin",
),
)
conn.commit()
# Only print password if it was auto-generated (not from env)
if "ADMIN_PASSWORD" not in os.environ:
print(f"Default admin user created: admin/{admin_password}")
print(
"WARNING: Please change this password immediately after first login!"
)
else:
print("Default admin user created with environment-configured password")
conn.close()
def hash_password(self, password: str) -> str:
"""Hash password using SHA-256."""
return hashlib.sha256(password.encode()).hexdigest()
def verify_password(self, password: str, hashed: str) -> bool:
"""Verify password against hash."""
return self.hash_password(password) == hashed
def create_user(self, user_data: UserCreate) -> User:
"""Create a new user."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
try:
# Check if username or email already exists
cursor.execute(
"SELECT COUNT(*) FROM users WHERE username = ? OR email = ?",
(user_data.username, user_data.email),
)
if cursor.fetchone()[0] > 0:
raise ValueError("Username or email already exists")
password_hash = self.hash_password(user_data.password)
cursor.execute(
"""
INSERT INTO users (username, email, full_name, password_hash, role)
VALUES (?, ?, ?, ?, ?)
""",
(
user_data.username,
user_data.email,
user_data.full_name,
password_hash,
user_data.role,
),
)
user_id = cursor.lastrowid
conn.commit()
return User(
id=user_id,
username=user_data.username,
email=user_data.email,
full_name=user_data.full_name,
role=user_data.role,
active=True,
created_at=datetime.now().isoformat(),
)
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def authenticate_user(self, username: str, password: str) -> Optional[User]:
"""Authenticate user and return user data."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT id, username, email, full_name, password_hash, role, active
FROM users WHERE username = ? AND active = 1
""",
(username,),
)
row = cursor.fetchone()
conn.close()
if row and self.verify_password(password, row[4]):
return User(
id=row[0],
username=row[1],
email=row[2],
full_name=row[3],
role=row[5],
active=bool(row[6]),
)
return None
def create_access_token(self, user: User) -> str:
"""Create JWT access token."""
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode = {
"sub": str(user.id),
"username": user.username,
"role": user.role,
"exp": expire,
}
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def verify_token(self, token: str) -> Optional[User]:
"""Verify JWT token and return user data."""
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id = payload.get("sub")
username = payload.get("username")
role = payload.get("role")
if user_id is None or username is None:
return None
return User(id=int(user_id), username=username, role=role)
except jwt.PyJWTError:
return None
def get_user_by_id(self, user_id: int) -> Optional[User]:
"""Get user by ID."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT id, username, email, full_name, role, active, created_at
FROM users WHERE id = ?
""",
(user_id,),
)
row = cursor.fetchone()
conn.close()
if row:
return User(
id=row[0],
username=row[1],
email=row[2],
full_name=row[3],
role=row[4],
active=bool(row[5]),
created_at=row[6],
)
return None
def get_all_users(self) -> List[User]:
"""Get all users."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
SELECT id, username, email, full_name, role, active, created_at
FROM users ORDER BY created_at DESC
""")
users = []
for row in cursor.fetchall():
users.append(
User(
id=row[0],
username=row[1],
email=row[2],
full_name=row[3],
role=row[4],
active=bool(row[5]),
created_at=row[6],
)
)
conn.close()
return users
def update_user(self, user_id: int, update_data: UserUpdate) -> Optional[User]:
"""Update user data."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
try:
# Build update query dynamically
updates = []
params = []
if update_data.full_name is not None:
updates.append("full_name = ?")
params.append(update_data.full_name)
if update_data.email is not None:
updates.append("email = ?")
params.append(update_data.email)
if update_data.role is not None:
updates.append("role = ?")
params.append(update_data.role)
if update_data.active is not None:
updates.append("active = ?")
params.append(update_data.active)
if not updates:
return self.get_user_by_id(user_id)
params.append(user_id)
query = f"UPDATE users SET {', '.join(updates)} WHERE id = ?"
cursor.execute(query, params)
conn.commit()
return self.get_user_by_id(user_id)
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def delete_user(self, user_id: int) -> bool:
"""Delete user (soft delete by setting active=False)."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
try:
cursor.execute("UPDATE users SET active = 0 WHERE id = ?", (user_id,))
conn.commit()
return cursor.rowcount > 0
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
# Initialize user manager
user_manager = UserManager()
# FastAPI app for User Management
user_app = FastAPI(title="N8N User Management", version="1.0.0")
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
) -> User:
"""Get current authenticated user."""
token = credentials.credentials
user = user_manager.verify_token(token)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return user
def require_admin(current_user: User = Depends(get_current_user)) -> User:
"""Require admin role."""
if current_user.role != "admin":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required"
)
return current_user
@user_app.post("/auth/register", response_model=User)
async def register_user(user_data: UserCreate):
"""Register a new user."""
try:
user = user_manager.create_user(user_data)
return user
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@user_app.post("/auth/login", response_model=Token)
async def login_user(login_data: UserLogin):
"""Login user and return access token."""
user = user_manager.authenticate_user(login_data.username, login_data.password)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = user_manager.create_access_token(user)
return Token(
access_token=access_token,
token_type="bearer",
expires_in=ACCESS_TOKEN_EXPIRE_MINUTES * 60,
)
@user_app.get("/auth/me", response_model=User)
async def get_current_user_info(current_user: User = Depends(get_current_user)):
"""Get current user information."""
return current_user
@user_app.get("/users", response_model=List[User])
async def get_all_users(admin: User = Depends(require_admin)):
"""Get all users (admin only)."""
return user_manager.get_all_users()
@user_app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int, current_user: User = Depends(get_current_user)):
"""Get user by ID."""
# Users can only view their own profile unless they're admin
if current_user.id != user_id and current_user.role != "admin":
raise HTTPException(status_code=403, detail="Access denied")
user = user_manager.get_user_by_id(user_id)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
@user_app.put("/users/{user_id}", response_model=User)
async def update_user(
user_id: int,
update_data: UserUpdate,
current_user: User = Depends(get_current_user),
):
"""Update user data."""
# Users can only update their own profile unless they're admin
if current_user.id != user_id and current_user.role != "admin":
raise HTTPException(status_code=403, detail="Access denied")
# Non-admin users cannot change roles
if current_user.role != "admin" and update_data.role is not None:
raise HTTPException(status_code=403, detail="Cannot change role")
user = user_manager.update_user(user_id, update_data)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
@user_app.delete("/users/{user_id}")
async def delete_user(user_id: int, admin: User = Depends(require_admin)):
"""Delete user (admin only)."""
success = user_manager.delete_user(user_id)
if not success:
raise HTTPException(status_code=404, detail="User not found")
return {"message": "User deleted successfully"}
@user_app.get("/auth/dashboard")
async def get_auth_dashboard():
"""Get authentication dashboard HTML."""
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N8N User Management</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
color: #333;
}
.dashboard {
max-width: 1000px;
margin: 0 auto;
padding: 20px;
}
.header {
background: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}
.header h1 {
font-size: 32px;
margin-bottom: 10px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.auth-section {
background: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.auth-tabs {
display: flex;
margin-bottom: 20px;
border-bottom: 2px solid #e9ecef;
}
.tab {
padding: 15px 30px;
cursor: pointer;
border-bottom: 3px solid transparent;
transition: all 0.3s ease;
}
.tab.active {
border-bottom-color: #667eea;
color: #667eea;
font-weight: bold;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: #333;
}
.form-group input {
width: 100%;
padding: 12px;
border: 2px solid #e9ecef;
border-radius: 8px;
font-size: 16px;
transition: border-color 0.3s ease;
}
.form-group input:focus {
outline: none;
border-color: #667eea;
}
.btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
transition: all 0.3s ease;
text-decoration: none;
display: inline-block;
text-align: center;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5a6fd8;
}
.btn-secondary {
background: #f8f9fa;
color: #666;
border: 1px solid #e9ecef;
}
.btn-secondary:hover {
background: #e9ecef;
}
.user-list {
background: white;
padding: 30px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.user-card {
background: #f8f9fa;
padding: 20px;
border-radius: 10px;
margin-bottom: 15px;
display: flex;
justify-content: space-between;
align-items: center;
}
.user-info h3 {
margin-bottom: 5px;
color: #333;
}
.user-info p {
color: #666;
font-size: 14px;
}
.user-role {
background: #667eea;
color: white;
padding: 4px 12px;
border-radius: 15px;
font-size: 12px;
font-weight: bold;
}
.user-role.admin {
background: #dc3545;
}
.status-indicator {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 8px;
}
.status-online {
background: #28a745;
}
.status-offline {
background: #dc3545;
}
.message {
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
display: none;
}
.message.success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.message.error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
</style>
</head>
<body>
<div class="dashboard">
<div class="header">
<h1>👥 N8N User Management</h1>
<p>Manage users, roles, and access control for your workflow platform</p>
</div>
<div class="auth-section">
<div class="auth-tabs">
<div class="tab active" onclick="showTab('login')">Login</div>
<div class="tab" onclick="showTab('register')">Register</div>
</div>
<div id="message" class="message"></div>
<div id="login" class="tab-content active">
<h2>Login to Your Account</h2>
<form id="loginForm">
<div class="form-group">
<label for="loginUsername">Username</label>
<input type="text" id="loginUsername" required>
</div>
<div class="form-group">
<label for="loginPassword">Password</label>
<input type="password" id="loginPassword" required>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
<div id="register" class="tab-content">
<h2>Create New Account</h2>
<form id="registerForm">
<div class="form-group">
<label for="regUsername">Username</label>
<input type="text" id="regUsername" required>
</div>
<div class="form-group">
<label for="regEmail">Email</label>
<input type="email" id="regEmail" required>
</div>
<div class="form-group">
<label for="regFullName">Full Name</label>
<input type="text" id="regFullName" required>
</div>
<div class="form-group">
<label for="regPassword">Password</label>
<input type="password" id="regPassword" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
<div class="user-list" id="userList" style="display: none;">
<h2>User Management</h2>
<div id="usersContainer">
<div class="loading">Loading users...</div>
</div>
</div>
</div>
<script>
let currentUser = null;
let authToken = null;
function showTab(tabName) {
// Hide all tabs
document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
// Show selected tab
event.target.classList.add('active');
document.getElementById(tabName).classList.add('active');
}
function showMessage(message, type) {
const messageDiv = document.getElementById('message');
messageDiv.textContent = message;
messageDiv.className = `message ${type}`;
messageDiv.style.display = 'block';
setTimeout(() => {
messageDiv.style.display = 'none';
}, 5000);
}
async function login(username, password) {
try {
const response = await fetch('/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username, password})
});
if (response.ok) {
const data = await response.json();
authToken = data.access_token;
currentUser = await getCurrentUser();
showMessage('Login successful!', 'success');
loadUsers();
} else {
const error = await response.json();
showMessage(error.detail || 'Login failed', 'error');
}
} catch (error) {
showMessage('Login error: ' + error.message, 'error');
}
}
async function register(username, email, fullName, password) {
try {
const response = await fetch('/auth/register', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username, email, full_name: fullName, password, role: 'user'})
});
if (response.ok) {
showMessage('Registration successful! Please login.', 'success');
showTab('login');
} else {
const error = await response.json();
showMessage(error.detail || 'Registration failed', 'error');
}
} catch (error) {
showMessage('Registration error: ' + error.message, 'error');
}
}
async function getCurrentUser() {
if (!authToken) return null;
try {
const response = await fetch('/auth/me', {
headers: {'Authorization': `Bearer ${authToken}`}
});
if (response.ok) {
return await response.json();
}
} catch (error) {
console.error('Error getting current user:', error);
}
return null;
}
async function loadUsers() {
if (!authToken) return;
try {
const response = await fetch('/users', {
headers: {'Authorization': `Bearer ${authToken}`}
});
if (response.ok) {
const users = await response.json();
displayUsers(users);
document.getElementById('userList').style.display = 'block';
} else {
showMessage('Failed to load users', 'error');
}
} catch (error) {
showMessage('Error loading users: ' + error.message, 'error');
}
}
function displayUsers(users) {
const container = document.getElementById('usersContainer');
container.innerHTML = users.map(user => `
<div class="user-card">
<div class="user-info">
<h3>${user.full_name}</h3>
<p>@${user.username} • ${user.email}</p>
</div>
<div>
<span class="user-role ${user.role}">${user.role.toUpperCase()}</span>
<span class="status-indicator ${user.active ? 'status-online' : 'status-offline'}"></span>
</div>
</div>
`).join('');
}
// Event listeners
document.getElementById('loginForm').addEventListener('submit', (e) => {
e.preventDefault();
const username = document.getElementById('loginUsername').value;
const password = document.getElementById('loginPassword').value;
login(username, password);
});
document.getElementById('registerForm').addEventListener('submit', (e) => {
e.preventDefault();
const username = document.getElementById('regUsername').value;
const email = document.getElementById('regEmail').value;
const fullName = document.getElementById('regFullName').value;
const password = document.getElementById('regPassword').value;
register(username, email, fullName, password);
});
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(user_app, host="127.0.0.1", port=8004)
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/src/ai_assistant.py | src/ai_assistant.py | #!/usr/bin/env python3
"""
AI Assistant for N8N Workflow Discovery
Intelligent chat interface for finding and understanding workflows.
"""
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import List, Dict, Optional
import json
import sqlite3
class ChatMessage(BaseModel):
message: str
user_id: Optional[str] = None
class AIResponse(BaseModel):
response: str
workflows: List[Dict] = []
suggestions: List[str] = []
confidence: float = 0.0
class WorkflowAssistant:
def __init__(self, db_path: str = "workflows.db"):
self.db_path = db_path
self.conversation_history = {}
def get_db_connection(self):
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
return conn
def search_workflows_intelligent(self, query: str, limit: int = 5) -> List[Dict]:
"""Intelligent workflow search based on natural language query."""
conn = self.get_db_connection()
# Extract keywords and intent from query
keywords = self.extract_keywords(query)
intent = self.detect_intent(query)
# Build search query
search_terms = []
for keyword in keywords:
search_terms.append(
f"name LIKE '%{keyword}%' OR description LIKE '%{keyword}%'"
)
where_clause = " OR ".join(search_terms) if search_terms else "1=1"
# Add intent-based filtering
if intent == "automation":
where_clause += (
" AND (trigger_type = 'Scheduled' OR trigger_type = 'Complex')"
)
elif intent == "integration":
where_clause += " AND trigger_type = ?"
params.append('Webhook')
elif intent == "manual":
where_clause += " AND trigger_type = 'Manual'"
query_sql = f"""
SELECT * FROM workflows
WHERE {where_clause}
ORDER BY
CASE WHEN active = 1 THEN 1 ELSE 2 END,
node_count DESC
LIMIT ?
"""
cursor = conn.execute(query_sql)
workflows = []
for row in cursor.fetchall():
workflow = dict(row)
workflow["integrations"] = json.loads(workflow["integrations"] or "[]")
workflow["tags"] = json.loads(workflow["tags"] or "[]")
workflows.append(workflow)
conn.close()
return workflows
def extract_keywords(self, query: str) -> List[str]:
"""Extract relevant keywords from user query."""
# Common automation terms
automation_terms = {
"email": ["email", "gmail", "mail"],
"social": ["twitter", "facebook", "instagram", "linkedin", "social"],
"data": ["data", "database", "spreadsheet", "csv", "excel"],
"ai": ["ai", "openai", "chatgpt", "artificial", "intelligence"],
"notification": ["notification", "alert", "slack", "telegram", "discord"],
"automation": ["automation", "workflow", "process", "automate"],
"integration": ["integration", "connect", "sync", "api"],
}
query_lower = query.lower()
keywords = []
for category, terms in automation_terms.items():
for term in terms:
if term in query_lower:
keywords.append(term)
# Extract specific service names
services = [
"slack",
"telegram",
"openai",
"google",
"microsoft",
"shopify",
"airtable",
]
for service in services:
if service in query_lower:
keywords.append(service)
return list(set(keywords))
def detect_intent(self, query: str) -> str:
"""Detect user intent from query."""
query_lower = query.lower()
if any(
word in query_lower
for word in ["automate", "schedule", "recurring", "daily", "weekly"]
):
return "automation"
elif any(
word in query_lower for word in ["connect", "integrate", "sync", "webhook"]
):
return "integration"
elif any(
word in query_lower for word in ["manual", "trigger", "button", "click"]
):
return "manual"
elif any(
word in query_lower for word in ["ai", "chat", "assistant", "intelligent"]
):
return "ai"
else:
return "general"
def generate_response(self, query: str, workflows: List[Dict]) -> str:
"""Generate natural language response based on query and workflows."""
if not workflows:
return "I couldn't find any workflows matching your request. Try searching for specific services like 'Slack', 'OpenAI', or 'Email automation'."
# Analyze workflow patterns
trigger_types = [w["trigger_type"] for w in workflows]
integrations = []
for w in workflows:
integrations.extend(w["integrations"])
common_integrations = list(set(integrations))[:3]
most_common_trigger = max(set(trigger_types), key=trigger_types.count)
# Generate contextual response
response_parts = []
if len(workflows) == 1:
workflow = workflows[0]
response_parts.append(f"I found a perfect match: **{workflow['name']}**")
response_parts.append(
f"This is a {workflow['trigger_type'].lower()} workflow that {workflow['description'].lower()}"
)
else:
response_parts.append(f"I found {len(workflows)} relevant workflows:")
for i, workflow in enumerate(workflows[:3], 1):
response_parts.append(
f"{i}. **{workflow['name']}** - {workflow['description']}"
)
if common_integrations:
response_parts.append(
f"\nThese workflows commonly use: {', '.join(common_integrations)}"
)
if most_common_trigger != "all":
response_parts.append(
f"Most are {most_common_trigger.lower()} triggered workflows."
)
return "\n".join(response_parts)
def get_suggestions(self, query: str) -> List[str]:
"""Generate helpful suggestions based on query."""
suggestions = []
if "email" in query.lower():
suggestions.extend(
[
"Email automation workflows",
"Gmail integration examples",
"Email notification systems",
]
)
elif "ai" in query.lower() or "openai" in query.lower():
suggestions.extend(
[
"AI-powered workflows",
"OpenAI integration examples",
"Chatbot automation",
]
)
elif "social" in query.lower():
suggestions.extend(
[
"Social media automation",
"Twitter integration workflows",
"LinkedIn automation",
]
)
else:
suggestions.extend(
[
"Popular automation patterns",
"Webhook-triggered workflows",
"Scheduled automation examples",
]
)
return suggestions[:3]
def calculate_confidence(self, query: str, workflows: List[Dict]) -> float:
"""Calculate confidence score for the response."""
if not workflows:
return 0.0
# Base confidence on number of matches and relevance
base_confidence = min(len(workflows) / 5.0, 1.0)
# Boost confidence for exact matches
query_lower = query.lower()
exact_matches = 0
for workflow in workflows:
if any(word in workflow["name"].lower() for word in query_lower.split()):
exact_matches += 1
if exact_matches > 0:
base_confidence += 0.2
return min(base_confidence, 1.0)
# Initialize assistant
assistant = WorkflowAssistant()
# FastAPI app for AI Assistant
ai_app = FastAPI(title="N8N AI Assistant", version="1.0.0")
@ai_app.post("/chat", response_model=AIResponse)
async def chat_with_assistant(message: ChatMessage):
"""Chat with the AI assistant to discover workflows."""
try:
# Search for relevant workflows
workflows = assistant.search_workflows_intelligent(message.message, limit=5)
# Generate response
response_text = assistant.generate_response(message.message, workflows)
# Get suggestions
suggestions = assistant.get_suggestions(message.message)
# Calculate confidence
confidence = assistant.calculate_confidence(message.message, workflows)
return AIResponse(
response=response_text,
workflows=workflows,
suggestions=suggestions,
confidence=confidence,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Assistant error: {str(e)}")
@ai_app.get("/chat/interface")
async def chat_interface():
"""Get the chat interface HTML."""
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N8N AI Assistant</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.chat-container {
width: 90%;
max-width: 800px;
height: 80vh;
background: white;
border-radius: 20px;
box-shadow: 0 20px 40px rgba(0,0,0,0.1);
display: flex;
flex-direction: column;
overflow: hidden;
}
.chat-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
text-align: center;
}
.chat-header h1 {
font-size: 24px;
margin-bottom: 5px;
}
.chat-messages {
flex: 1;
padding: 20px;
overflow-y: auto;
background: #f8f9fa;
}
.message {
margin-bottom: 15px;
display: flex;
align-items: flex-start;
}
.message.user {
justify-content: flex-end;
}
.message.assistant {
justify-content: flex-start;
}
.message-content {
max-width: 70%;
padding: 15px 20px;
border-radius: 20px;
word-wrap: break-word;
}
.message.user .message-content {
background: #667eea;
color: white;
border-bottom-right-radius: 5px;
}
.message.assistant .message-content {
background: white;
color: #333;
border: 1px solid #e9ecef;
border-bottom-left-radius: 5px;
}
.workflow-card {
background: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 10px;
padding: 15px;
margin: 10px 0;
}
.workflow-title {
font-weight: bold;
color: #667eea;
margin-bottom: 5px;
}
.workflow-description {
color: #666;
font-size: 14px;
margin-bottom: 10px;
}
.workflow-meta {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.meta-tag {
background: #e9ecef;
padding: 4px 8px;
border-radius: 12px;
font-size: 12px;
color: #666;
}
.suggestions {
margin-top: 10px;
}
.suggestion {
background: #e3f2fd;
color: #1976d2;
padding: 8px 12px;
border-radius: 15px;
margin: 5px 5px 5px 0;
display: inline-block;
cursor: pointer;
font-size: 14px;
transition: all 0.3s ease;
}
.suggestion:hover {
background: #1976d2;
color: white;
}
.chat-input {
padding: 20px;
background: white;
border-top: 1px solid #e9ecef;
display: flex;
gap: 10px;
}
.chat-input input {
flex: 1;
padding: 15px;
border: 2px solid #e9ecef;
border-radius: 25px;
font-size: 16px;
outline: none;
transition: border-color 0.3s ease;
}
.chat-input input:focus {
border-color: #667eea;
}
.send-btn {
background: #667eea;
color: white;
border: none;
border-radius: 50%;
width: 50px;
height: 50px;
cursor: pointer;
font-size: 18px;
transition: all 0.3s ease;
}
.send-btn:hover {
background: #5a6fd8;
transform: scale(1.05);
}
.typing {
color: #666;
font-style: italic;
}
</style>
</head>
<body>
<div class="chat-container">
<div class="chat-header">
<h1>🤖 N8N AI Assistant</h1>
<p>Ask me about workflows and automation</p>
</div>
<div class="chat-messages" id="chatMessages">
<div class="message assistant">
<div class="message-content">
👋 Hi! I'm your N8N workflow assistant. I can help you find workflows for:
<div class="suggestions">
<span class="suggestion" onclick="sendMessage('Show me email automation workflows')">Email automation</span>
<span class="suggestion" onclick="sendMessage('Find AI-powered workflows')">AI workflows</span>
<span class="suggestion" onclick="sendMessage('Show me Slack integrations')">Slack integrations</span>
<span class="suggestion" onclick="sendMessage('Find webhook workflows')">Webhook workflows</span>
</div>
</div>
</div>
</div>
<div class="chat-input">
<input type="text" id="messageInput" placeholder="Ask about workflows..." onkeypress="handleKeyPress(event)">
<button class="send-btn" onclick="sendMessage()">➤</button>
</div>
</div>
<script>
async function sendMessage(message = null) {
const input = document.getElementById('messageInput');
const messageText = message || input.value.trim();
if (!messageText) return;
// Add user message
addMessage(messageText, 'user');
input.value = '';
// Show typing indicator
const typingId = addMessage('Thinking...', 'assistant', true);
try {
const response = await fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: messageText })
});
const data = await response.json();
// Remove typing indicator
document.getElementById(typingId).remove();
// Add assistant response
addAssistantMessage(data);
} catch (error) {
document.getElementById(typingId).remove();
addMessage('Sorry, I encountered an error. Please try again.', 'assistant');
}
}
function addMessage(text, sender, isTyping = false) {
const messagesContainer = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
const messageId = 'msg_' + Date.now();
messageDiv.id = messageId;
messageDiv.className = `message ${sender}`;
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
if (isTyping) {
contentDiv.className += ' typing';
}
contentDiv.textContent = text;
messageDiv.appendChild(contentDiv);
messagesContainer.appendChild(messageDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
return messageId;
}
function addAssistantMessage(data) {
const messagesContainer = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = 'message assistant';
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
// Add response text
contentDiv.innerHTML = data.response.replace(/\\*\\*(.*?)\\*\\*/g, '<strong>$1</strong>');
// Add workflow cards
if (data.workflows && data.workflows.length > 0) {
data.workflows.forEach(workflow => {
const workflowCard = document.createElement('div');
workflowCard.className = 'workflow-card';
workflowCard.innerHTML = `
<div class="workflow-title">${workflow.name}</div>
<div class="workflow-description">${workflow.description}</div>
<div class="workflow-meta">
<span class="meta-tag">${workflow.trigger_type}</span>
<span class="meta-tag">${workflow.complexity}</span>
<span class="meta-tag">${workflow.node_count} nodes</span>
${workflow.active ? '<span class="meta-tag" style="background: #d4edda; color: #155724;">Active</span>' : ''}
</div>
`;
contentDiv.appendChild(workflowCard);
});
}
// Add suggestions
if (data.suggestions && data.suggestions.length > 0) {
const suggestionsDiv = document.createElement('div');
suggestionsDiv.className = 'suggestions';
data.suggestions.forEach(suggestion => {
const suggestionSpan = document.createElement('span');
suggestionSpan.className = 'suggestion';
suggestionSpan.textContent = suggestion;
suggestionSpan.onclick = () => sendMessage(suggestion);
suggestionsDiv.appendChild(suggestionSpan);
});
contentDiv.appendChild(suggestionsDiv);
}
messageDiv.appendChild(contentDiv);
messagesContainer.appendChild(messageDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
function handleKeyPress(event) {
if (event.key === 'Enter') {
sendMessage();
}
}
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(ai_app, host="127.0.0.1", port=8001)
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/src/performance_monitor.py | src/performance_monitor.py | #!/usr/bin/env python3
"""
Performance Monitoring System for N8N Workflows
Real-time metrics, monitoring, and alerting.
"""
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import List, Dict, Any
import asyncio
import time
import psutil
from datetime import datetime, timedelta
import json
import threading
import queue
import os
class PerformanceMetrics(BaseModel):
timestamp: str
cpu_usage: float
memory_usage: float
disk_usage: float
network_io: Dict[str, int]
api_response_times: Dict[str, float]
active_connections: int
database_size: int
workflow_executions: int
error_rate: float
class Alert(BaseModel):
id: str
type: str
severity: str
message: str
timestamp: str
resolved: bool = False
class PerformanceMonitor:
def __init__(self, db_path: str = "workflows.db"):
self.db_path = db_path
self.metrics_history = []
self.alerts = []
self.websocket_connections = []
self.monitoring_active = False
self.metrics_queue = queue.Queue()
def start_monitoring(self):
"""Start performance monitoring in background thread."""
if not self.monitoring_active:
self.monitoring_active = True
monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
monitor_thread.start()
def _monitor_loop(self):
"""Main monitoring loop."""
while self.monitoring_active:
try:
metrics = self._collect_metrics()
self.metrics_history.append(metrics)
# Keep only last 1000 metrics
if len(self.metrics_history) > 1000:
self.metrics_history = self.metrics_history[-1000:]
# Check for alerts
self._check_alerts(metrics)
# Send to websocket connections
self._broadcast_metrics(metrics)
time.sleep(5) # Collect metrics every 5 seconds
except Exception as e:
print(f"Monitoring error: {e}")
time.sleep(10)
def _collect_metrics(self) -> PerformanceMetrics:
"""Collect current system metrics."""
# CPU and Memory
cpu_usage = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
memory_usage = memory.percent
# Disk usage
disk = psutil.disk_usage("/")
disk_usage = (disk.used / disk.total) * 100
# Network I/O
network = psutil.net_io_counters()
network_io = {
"bytes_sent": network.bytes_sent,
"bytes_recv": network.bytes_recv,
"packets_sent": network.packets_sent,
"packets_recv": network.packets_recv,
}
# API response times (simulated)
api_response_times = {
"/api/stats": self._measure_api_time("/api/stats"),
"/api/workflows": self._measure_api_time("/api/workflows"),
"/api/search": self._measure_api_time("/api/workflows?q=test"),
}
# Active connections
active_connections = len(psutil.net_connections())
# Database size
try:
db_size = (
os.path.getsize(self.db_path) if os.path.exists(self.db_path) else 0
)
except:
db_size = 0
# Workflow executions (simulated)
workflow_executions = self._get_workflow_executions()
# Error rate (simulated)
error_rate = self._calculate_error_rate()
return PerformanceMetrics(
timestamp=datetime.now().isoformat(),
cpu_usage=cpu_usage,
memory_usage=memory_usage,
disk_usage=disk_usage,
network_io=network_io,
api_response_times=api_response_times,
active_connections=active_connections,
database_size=db_size,
workflow_executions=workflow_executions,
error_rate=error_rate,
)
def _measure_api_time(self, endpoint: str) -> float:
"""Measure API response time (simulated)."""
# In a real implementation, this would make actual HTTP requests
import random
return round(random.uniform(10, 100), 2)
def _get_workflow_executions(self) -> int:
"""Get number of workflow executions (simulated)."""
# In a real implementation, this would query execution logs
import random
return random.randint(0, 50)
def _calculate_error_rate(self) -> float:
"""Calculate error rate (simulated)."""
# In a real implementation, this would analyze error logs
import random
return round(random.uniform(0, 5), 2)
def _check_alerts(self, metrics: PerformanceMetrics):
"""Check metrics against alert thresholds."""
# CPU alert
if metrics.cpu_usage > 80:
self._create_alert(
"high_cpu", "warning", f"High CPU usage: {metrics.cpu_usage}%"
)
# Memory alert
if metrics.memory_usage > 85:
self._create_alert(
"high_memory", "warning", f"High memory usage: {metrics.memory_usage}%"
)
# Disk alert
if metrics.disk_usage > 90:
self._create_alert(
"high_disk", "critical", f"High disk usage: {metrics.disk_usage}%"
)
# API response time alert
for endpoint, response_time in metrics.api_response_times.items():
if response_time > 1000: # 1 second
self._create_alert(
"slow_api",
"warning",
f"Slow API response: {endpoint} ({response_time}ms)",
)
# Error rate alert
if metrics.error_rate > 10:
self._create_alert(
"high_error_rate", "critical", f"High error rate: {metrics.error_rate}%"
)
def _create_alert(self, alert_type: str, severity: str, message: str):
"""Create a new alert."""
alert = Alert(
id=f"{alert_type}_{int(time.time())}",
type=alert_type,
severity=severity,
message=message,
timestamp=datetime.now().isoformat(),
)
# Check if similar alert already exists
existing_alert = next(
(a for a in self.alerts if a.type == alert_type and not a.resolved), None
)
if not existing_alert:
self.alerts.append(alert)
self._broadcast_alert(alert)
def _broadcast_metrics(self, metrics: PerformanceMetrics):
"""Broadcast metrics to all websocket connections."""
if self.websocket_connections:
message = {"type": "metrics", "data": metrics.dict()}
self._broadcast_to_websockets(message)
def _broadcast_alert(self, alert: Alert):
"""Broadcast alert to all websocket connections."""
message = {"type": "alert", "data": alert.dict()}
self._broadcast_to_websockets(message)
def _broadcast_to_websockets(self, message: dict):
"""Broadcast message to all websocket connections."""
disconnected = []
for websocket in self.websocket_connections:
try:
asyncio.create_task(websocket.send_text(json.dumps(message)))
except:
disconnected.append(websocket)
# Remove disconnected connections
for ws in disconnected:
self.websocket_connections.remove(ws)
def get_metrics_summary(self) -> Dict[str, Any]:
"""Get performance metrics summary."""
if not self.metrics_history:
return {"message": "No metrics available"}
latest = self.metrics_history[-1]
avg_cpu = sum(m.cpu_usage for m in self.metrics_history[-10:]) / min(
10, len(self.metrics_history)
)
avg_memory = sum(m.memory_usage for m in self.metrics_history[-10:]) / min(
10, len(self.metrics_history)
)
return {
"current": latest.dict(),
"averages": {
"cpu_usage": round(avg_cpu, 2),
"memory_usage": round(avg_memory, 2),
},
"alerts": [alert.dict() for alert in self.alerts[-10:]],
"status": "healthy"
if latest.cpu_usage < 80 and latest.memory_usage < 85
else "warning",
}
def get_historical_metrics(self, hours: int = 24) -> List[Dict]:
"""Get historical metrics for specified hours."""
cutoff_time = datetime.now() - timedelta(hours=hours)
cutoff_timestamp = cutoff_time.isoformat()
return [
metrics.dict()
for metrics in self.metrics_history
if metrics.timestamp >= cutoff_timestamp
]
def resolve_alert(self, alert_id: str) -> bool:
"""Resolve an alert."""
for alert in self.alerts:
if alert.id == alert_id:
alert.resolved = True
return True
return False
# Initialize performance monitor
performance_monitor = PerformanceMonitor()
performance_monitor.start_monitoring()
# FastAPI app for Performance Monitoring
monitor_app = FastAPI(title="N8N Performance Monitor", version="1.0.0")
@monitor_app.get("/monitor/metrics")
async def get_current_metrics():
"""Get current performance metrics."""
return performance_monitor.get_metrics_summary()
@monitor_app.get("/monitor/history")
async def get_historical_metrics(hours: int = 24):
"""Get historical performance metrics."""
return performance_monitor.get_historical_metrics(hours)
@monitor_app.get("/monitor/alerts")
async def get_alerts():
"""Get current alerts."""
return [alert.dict() for alert in performance_monitor.alerts if not alert.resolved]
@monitor_app.post("/monitor/alerts/{alert_id}/resolve")
async def resolve_alert(alert_id: str):
"""Resolve an alert."""
success = performance_monitor.resolve_alert(alert_id)
if success:
return {"message": "Alert resolved"}
else:
return {"message": "Alert not found"}
@monitor_app.websocket("/monitor/ws")
async def websocket_endpoint(websocket: WebSocket):
"""WebSocket endpoint for real-time metrics."""
await websocket.accept()
performance_monitor.websocket_connections.append(websocket)
try:
while True:
# Keep connection alive
await websocket.receive_text()
except WebSocketDisconnect:
performance_monitor.websocket_connections.remove(websocket)
@monitor_app.get("/monitor/dashboard")
async def get_monitoring_dashboard():
"""Get performance monitoring dashboard HTML."""
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N8N Performance Monitor</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f8f9fa;
color: #333;
}
.dashboard {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
text-align: center;
}
.header h1 {
font-size: 32px;
margin-bottom: 10px;
}
.metrics-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.metric-card {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
text-align: center;
}
.metric-value {
font-size: 36px;
font-weight: bold;
margin-bottom: 10px;
}
.metric-value.cpu { color: #667eea; }
.metric-value.memory { color: #28a745; }
.metric-value.disk { color: #ffc107; }
.metric-value.network { color: #17a2b8; }
.metric-label {
color: #666;
font-size: 16px;
}
.status-indicator {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: 8px;
}
.status-healthy { background: #28a745; }
.status-warning { background: #ffc107; }
.status-critical { background: #dc3545; }
.chart-container {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
margin-bottom: 30px;
}
.chart-title {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
color: #333;
}
.alerts-section {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.alert {
background: #f8f9fa;
padding: 15px;
border-radius: 10px;
margin-bottom: 10px;
border-left: 4px solid #667eea;
}
.alert.warning {
border-left-color: #ffc107;
background: #fff3cd;
}
.alert.critical {
border-left-color: #dc3545;
background: #f8d7da;
}
.alert-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 5px;
}
.alert-type {
font-weight: bold;
color: #333;
}
.alert-severity {
padding: 4px 8px;
border-radius: 12px;
font-size: 12px;
font-weight: bold;
text-transform: uppercase;
}
.severity-warning {
background: #ffc107;
color: #856404;
}
.severity-critical {
background: #dc3545;
color: white;
}
.alert-message {
color: #666;
font-size: 14px;
}
.alert-timestamp {
color: #999;
font-size: 12px;
margin-top: 5px;
}
.resolve-btn {
background: #28a745;
color: white;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
}
.resolve-btn:hover {
background: #218838;
}
</style>
</head>
<body>
<div class="dashboard">
<div class="header">
<h1>📊 N8N Performance Monitor</h1>
<p>Real-time system monitoring and alerting</p>
<div id="connectionStatus">
<span class="status-indicator" id="statusIndicator"></span>
<span id="statusText">Connecting...</span>
</div>
</div>
<div class="metrics-grid" id="metricsGrid">
<div class="loading">Loading metrics...</div>
</div>
<div class="chart-container">
<div class="chart-title">CPU & Memory Usage</div>
<canvas id="performanceChart" width="400" height="200"></canvas>
</div>
<div class="chart-container">
<div class="chart-title">API Response Times</div>
<canvas id="apiChart" width="400" height="200"></canvas>
</div>
<div class="alerts-section">
<div class="chart-title">Active Alerts</div>
<div id="alertsContainer">
<div class="loading">Loading alerts...</div>
</div>
</div>
</div>
<script>
let ws = null;
let performanceChart = null;
let apiChart = null;
let metricsData = [];
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/monitor/ws`;
ws = new WebSocket(wsUrl);
ws.onopen = function() {
updateConnectionStatus(true);
loadInitialData();
};
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.type === 'metrics') {
updateMetrics(data.data);
updateCharts(data.data);
} else if (data.type === 'alert') {
addAlert(data.data);
}
};
ws.onclose = function() {
updateConnectionStatus(false);
setTimeout(connectWebSocket, 5000);
};
ws.onerror = function() {
updateConnectionStatus(false);
};
}
function updateConnectionStatus(connected) {
const indicator = document.getElementById('statusIndicator');
const text = document.getElementById('statusText');
if (connected) {
indicator.className = 'status-indicator status-healthy';
text.textContent = 'Connected';
} else {
indicator.className = 'status-indicator status-critical';
text.textContent = 'Disconnected';
}
}
async function loadInitialData() {
try {
// Load current metrics
const metricsResponse = await fetch('/monitor/metrics');
const metrics = await metricsResponse.json();
updateMetrics(metrics.current);
// Load alerts
const alertsResponse = await fetch('/monitor/alerts');
const alerts = await alertsResponse.json();
displayAlerts(alerts);
} catch (error) {
console.error('Error loading initial data:', error);
}
}
function updateMetrics(metrics) {
const grid = document.getElementById('metricsGrid');
grid.innerHTML = `
<div class="metric-card">
<div class="metric-value cpu">${metrics.cpu_usage?.toFixed(1) || 0}%</div>
<div class="metric-label">CPU Usage</div>
</div>
<div class="metric-card">
<div class="metric-value memory">${metrics.memory_usage?.toFixed(1) || 0}%</div>
<div class="metric-label">Memory Usage</div>
</div>
<div class="metric-card">
<div class="metric-value disk">${metrics.disk_usage?.toFixed(1) || 0}%</div>
<div class="metric-label">Disk Usage</div>
</div>
<div class="metric-card">
<div class="metric-value network">${metrics.active_connections || 0}</div>
<div class="metric-label">Active Connections</div>
</div>
`;
metricsData.push(metrics);
if (metricsData.length > 20) {
metricsData = metricsData.slice(-20);
}
}
function updateCharts(metrics) {
if (!performanceChart) {
initPerformanceChart();
}
if (!apiChart) {
initApiChart();
}
// Update performance chart
const labels = metricsData.map((_, i) => i);
performanceChart.data.labels = labels;
performanceChart.data.datasets[0].data = metricsData.map(m => m.cpu_usage);
performanceChart.data.datasets[1].data = metricsData.map(m => m.memory_usage);
performanceChart.update();
// Update API chart
if (metrics.api_response_times) {
const endpoints = Object.keys(metrics.api_response_times);
const times = Object.values(metrics.api_response_times);
apiChart.data.labels = endpoints;
apiChart.data.datasets[0].data = times;
apiChart.update();
}
}
function initPerformanceChart() {
const ctx = document.getElementById('performanceChart').getContext('2d');
performanceChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'CPU Usage (%)',
data: [],
borderColor: '#667eea',
backgroundColor: 'rgba(102, 126, 234, 0.1)',
tension: 0.4
}, {
label: 'Memory Usage (%)',
data: [],
borderColor: '#28a745',
backgroundColor: 'rgba(40, 167, 69, 0.1)',
tension: 0.4
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true,
max: 100
}
}
}
});
}
function initApiChart() {
const ctx = document.getElementById('apiChart').getContext('2d');
apiChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: 'Response Time (ms)',
data: [],
backgroundColor: '#667eea'
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
function displayAlerts(alerts) {
const container = document.getElementById('alertsContainer');
if (alerts.length === 0) {
container.innerHTML = '<div class="loading">No active alerts</div>';
return;
}
container.innerHTML = alerts.map(alert => `
<div class="alert ${alert.severity}">
<div class="alert-header">
<span class="alert-type">${alert.type.replace('_', ' ').toUpperCase()}</span>
<span class="alert-severity severity-${alert.severity}">${alert.severity}</span>
</div>
<div class="alert-message">${alert.message}</div>
<div class="alert-timestamp">${new Date(alert.timestamp).toLocaleString()}</div>
<button class="resolve-btn" onclick="resolveAlert('${alert.id}')">Resolve</button>
</div>
`).join('');
}
function addAlert(alert) {
const container = document.getElementById('alertsContainer');
const alertHtml = `
<div class="alert ${alert.severity}">
<div class="alert-header">
<span class="alert-type">${alert.type.replace('_', ' ').toUpperCase()}</span>
<span class="alert-severity severity-${alert.severity}">${alert.severity}</span>
</div>
<div class="alert-message">${alert.message}</div>
<div class="alert-timestamp">${new Date(alert.timestamp).toLocaleString()}</div>
<button class="resolve-btn" onclick="resolveAlert('${alert.id}')">Resolve</button>
</div>
`;
container.insertAdjacentHTML('afterbegin', alertHtml);
}
async function resolveAlert(alertId) {
try {
const response = await fetch(`/monitor/alerts/${alertId}/resolve`, {
method: 'POST'
});
if (response.ok) {
// Remove alert from UI
const alertElement = document.querySelector(`[onclick="resolveAlert('${alertId}')"]`).closest('.alert');
alertElement.remove();
}
} catch (error) {
console.error('Error resolving alert:', error);
}
}
// Initialize dashboard
connectWebSocket();
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(monitor_app, host="127.0.0.1", port=8005)
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/src/integration_hub.py | src/integration_hub.py | #!/usr/bin/env python3
"""
Integration Hub for N8N Workflows
Connect with external platforms and services.
"""
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
from typing import List, Dict, Any
import httpx
from datetime import datetime
class IntegrationConfig(BaseModel):
name: str
api_key: str
base_url: str
enabled: bool = True
class WebhookPayload(BaseModel):
event: str
data: Dict[str, Any]
timestamp: str = Field(default_factory=lambda: datetime.now().isoformat())
class IntegrationHub:
def __init__(self):
self.integrations = {}
self.webhook_endpoints = {}
def register_integration(self, config: IntegrationConfig):
"""Register a new integration."""
self.integrations[config.name] = config
async def sync_with_github(self, repo: str, token: str) -> Dict[str, Any]:
"""Sync workflows with GitHub repository."""
try:
async with httpx.AsyncClient() as client:
headers = {"Authorization": f"token {token}"}
# Get repository contents
response = await client.get(
f"https://api.github.com/repos/{repo}/contents/workflows",
headers=headers,
)
if response.status_code == 200:
files = response.json()
workflow_files = [f for f in files if f["name"].endswith(".json")]
return {
"status": "success",
"repository": repo,
"workflow_files": len(workflow_files),
"files": [f["name"] for f in workflow_files],
}
else:
return {"status": "error", "message": "Failed to access repository"}
except Exception as e:
return {"status": "error", "message": str(e)}
async def sync_with_slack(self, webhook_url: str, message: str) -> Dict[str, Any]:
"""Send notification to Slack."""
try:
async with httpx.AsyncClient() as client:
payload = {
"text": message,
"username": "N8N Workflows Bot",
"icon_emoji": ":robot_face:",
}
response = await client.post(webhook_url, json=payload)
if response.status_code == 200:
return {
"status": "success",
"message": "Notification sent to Slack",
}
else:
return {"status": "error", "message": "Failed to send to Slack"}
except Exception as e:
return {"status": "error", "message": str(e)}
async def sync_with_discord(self, webhook_url: str, message: str) -> Dict[str, Any]:
"""Send notification to Discord."""
try:
async with httpx.AsyncClient() as client:
payload = {"content": message, "username": "N8N Workflows Bot"}
response = await client.post(webhook_url, json=payload)
if response.status_code == 204:
return {
"status": "success",
"message": "Notification sent to Discord",
}
else:
return {"status": "error", "message": "Failed to send to Discord"}
except Exception as e:
return {"status": "error", "message": str(e)}
async def export_to_airtable(
self, base_id: str, table_name: str, api_key: str, workflows: List[Dict]
) -> Dict[str, Any]:
"""Export workflows to Airtable."""
try:
async with httpx.AsyncClient() as client:
headers = {"Authorization": f"Bearer {api_key}"}
records = []
for workflow in workflows:
record = {
"fields": {
"Name": workflow.get("name", ""),
"Description": workflow.get("description", ""),
"Trigger Type": workflow.get("trigger_type", ""),
"Complexity": workflow.get("complexity", ""),
"Node Count": workflow.get("node_count", 0),
"Active": workflow.get("active", False),
"Integrations": ", ".join(workflow.get("integrations", [])),
"Last Updated": datetime.now().isoformat(),
}
}
records.append(record)
# Create records in batches
batch_size = 10
created_records = 0
for i in range(0, len(records), batch_size):
batch = records[i : i + batch_size]
response = await client.post(
f"https://api.airtable.com/v0/{base_id}/{table_name}",
headers=headers,
json={"records": batch},
)
if response.status_code == 200:
created_records += len(batch)
else:
return {
"status": "error",
"message": f"Failed to create records: {response.text}",
}
return {
"status": "success",
"message": f"Exported {created_records} workflows to Airtable",
}
except Exception as e:
return {"status": "error", "message": str(e)}
async def sync_with_notion(
self, database_id: str, token: str, workflows: List[Dict]
) -> Dict[str, Any]:
"""Sync workflows with Notion database."""
try:
async with httpx.AsyncClient() as client:
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"Notion-Version": "2022-06-28",
}
created_pages = 0
for workflow in workflows:
page_data = {
"parent": {"database_id": database_id},
"properties": {
"Name": {
"title": [
{"text": {"content": workflow.get("name", "")}}
]
},
"Description": {
"rich_text": [
{
"text": {
"content": workflow.get("description", "")
}
}
]
},
"Trigger Type": {
"select": {"name": workflow.get("trigger_type", "")}
},
"Complexity": {
"select": {"name": workflow.get("complexity", "")}
},
"Node Count": {"number": workflow.get("node_count", 0)},
"Active": {"checkbox": workflow.get("active", False)},
"Integrations": {
"multi_select": [
{"name": integration}
for integration in workflow.get("integrations", [])
]
},
},
}
response = await client.post(
"https://api.notion.com/v1/pages",
headers=headers,
json=page_data,
)
if response.status_code == 200:
created_pages += 1
else:
return {
"status": "error",
"message": f"Failed to create page: {response.text}",
}
return {
"status": "success",
"message": f"Synced {created_pages} workflows to Notion",
}
except Exception as e:
return {"status": "error", "message": str(e)}
def register_webhook(self, endpoint: str, handler):
"""Register a webhook endpoint."""
self.webhook_endpoints[endpoint] = handler
async def handle_webhook(self, endpoint: str, payload: WebhookPayload):
"""Handle incoming webhook."""
if endpoint in self.webhook_endpoints:
return await self.webhook_endpoints[endpoint](payload)
else:
return {"status": "error", "message": "Webhook endpoint not found"}
# Initialize integration hub
integration_hub = IntegrationHub()
# FastAPI app for Integration Hub
integration_app = FastAPI(title="N8N Integration Hub", version="1.0.0")
@integration_app.post("/integrations/github/sync")
async def sync_github(repo: str, token: str):
"""Sync workflows with GitHub repository."""
try:
result = await integration_hub.sync_with_github(repo, token)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.post("/integrations/slack/notify")
async def notify_slack(webhook_url: str, message: str):
"""Send notification to Slack."""
try:
result = await integration_hub.sync_with_slack(webhook_url, message)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.post("/integrations/discord/notify")
async def notify_discord(webhook_url: str, message: str):
"""Send notification to Discord."""
try:
result = await integration_hub.sync_with_discord(webhook_url, message)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.post("/integrations/airtable/export")
async def export_airtable(
base_id: str, table_name: str, api_key: str, workflows: List[Dict]
):
"""Export workflows to Airtable."""
try:
result = await integration_hub.export_to_airtable(
base_id, table_name, api_key, workflows
)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.post("/integrations/notion/sync")
async def sync_notion(database_id: str, token: str, workflows: List[Dict]):
"""Sync workflows with Notion database."""
try:
result = await integration_hub.sync_with_notion(database_id, token, workflows)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.post("/webhooks/{endpoint}")
async def handle_webhook_endpoint(endpoint: str, payload: WebhookPayload):
"""Handle incoming webhook."""
try:
result = await integration_hub.handle_webhook(endpoint, payload)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@integration_app.get("/integrations/status")
async def get_integration_status():
"""Get status of all integrations."""
return {
"integrations": list(integration_hub.integrations.keys()),
"webhook_endpoints": list(integration_hub.webhook_endpoints.keys()),
"status": "operational",
}
@integration_app.get("/integrations/dashboard")
async def get_integration_dashboard():
"""Get integration dashboard HTML."""
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N8N Integration Hub</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
color: #333;
}
.dashboard {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.header {
background: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}
.header h1 {
font-size: 32px;
margin-bottom: 10px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.integrations-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.integration-card {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
transition: transform 0.3s ease;
}
.integration-card:hover {
transform: translateY(-5px);
}
.integration-icon {
font-size: 48px;
margin-bottom: 15px;
}
.integration-title {
font-size: 20px;
font-weight: bold;
margin-bottom: 10px;
color: #333;
}
.integration-description {
color: #666;
margin-bottom: 20px;
line-height: 1.5;
}
.integration-actions {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.action-btn {
padding: 10px 20px;
border: none;
border-radius: 25px;
cursor: pointer;
font-size: 14px;
transition: all 0.3s ease;
text-decoration: none;
display: inline-block;
text-align: center;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5a6fd8;
}
.btn-secondary {
background: #f8f9fa;
color: #666;
border: 1px solid #e9ecef;
}
.btn-secondary:hover {
background: #e9ecef;
}
.status-indicator {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 8px;
}
.status-online {
background: #28a745;
}
.status-offline {
background: #dc3545;
}
.webhook-section {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
margin-bottom: 30px;
}
.webhook-endpoint {
background: #f8f9fa;
padding: 15px;
border-radius: 10px;
margin: 10px 0;
font-family: monospace;
border-left: 4px solid #667eea;
}
</style>
</head>
<body>
<div class="dashboard">
<div class="header">
<h1>🔗 N8N Integration Hub</h1>
<p>Connect your workflows with external platforms and services</p>
</div>
<div class="integrations-grid">
<div class="integration-card">
<div class="integration-icon">🐙</div>
<div class="integration-title">GitHub</div>
<div class="integration-description">
Sync your workflows with GitHub repositories.
Version control and collaborate on workflow development.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="syncGitHub()">Sync Repository</button>
<button class="action-btn btn-secondary" onclick="showGitHubConfig()">Configure</button>
</div>
</div>
<div class="integration-card">
<div class="integration-icon">💬</div>
<div class="integration-title">Slack</div>
<div class="integration-description">
Send notifications and workflow updates to Slack channels.
Keep your team informed about automation activities.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="testSlack()">Test Notification</button>
<button class="action-btn btn-secondary" onclick="showSlackConfig()">Configure</button>
</div>
</div>
<div class="integration-card">
<div class="integration-icon">🎮</div>
<div class="integration-title">Discord</div>
<div class="integration-description">
Integrate with Discord servers for workflow notifications.
Perfect for gaming communities and developer teams.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="testDiscord()">Test Notification</button>
<button class="action-btn btn-secondary" onclick="showDiscordConfig()">Configure</button>
</div>
</div>
<div class="integration-card">
<div class="integration-icon">📊</div>
<div class="integration-title">Airtable</div>
<div class="integration-description">
Export workflow data to Airtable for project management.
Create databases of your automation workflows.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="exportAirtable()">Export Data</button>
<button class="action-btn btn-secondary" onclick="showAirtableConfig()">Configure</button>
</div>
</div>
<div class="integration-card">
<div class="integration-icon">📝</div>
<div class="integration-title">Notion</div>
<div class="integration-description">
Sync workflows with Notion databases for documentation.
Create comprehensive workflow documentation.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="syncNotion()">Sync Database</button>
<button class="action-btn btn-secondary" onclick="showNotionConfig()">Configure</button>
</div>
</div>
<div class="integration-card">
<div class="integration-icon">🔗</div>
<div class="integration-title">Webhooks</div>
<div class="integration-description">
Create custom webhook endpoints for external integrations.
Receive data from any service that supports webhooks.
</div>
<div class="integration-actions">
<button class="action-btn btn-primary" onclick="createWebhook()">Create Webhook</button>
<button class="action-btn btn-secondary" onclick="showWebhookDocs()">Documentation</button>
</div>
</div>
</div>
<div class="webhook-section">
<h2>🔗 Webhook Endpoints</h2>
<p>Available webhook endpoints for external integrations:</p>
<div class="webhook-endpoint">
POST /webhooks/workflow-update<br>
<small>Receive notifications when workflows are updated</small>
</div>
<div class="webhook-endpoint">
POST /webhooks/workflow-execution<br>
<small>Receive notifications when workflows are executed</small>
</div>
<div class="webhook-endpoint">
POST /webhooks/error-report<br>
<small>Receive error reports from workflow executions</small>
</div>
</div>
</div>
<script>
async function syncGitHub() {
const repo = prompt('Enter GitHub repository (owner/repo):');
const token = prompt('Enter GitHub token:');
if (repo && token) {
try {
const response = await fetch('/integrations/github/sync', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({repo, token})
});
const result = await response.json();
alert(result.message || 'GitHub sync completed');
} catch (error) {
alert('Error syncing with GitHub: ' + error.message);
}
}
}
async function testSlack() {
const webhook = prompt('Enter Slack webhook URL:');
const message = 'Test notification from N8N Integration Hub';
if (webhook) {
try {
const response = await fetch('/integrations/slack/notify', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({webhook_url: webhook, message})
});
const result = await response.json();
alert(result.message || 'Slack notification sent');
} catch (error) {
alert('Error sending to Slack: ' + error.message);
}
}
}
async function testDiscord() {
const webhook = prompt('Enter Discord webhook URL:');
const message = 'Test notification from N8N Integration Hub';
if (webhook) {
try {
const response = await fetch('/integrations/discord/notify', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({webhook_url: webhook, message})
});
const result = await response.json();
alert(result.message || 'Discord notification sent');
} catch (error) {
alert('Error sending to Discord: ' + error.message);
}
}
}
function showGitHubConfig() {
alert('GitHub Configuration:\\n\\n1. Create a GitHub token with repo access\\n2. Use format: owner/repository\\n3. Ensure workflows are in /workflows directory');
}
function showSlackConfig() {
alert('Slack Configuration:\\n\\n1. Go to Slack App Directory\\n2. Add "Incoming Webhooks" app\\n3. Create webhook URL\\n4. Use the URL for notifications');
}
function showDiscordConfig() {
alert('Discord Configuration:\\n\\n1. Go to Server Settings\\n2. Navigate to Integrations\\n3. Create Webhook\\n4. Copy webhook URL');
}
function showAirtableConfig() {
alert('Airtable Configuration:\\n\\n1. Create a new Airtable base\\n2. Get API key from account settings\\n3. Get base ID from API documentation\\n4. Configure table structure');
}
function showNotionConfig() {
alert('Notion Configuration:\\n\\n1. Create a Notion integration\\n2. Get integration token\\n3. Create database with proper schema\\n4. Share database with integration');
}
function createWebhook() {
alert('Webhook Creation:\\n\\n1. Choose endpoint name\\n2. Configure payload structure\\n3. Set up authentication\\n4. Test webhook endpoint');
}
function showWebhookDocs() {
alert('Webhook Documentation:\\n\\nAvailable at: /docs\\n\\nEndpoints:\\n- POST /webhooks/{endpoint}\\n- Payload: {event, data, timestamp}\\n- Response: {status, message}');
}
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(integration_app, host="127.0.0.1", port=8003)
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/src/analytics_engine.py | src/analytics_engine.py | #!/usr/bin/env python3
"""
Advanced Analytics Engine for N8N Workflows
Provides insights, patterns, and usage analytics.
"""
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import List, Dict, Any
import sqlite3
import json
from datetime import datetime
from collections import Counter, defaultdict
class AnalyticsResponse(BaseModel):
overview: Dict[str, Any]
trends: Dict[str, Any]
patterns: Dict[str, Any]
recommendations: List[str]
generated_at: str
class WorkflowAnalytics:
def __init__(self, db_path: str = "workflows.db"):
self.db_path = db_path
def get_db_connection(self):
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
return conn
def get_workflow_analytics(self) -> Dict[str, Any]:
"""Get comprehensive workflow analytics."""
conn = self.get_db_connection()
# Basic statistics
cursor = conn.execute("SELECT COUNT(*) as total FROM workflows")
total_workflows = cursor.fetchone()["total"]
cursor = conn.execute(
"SELECT COUNT(*) as active FROM workflows WHERE active = 1"
)
active_workflows = cursor.fetchone()["active"]
# Trigger type distribution
cursor = conn.execute("""
SELECT trigger_type, COUNT(*) as count
FROM workflows
GROUP BY trigger_type
ORDER BY count DESC
""")
trigger_distribution = {
row["trigger_type"]: row["count"] for row in cursor.fetchall()
}
# Complexity distribution
cursor = conn.execute("""
SELECT complexity, COUNT(*) as count
FROM workflows
GROUP BY complexity
ORDER BY count DESC
""")
complexity_distribution = {
row["complexity"]: row["count"] for row in cursor.fetchall()
}
# Node count statistics
cursor = conn.execute("""
SELECT
AVG(node_count) as avg_nodes,
MIN(node_count) as min_nodes,
MAX(node_count) as max_nodes,
COUNT(*) as total
FROM workflows
""")
node_stats = dict(cursor.fetchone())
# Integration analysis
cursor = conn.execute(
"SELECT integrations FROM workflows WHERE integrations IS NOT NULL"
)
all_integrations = []
for row in cursor.fetchall():
integrations = json.loads(row["integrations"] or "[]")
all_integrations.extend(integrations)
integration_counts = Counter(all_integrations)
top_integrations = dict(integration_counts.most_common(10))
# Workflow patterns
patterns = self.analyze_workflow_patterns(conn)
# Recommendations
recommendations = self.generate_recommendations(
total_workflows,
active_workflows,
trigger_distribution,
complexity_distribution,
top_integrations,
)
conn.close()
return {
"overview": {
"total_workflows": total_workflows,
"active_workflows": active_workflows,
"activation_rate": round((active_workflows / total_workflows) * 100, 2)
if total_workflows > 0
else 0,
"unique_integrations": len(integration_counts),
"avg_nodes_per_workflow": round(node_stats["avg_nodes"], 2),
"most_complex_workflow": node_stats["max_nodes"],
},
"distributions": {
"trigger_types": trigger_distribution,
"complexity_levels": complexity_distribution,
"top_integrations": top_integrations,
},
"patterns": patterns,
"recommendations": recommendations,
"generated_at": datetime.now().isoformat(),
}
def analyze_workflow_patterns(self, conn) -> Dict[str, Any]:
"""Analyze common workflow patterns and relationships."""
# Integration co-occurrence analysis
cursor = conn.execute("""
SELECT name, integrations, trigger_type, complexity, node_count
FROM workflows
WHERE integrations IS NOT NULL
""")
integration_pairs = defaultdict(int)
service_categories = defaultdict(int)
for row in cursor.fetchall():
integrations = json.loads(row["integrations"] or "[]")
# Count service categories
for integration in integrations:
category = self.categorize_service(integration)
service_categories[category] += 1
# Find integration pairs
for i in range(len(integrations)):
for j in range(i + 1, len(integrations)):
pair = tuple(sorted([integrations[i], integrations[j]]))
integration_pairs[pair] += 1
# Most common integration pairs
top_pairs = dict(Counter(integration_pairs).most_common(5))
# Workflow complexity patterns
cursor = conn.execute("""
SELECT
trigger_type,
complexity,
AVG(node_count) as avg_nodes,
COUNT(*) as count
FROM workflows
GROUP BY trigger_type, complexity
ORDER BY count DESC
""")
complexity_patterns = []
for row in cursor.fetchall():
complexity_patterns.append(
{
"trigger_type": row["trigger_type"],
"complexity": row["complexity"],
"avg_nodes": round(row["avg_nodes"], 2),
"frequency": row["count"],
}
)
return {
"integration_pairs": top_pairs,
"service_categories": dict(service_categories),
"complexity_patterns": complexity_patterns[:10],
}
def categorize_service(self, service: str) -> str:
"""Categorize a service into a broader category."""
service_lower = service.lower()
if any(
word in service_lower
for word in ["slack", "telegram", "discord", "whatsapp"]
):
return "Communication"
elif any(word in service_lower for word in ["openai", "ai", "chat", "gpt"]):
return "AI/ML"
elif any(word in service_lower for word in ["google", "microsoft", "office"]):
return "Productivity"
elif any(
word in service_lower for word in ["shopify", "woocommerce", "stripe"]
):
return "E-commerce"
elif any(word in service_lower for word in ["airtable", "notion", "database"]):
return "Data Management"
elif any(
word in service_lower for word in ["twitter", "facebook", "instagram"]
):
return "Social Media"
else:
return "Other"
def generate_recommendations(
self,
total: int,
active: int,
triggers: Dict,
complexity: Dict,
integrations: Dict,
) -> List[str]:
"""Generate actionable recommendations based on analytics."""
recommendations = []
# Activation rate recommendations
activation_rate = (active / total) * 100 if total > 0 else 0
if activation_rate < 20:
recommendations.append(
f"Low activation rate ({activation_rate:.1f}%). Consider reviewing inactive workflows "
"and updating them for current use cases."
)
elif activation_rate > 80:
recommendations.append(
f"High activation rate ({activation_rate:.1f}%)! Your workflows are well-maintained. "
"Consider documenting successful patterns for team sharing."
)
# Trigger type recommendations
webhook_count = triggers.get("Webhook", 0)
scheduled_count = triggers.get("Scheduled", 0)
if webhook_count > scheduled_count * 2:
recommendations.append(
"You have many webhook-triggered workflows. Consider adding scheduled workflows "
"for data synchronization and maintenance tasks."
)
elif scheduled_count > webhook_count * 2:
recommendations.append(
"You have many scheduled workflows. Consider adding webhook-triggered workflows "
"for real-time integrations and event-driven automation."
)
# Integration recommendations
if "OpenAI" in integrations and integrations["OpenAI"] > 5:
recommendations.append(
"You're using OpenAI extensively. Consider creating AI workflow templates "
"for common use cases like content generation and data analysis."
)
if "Slack" in integrations and "Telegram" in integrations:
recommendations.append(
"You're using multiple communication platforms. Consider creating unified "
"notification workflows that can send to multiple channels."
)
# Complexity recommendations
high_complexity = complexity.get("high", 0)
if high_complexity > total * 0.3:
recommendations.append(
"You have many high-complexity workflows. Consider breaking them down into "
"smaller, reusable components for better maintainability."
)
return recommendations
def get_trend_analysis(self, days: int = 30) -> Dict[str, Any]:
"""Analyze trends over time (simulated for demo)."""
# In a real implementation, this would analyze historical data
return {
"workflow_growth": {
"daily_average": 2.3,
"growth_rate": 15.2,
"trend": "increasing",
},
"popular_integrations": {
"trending_up": ["OpenAI", "Slack", "Google Sheets"],
"trending_down": ["Twitter", "Facebook"],
"stable": ["Telegram", "Airtable"],
},
"complexity_trends": {
"average_nodes": 12.5,
"complexity_increase": 8.3,
"automation_maturity": "intermediate",
},
}
def get_usage_insights(self) -> Dict[str, Any]:
"""Get usage insights and patterns."""
conn = self.get_db_connection()
# Active vs inactive analysis
cursor = conn.execute("""
SELECT
trigger_type,
complexity,
COUNT(*) as total,
SUM(active) as active_count
FROM workflows
GROUP BY trigger_type, complexity
""")
usage_patterns = []
for row in cursor.fetchall():
activation_rate = (
(row["active_count"] / row["total"]) * 100 if row["total"] > 0 else 0
)
usage_patterns.append(
{
"trigger_type": row["trigger_type"],
"complexity": row["complexity"],
"total_workflows": row["total"],
"active_workflows": row["active_count"],
"activation_rate": round(activation_rate, 2),
}
)
# Most effective patterns
effective_patterns = sorted(
usage_patterns, key=lambda x: x["activation_rate"], reverse=True
)[:5]
conn.close()
return {
"usage_patterns": usage_patterns,
"most_effective_patterns": effective_patterns,
"insights": [
"Webhook-triggered workflows have higher activation rates",
"Medium complexity workflows are most commonly used",
"AI-powered workflows show increasing adoption",
"Communication integrations are most popular",
],
}
# Initialize analytics engine
analytics_engine = WorkflowAnalytics()
# FastAPI app for Analytics
analytics_app = FastAPI(title="N8N Analytics Engine", version="1.0.0")
@analytics_app.get("/analytics/overview", response_model=AnalyticsResponse)
async def get_analytics_overview():
"""Get comprehensive analytics overview."""
try:
analytics_data = analytics_engine.get_workflow_analytics()
trends = analytics_engine.get_trend_analysis()
insights = analytics_engine.get_usage_insights()
return AnalyticsResponse(
overview=analytics_data["overview"],
trends=trends,
patterns=analytics_data["patterns"],
recommendations=analytics_data["recommendations"],
generated_at=analytics_data["generated_at"],
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Analytics error: {str(e)}")
@analytics_app.get("/analytics/trends")
async def get_trend_analysis(days: int = Query(30, ge=1, le=365)):
"""Get trend analysis for specified period."""
try:
return analytics_engine.get_trend_analysis(days)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Trend analysis error: {str(e)}")
@analytics_app.get("/analytics/insights")
async def get_usage_insights():
"""Get usage insights and patterns."""
try:
return analytics_engine.get_usage_insights()
except Exception as e:
raise HTTPException(status_code=500, detail=f"Insights error: {str(e)}")
@analytics_app.get("/analytics/dashboard")
async def get_analytics_dashboard():
"""Get analytics dashboard HTML."""
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N8N Analytics Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f8f9fa;
color: #333;
}
.dashboard {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
text-align: center;
}
.header h1 {
font-size: 32px;
margin-bottom: 10px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.stat-card {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
text-align: center;
}
.stat-number {
font-size: 36px;
font-weight: bold;
color: #667eea;
margin-bottom: 10px;
}
.stat-label {
color: #666;
font-size: 16px;
}
.chart-container {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin-bottom: 30px;
}
.chart-title {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
color: #333;
}
.recommendations {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.recommendation {
background: #e3f2fd;
padding: 15px;
border-radius: 10px;
margin-bottom: 10px;
border-left: 4px solid #2196f3;
}
.loading {
text-align: center;
padding: 40px;
color: #666;
}
</style>
</head>
<body>
<div class="dashboard">
<div class="header">
<h1>📊 N8N Analytics Dashboard</h1>
<p>Comprehensive insights into your workflow ecosystem</p>
</div>
<div class="stats-grid" id="statsGrid">
<div class="loading">Loading analytics...</div>
</div>
<div class="chart-container">
<div class="chart-title">Workflow Distribution</div>
<canvas id="triggerChart" width="400" height="200"></canvas>
</div>
<div class="chart-container">
<div class="chart-title">Integration Usage</div>
<canvas id="integrationChart" width="400" height="200"></canvas>
</div>
<div class="recommendations" id="recommendations">
<div class="chart-title">Recommendations</div>
<div class="loading">Loading recommendations...</div>
</div>
</div>
<script>
async function loadAnalytics() {
try {
const response = await fetch('/analytics/overview');
const data = await response.json();
// Update stats
updateStats(data.overview);
// Create charts
createTriggerChart(data.patterns.distributions?.trigger_types || {});
createIntegrationChart(data.patterns.distributions?.top_integrations || {});
// Update recommendations
updateRecommendations(data.recommendations);
} catch (error) {
console.error('Error loading analytics:', error);
document.getElementById('statsGrid').innerHTML =
'<div class="loading">Error loading analytics. Please try again.</div>';
}
}
function updateStats(overview) {
const statsGrid = document.getElementById('statsGrid');
statsGrid.innerHTML = `
<div class="stat-card">
<div class="stat-number">${overview.total_workflows?.toLocaleString() || 0}</div>
<div class="stat-label">Total Workflows</div>
</div>
<div class="stat-card">
<div class="stat-number">${overview.active_workflows?.toLocaleString() || 0}</div>
<div class="stat-label">Active Workflows</div>
</div>
<div class="stat-card">
<div class="stat-number">${overview.activation_rate || 0}%</div>
<div class="stat-label">Activation Rate</div>
</div>
<div class="stat-card">
<div class="stat-number">${overview.unique_integrations || 0}</div>
<div class="stat-label">Unique Integrations</div>
</div>
`;
}
function createTriggerChart(triggerData) {
const ctx = document.getElementById('triggerChart').getContext('2d');
new Chart(ctx, {
type: 'doughnut',
data: {
labels: Object.keys(triggerData),
datasets: [{
data: Object.values(triggerData),
backgroundColor: [
'#667eea',
'#764ba2',
'#f093fb',
'#f5576c',
'#4facfe'
]
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom'
}
}
}
});
}
function createIntegrationChart(integrationData) {
const ctx = document.getElementById('integrationChart').getContext('2d');
const labels = Object.keys(integrationData).slice(0, 10);
const data = Object.values(integrationData).slice(0, 10);
new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Usage Count',
data: data,
backgroundColor: '#667eea'
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
function updateRecommendations(recommendations) {
const container = document.getElementById('recommendations');
if (recommendations && recommendations.length > 0) {
container.innerHTML = `
<div class="chart-title">Recommendations</div>
${recommendations.map(rec => `
<div class="recommendation">${rec}</div>
`).join('')}
`;
} else {
container.innerHTML = '<div class="chart-title">Recommendations</div><div class="loading">No recommendations available</div>';
}
}
// Load analytics on page load
loadAnalytics();
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
if __name__ == "__main__":
import uvicorn
uvicorn.run(analytics_app, host="127.0.0.1", port=8002)
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/src/community_features.py | src/community_features.py | #!/usr/bin/env python3
"""
Community Features Module for n8n Workflows Repository
Implements rating, review, and social features
"""
import sqlite3
import json
from datetime import datetime
from typing import Dict, List, Optional
from dataclasses import dataclass
@dataclass
class WorkflowRating:
"""Workflow rating data structure"""
workflow_id: str
user_id: str
rating: int # 1-5 stars
review: Optional[str] = None
helpful_votes: int = 0
created_at: datetime = None
updated_at: datetime = None
@dataclass
class WorkflowStats:
"""Workflow statistics"""
workflow_id: str
total_ratings: int
average_rating: float
total_reviews: int
total_views: int
total_downloads: int
last_updated: datetime
class CommunityFeatures:
"""Community features manager for workflow repository"""
def __init__(self, db_path: str = "workflows.db"):
"""Initialize community features with database connection"""
self.db_path = db_path
self.init_community_tables()
def init_community_tables(self):
"""Initialize community feature database tables"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Workflow ratings and reviews
cursor.execute("""
CREATE TABLE IF NOT EXISTS workflow_ratings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
workflow_id TEXT NOT NULL,
user_id TEXT NOT NULL,
rating INTEGER CHECK(rating >= 1 AND rating <= 5),
review TEXT,
helpful_votes INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(workflow_id, user_id)
)
""")
# Workflow usage statistics
cursor.execute("""
CREATE TABLE IF NOT EXISTS workflow_stats (
workflow_id TEXT PRIMARY KEY,
total_ratings INTEGER DEFAULT 0,
average_rating REAL DEFAULT 0.0,
total_reviews INTEGER DEFAULT 0,
total_views INTEGER DEFAULT 0,
total_downloads INTEGER DEFAULT 0,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# User profiles
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_profiles (
user_id TEXT PRIMARY KEY,
username TEXT,
display_name TEXT,
email TEXT,
avatar_url TEXT,
bio TEXT,
github_url TEXT,
website_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Workflow collections (user favorites)
cursor.execute("""
CREATE TABLE IF NOT EXISTS workflow_collections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
collection_name TEXT NOT NULL,
workflow_ids TEXT, -- JSON array of workflow IDs
is_public BOOLEAN DEFAULT FALSE,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Workflow comments
cursor.execute("""
CREATE TABLE IF NOT EXISTS workflow_comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
workflow_id TEXT NOT NULL,
user_id TEXT NOT NULL,
parent_id INTEGER, -- For threaded comments
comment TEXT NOT NULL,
helpful_votes INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
def add_rating(
self, workflow_id: str, user_id: str, rating: int, review: str = None
) -> bool:
"""Add or update a workflow rating and review"""
if not (1 <= rating <= 5):
raise ValueError("Rating must be between 1 and 5")
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
try:
# Insert or update rating
cursor.execute(
"""
INSERT OR REPLACE INTO workflow_ratings
(workflow_id, user_id, rating, review, updated_at)
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
""",
(workflow_id, user_id, rating, review),
)
# Update workflow statistics
self._update_workflow_stats(workflow_id)
conn.commit()
return True
except Exception as e:
print(f"Error adding rating: {e}")
return False
finally:
conn.close()
def get_workflow_ratings(
self, workflow_id: str, limit: int = 10
) -> List[WorkflowRating]:
"""Get ratings and reviews for a workflow"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT workflow_id, user_id, rating, review, helpful_votes, created_at, updated_at
FROM workflow_ratings
WHERE workflow_id = ?
ORDER BY helpful_votes DESC, created_at DESC
LIMIT ?
""",
(workflow_id, limit),
)
ratings = []
for row in cursor.fetchall():
ratings.append(
WorkflowRating(
workflow_id=row[0],
user_id=row[1],
rating=row[2],
review=row[3],
helpful_votes=row[4],
created_at=datetime.fromisoformat(row[5]) if row[5] else None,
updated_at=datetime.fromisoformat(row[6]) if row[6] else None,
)
)
conn.close()
return ratings
def get_workflow_stats(self, workflow_id: str) -> Optional[WorkflowStats]:
"""Get comprehensive statistics for a workflow"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT workflow_id, total_ratings, average_rating, total_reviews,
total_views, total_downloads, last_updated
FROM workflow_stats
WHERE workflow_id = ?
""",
(workflow_id,),
)
row = cursor.fetchone()
conn.close()
if row:
return WorkflowStats(
workflow_id=row[0],
total_ratings=row[1],
average_rating=row[2],
total_reviews=row[3],
total_views=row[4],
total_downloads=row[5],
last_updated=datetime.fromisoformat(row[6]) if row[6] else None,
)
return None
def increment_view(self, workflow_id: str):
"""Increment view count for a workflow"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
INSERT OR IGNORE INTO workflow_stats (workflow_id, total_views)
VALUES (?, 1)
""",
(workflow_id,),
)
cursor.execute(
"""
UPDATE workflow_stats
SET total_views = total_views + 1, last_updated = CURRENT_TIMESTAMP
WHERE workflow_id = ?
""",
(workflow_id,),
)
conn.commit()
conn.close()
def increment_download(self, workflow_id: str):
"""Increment download count for a workflow"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
INSERT OR IGNORE INTO workflow_stats (workflow_id, total_downloads)
VALUES (?, 1)
""",
(workflow_id,),
)
cursor.execute(
"""
UPDATE workflow_stats
SET total_downloads = total_downloads + 1, last_updated = CURRENT_TIMESTAMP
WHERE workflow_id = ?
""",
(workflow_id,),
)
conn.commit()
conn.close()
def get_top_rated_workflows(self, limit: int = 10) -> List[Dict]:
"""Get top-rated workflows"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT w.filename, w.name, w.description, ws.average_rating, ws.total_ratings
FROM workflows w
JOIN workflow_stats ws ON w.filename = ws.workflow_id
WHERE ws.total_ratings >= 3
ORDER BY ws.average_rating DESC, ws.total_ratings DESC
LIMIT ?
""",
(limit,),
)
results = []
for row in cursor.fetchall():
results.append(
{
"filename": row[0],
"name": row[1],
"description": row[2],
"average_rating": row[3],
"total_ratings": row[4],
}
)
conn.close()
return results
def get_most_popular_workflows(self, limit: int = 10) -> List[Dict]:
"""Get most popular workflows by views and downloads"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT w.filename, w.name, w.description, ws.total_views, ws.total_downloads
FROM workflows w
LEFT JOIN workflow_stats ws ON w.filename = ws.workflow_id
ORDER BY (ws.total_views + ws.total_downloads) DESC
LIMIT ?
""",
(limit,),
)
results = []
for row in cursor.fetchall():
results.append(
{
"filename": row[0],
"name": row[1],
"description": row[2],
"total_views": row[3] or 0,
"total_downloads": row[4] or 0,
}
)
conn.close()
return results
def create_collection(
self,
user_id: str,
collection_name: str,
workflow_ids: List[str],
is_public: bool = False,
description: str = None,
) -> bool:
"""Create a workflow collection"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
try:
cursor.execute(
"""
INSERT INTO workflow_collections
(user_id, collection_name, workflow_ids, is_public, description)
VALUES (?, ?, ?, ?, ?)
""",
(
user_id,
collection_name,
json.dumps(workflow_ids),
is_public,
description,
),
)
conn.commit()
return True
except Exception as e:
print(f"Error creating collection: {e}")
return False
finally:
conn.close()
def get_user_collections(self, user_id: str) -> List[Dict]:
"""Get collections for a user"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT id, collection_name, workflow_ids, is_public, description, created_at
FROM workflow_collections
WHERE user_id = ?
ORDER BY created_at DESC
""",
(user_id,),
)
collections = []
for row in cursor.fetchall():
collections.append(
{
"id": row[0],
"name": row[1],
"workflow_ids": json.loads(row[2]) if row[2] else [],
"is_public": bool(row[3]),
"description": row[4],
"created_at": row[5],
}
)
conn.close()
return collections
def _update_workflow_stats(self, workflow_id: str):
"""Update workflow statistics after rating changes"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Calculate new statistics
cursor.execute(
"""
SELECT COUNT(*), AVG(rating), COUNT(CASE WHEN review IS NOT NULL THEN 1 END)
FROM workflow_ratings
WHERE workflow_id = ?
""",
(workflow_id,),
)
total_ratings, avg_rating, total_reviews = cursor.fetchone()
# Update or insert statistics
cursor.execute(
"""
INSERT OR REPLACE INTO workflow_stats
(workflow_id, total_ratings, average_rating, total_reviews, last_updated)
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
""",
(workflow_id, total_ratings or 0, avg_rating or 0.0, total_reviews or 0),
)
conn.commit()
conn.close()
# Example usage and API endpoints
def create_community_api_endpoints(app):
"""Add community feature endpoints to FastAPI app"""
community = CommunityFeatures()
@app.post("/api/workflows/{workflow_id}/rate")
async def rate_workflow(workflow_id: str, rating_data: dict):
"""Rate a workflow"""
try:
success = community.add_rating(
workflow_id=workflow_id,
user_id=rating_data.get("user_id", "anonymous"),
rating=rating_data["rating"],
review=rating_data.get("review"),
)
return {"success": success}
except Exception as e:
return {"error": str(e)}
@app.get("/api/workflows/{workflow_id}/ratings")
async def get_workflow_ratings(workflow_id: str, limit: int = 10):
"""Get workflow ratings and reviews"""
ratings = community.get_workflow_ratings(workflow_id, limit)
return {"ratings": ratings}
@app.get("/api/workflows/{workflow_id}/stats")
async def get_workflow_stats(workflow_id: str):
"""Get workflow statistics"""
stats = community.get_workflow_stats(workflow_id)
return {"stats": stats}
@app.get("/api/workflows/top-rated")
async def get_top_rated_workflows(limit: int = 10):
"""Get top-rated workflows"""
workflows = community.get_top_rated_workflows(limit)
return {"workflows": workflows}
@app.get("/api/workflows/most-popular")
async def get_most_popular_workflows(limit: int = 10):
"""Get most popular workflows"""
workflows = community.get_most_popular_workflows(limit)
return {"workflows": workflows}
@app.post("/api/workflows/{workflow_id}/view")
async def track_workflow_view(workflow_id: str):
"""Track workflow view"""
community.increment_view(workflow_id)
return {"success": True}
@app.post("/api/workflows/{workflow_id}/download")
async def track_workflow_download(workflow_id: str):
"""Track workflow download"""
community.increment_download(workflow_id)
return {"success": True}
if __name__ == "__main__":
# Initialize community features
community = CommunityFeatures()
print("✅ Community features initialized successfully!")
# Example: Add a rating
# community.add_rating("example-workflow.json", "user123", 5, "Great workflow!")
# Example: Get top-rated workflows
top_workflows = community.get_top_rated_workflows(5)
print(f"📊 Top rated workflows: {len(top_workflows)}")
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
Zie619/n8n-workflows | https://github.com/Zie619/n8n-workflows/blob/61bc7a4455c49d47b0e288848e72ccd5778a7470/src/enhanced_api.py | src/enhanced_api.py | #!/usr/bin/env python3
"""
Enhanced API Module for n8n Workflows Repository
Advanced features, analytics, and performance optimizations
"""
import sqlite3
import time
from datetime import datetime
from typing import Dict, List, Optional
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from pydantic import BaseModel
import uvicorn
# Import community features
from community_features import CommunityFeatures, create_community_api_endpoints
class WorkflowSearchRequest(BaseModel):
"""Workflow search request model"""
query: str
categories: Optional[List[str]] = None
trigger_types: Optional[List[str]] = None
complexity_levels: Optional[List[str]] = None
integrations: Optional[List[str]] = None
min_rating: Optional[float] = None
limit: int = 20
offset: int = 0
class WorkflowRecommendationRequest(BaseModel):
"""Workflow recommendation request model"""
user_interests: List[str]
viewed_workflows: Optional[List[str]] = None
preferred_complexity: Optional[str] = None
limit: int = 10
class AnalyticsRequest(BaseModel):
"""Analytics request model"""
date_range: str # "7d", "30d", "90d", "1y"
metrics: List[str] # ["views", "downloads", "ratings", "searches"]
class EnhancedAPI:
"""Enhanced API with advanced features"""
def __init__(self, db_path: str = "workflows.db"):
"""Initialize enhanced API"""
self.db_path = db_path
self.community = CommunityFeatures(db_path)
self.app = FastAPI(
title="N8N Workflows Enhanced API",
description="Advanced API for n8n workflows repository with community features",
version="2.0.0",
)
self._setup_middleware()
self._setup_routes()
def _setup_middleware(self):
"""Setup middleware for performance and security"""
# CORS middleware
self.app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Gzip compression
self.app.add_middleware(GZipMiddleware, minimum_size=1000)
def _setup_routes(self):
"""Setup API routes"""
# Core workflow endpoints
@self.app.get("/api/v2/workflows")
async def get_workflows_enhanced(
search: Optional[str] = Query(None),
category: Optional[str] = Query(None),
trigger_type: Optional[str] = Query(None),
complexity: Optional[str] = Query(None),
integration: Optional[str] = Query(None),
min_rating: Optional[float] = Query(None),
sort_by: str = Query("name"),
sort_order: str = Query("asc"),
limit: int = Query(20, le=100),
offset: int = Query(0, ge=0),
):
"""Enhanced workflow search with multiple filters"""
start_time = time.time()
try:
workflows = self._search_workflows_enhanced(
search=search,
category=category,
trigger_type=trigger_type,
complexity=complexity,
integration=integration,
min_rating=min_rating,
sort_by=sort_by,
sort_order=sort_order,
limit=limit,
offset=offset,
)
response_time = (time.time() - start_time) * 1000
return {
"workflows": workflows,
"total": len(workflows),
"limit": limit,
"offset": offset,
"response_time_ms": round(response_time, 2),
"timestamp": datetime.now().isoformat(),
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.post("/api/v2/workflows/search")
async def advanced_workflow_search(request: WorkflowSearchRequest):
"""Advanced workflow search with complex queries"""
start_time = time.time()
try:
results = self._advanced_search(request)
response_time = (time.time() - start_time) * 1000
return {
"results": results,
"total": len(results),
"query": request.dict(),
"response_time_ms": round(response_time, 2),
"timestamp": datetime.now().isoformat(),
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.get("/api/v2/workflows/{workflow_id}")
async def get_workflow_enhanced(
workflow_id: str,
include_stats: bool = Query(True),
include_ratings: bool = Query(True),
include_related: bool = Query(True),
):
"""Get detailed workflow information"""
try:
workflow_data = self._get_workflow_details(
workflow_id, include_stats, include_ratings, include_related
)
if not workflow_data:
raise HTTPException(status_code=404, detail="Workflow not found")
return workflow_data
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Recommendation endpoints
@self.app.post("/api/v2/recommendations")
async def get_workflow_recommendations(request: WorkflowRecommendationRequest):
"""Get personalized workflow recommendations"""
try:
recommendations = self._get_recommendations(request)
return {
"recommendations": recommendations,
"user_profile": request.dict(),
"timestamp": datetime.now().isoformat(),
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.get("/api/v2/recommendations/trending")
async def get_trending_workflows(limit: int = Query(10, le=50)):
"""Get trending workflows based on recent activity"""
try:
trending = self._get_trending_workflows(limit)
return {
"trending": trending,
"limit": limit,
"timestamp": datetime.now().isoformat(),
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Analytics endpoints
@self.app.get("/api/v2/analytics/overview")
async def get_analytics_overview():
"""Get analytics overview"""
try:
overview = self._get_analytics_overview()
return overview
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.post("/api/v2/analytics/custom")
async def get_custom_analytics(request: AnalyticsRequest):
"""Get custom analytics data"""
try:
analytics = self._get_custom_analytics(request)
return analytics
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Performance monitoring
@self.app.get("/api/v2/health")
async def health_check():
"""Health check with performance metrics"""
try:
health_data = self._get_health_status()
return health_data
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Add community endpoints
create_community_api_endpoints(self.app)
def _search_workflows_enhanced(self, **kwargs) -> List[Dict]:
"""Enhanced workflow search with multiple filters"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Build dynamic query
query_parts = ["SELECT w.*, ws.average_rating, ws.total_ratings"]
query_parts.append("FROM workflows w")
query_parts.append("LEFT JOIN workflow_stats ws ON w.filename = ws.workflow_id")
conditions = []
params = []
# Apply filters
if kwargs.get("search"):
conditions.append(
"(w.name LIKE ? OR w.description LIKE ? OR w.integrations LIKE ?)"
)
search_term = f"%{kwargs['search']}%"
params.extend([search_term, search_term, search_term])
if kwargs.get("category"):
conditions.append("w.category = ?")
params.append(kwargs["category"])
if kwargs.get("trigger_type"):
conditions.append("w.trigger_type = ?")
params.append(kwargs["trigger_type"])
if kwargs.get("complexity"):
conditions.append("w.complexity = ?")
params.append(kwargs["complexity"])
if kwargs.get("integration"):
conditions.append("w.integrations LIKE ?")
params.append(f"%{kwargs['integration']}%")
if kwargs.get("min_rating"):
conditions.append("ws.average_rating >= ?")
params.append(kwargs["min_rating"])
# Add conditions to query
if conditions:
query_parts.append("WHERE " + " AND ".join(conditions))
# Add sorting
sort_by = kwargs.get("sort_by", "name")
sort_order = kwargs.get("sort_order", "asc").upper()
query_parts.append(f"ORDER BY {sort_by} {sort_order}")
# Add pagination
query_parts.append("LIMIT ? OFFSET ?")
params.extend([kwargs.get("limit", 20), kwargs.get("offset", 0)])
# Execute query
query = " ".join(query_parts)
cursor.execute(query, params)
workflows = []
for row in cursor.fetchall():
workflows.append(
{
"filename": row[0],
"name": row[1],
"workflow_id": row[2],
"active": bool(row[3]),
"description": row[4],
"trigger_type": row[5],
"complexity": row[6],
"node_count": row[7],
"integrations": row[8],
"tags": row[9],
"created_at": row[10],
"updated_at": row[11],
"file_hash": row[12],
"file_size": row[13],
"analyzed_at": row[14],
"average_rating": row[15],
"total_ratings": row[16],
}
)
conn.close()
return workflows
def _advanced_search(self, request: WorkflowSearchRequest) -> List[Dict]:
"""Advanced search with complex queries"""
# Implementation for advanced search logic
# This would include semantic search, fuzzy matching, etc.
return self._search_workflows_enhanced(
search=request.query,
category=request.categories[0] if request.categories else None,
trigger_type=request.trigger_types[0] if request.trigger_types else None,
complexity=request.complexity_levels[0]
if request.complexity_levels
else None,
limit=request.limit,
offset=request.offset,
)
def _get_workflow_details(
self,
workflow_id: str,
include_stats: bool,
include_ratings: bool,
include_related: bool,
) -> Dict:
"""Get detailed workflow information"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Get basic workflow data
cursor.execute("SELECT * FROM workflows WHERE filename = ?", (workflow_id,))
workflow_row = cursor.fetchone()
if not workflow_row:
conn.close()
return None
workflow_data = {
"filename": workflow_row[0],
"name": workflow_row[1],
"workflow_id": workflow_row[2],
"active": bool(workflow_row[3]),
"description": workflow_row[4],
"trigger_type": workflow_row[5],
"complexity": workflow_row[6],
"node_count": workflow_row[7],
"integrations": workflow_row[8],
"tags": workflow_row[9],
"created_at": workflow_row[10],
"updated_at": workflow_row[11],
"file_hash": workflow_row[12],
"file_size": workflow_row[13],
"analyzed_at": workflow_row[14],
}
# Add statistics if requested
if include_stats:
stats = self.community.get_workflow_stats(workflow_id)
workflow_data["stats"] = stats.__dict__ if stats else None
# Add ratings if requested
if include_ratings:
ratings = self.community.get_workflow_ratings(workflow_id, 5)
workflow_data["ratings"] = [rating.__dict__ for rating in ratings]
# Add related workflows if requested
if include_related:
related = self._get_related_workflows(workflow_id)
workflow_data["related_workflows"] = related
conn.close()
return workflow_data
def _get_recommendations(
self, request: WorkflowRecommendationRequest
) -> List[Dict]:
"""Get personalized workflow recommendations"""
# Implementation for recommendation algorithm
# This would use collaborative filtering, content-based filtering, etc.
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Simple recommendation based on user interests
recommendations = []
for interest in request.user_interests:
cursor.execute(
"""
SELECT * FROM workflows
WHERE integrations LIKE ? OR name LIKE ? OR description LIKE ?
LIMIT 5
""",
(f"%{interest}%", f"%{interest}%", f"%{interest}%"),
)
for row in cursor.fetchall():
recommendations.append(
{
"filename": row[0],
"name": row[1],
"description": row[4],
"reason": f"Matches your interest in {interest}",
}
)
conn.close()
return recommendations[: request.limit]
def _get_trending_workflows(self, limit: int) -> List[Dict]:
"""Get trending workflows based on recent activity"""
return self.community.get_most_popular_workflows(limit)
def _get_analytics_overview(self) -> Dict:
"""Get analytics overview"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Total workflows
cursor.execute("SELECT COUNT(*) FROM workflows")
total_workflows = cursor.fetchone()[0]
# Active workflows
cursor.execute("SELECT COUNT(*) FROM workflows WHERE active = 1")
active_workflows = cursor.fetchone()[0]
# Categories
cursor.execute("SELECT category, COUNT(*) FROM workflows GROUP BY category")
categories = dict(cursor.fetchall())
# Integrations
cursor.execute("SELECT COUNT(DISTINCT integrations) FROM workflows")
unique_integrations = cursor.fetchone()[0]
conn.close()
return {
"total_workflows": total_workflows,
"active_workflows": active_workflows,
"categories": categories,
"unique_integrations": unique_integrations,
"timestamp": datetime.now().isoformat(),
}
def _get_custom_analytics(self, request: AnalyticsRequest) -> Dict:
"""Get custom analytics data"""
# Implementation for custom analytics
return {
"date_range": request.date_range,
"metrics": request.metrics,
"data": {}, # Placeholder for actual analytics data
"timestamp": datetime.now().isoformat(),
}
def _get_health_status(self) -> Dict:
"""Get health status and performance metrics"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Database health
cursor.execute("SELECT COUNT(*) FROM workflows")
total_workflows = cursor.fetchone()[0]
# Performance test
start_time = time.time()
cursor.execute("SELECT COUNT(*) FROM workflows WHERE active = 1")
active_count = cursor.fetchone()[0]
query_time = (time.time() - start_time) * 1000
conn.close()
return {
"status": "healthy",
"database": {
"total_workflows": total_workflows,
"active_workflows": active_count,
"connection_status": "connected",
},
"performance": {
"query_time_ms": round(query_time, 2),
"response_time_target": "<100ms",
"status": "good" if query_time < 100 else "slow",
},
"timestamp": datetime.now().isoformat(),
}
def _get_related_workflows(self, workflow_id: str, limit: int = 5) -> List[Dict]:
"""Get related workflows based on similar integrations or categories"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Get current workflow details
cursor.execute(
"SELECT integrations, category FROM workflows WHERE filename = ?",
(workflow_id,),
)
current_workflow = cursor.fetchone()
if not current_workflow:
conn.close()
return []
current_integrations = current_workflow[0] or ""
current_category = current_workflow[1] or ""
# Find related workflows
cursor.execute(
"""
SELECT filename, name, description FROM workflows
WHERE filename != ?
AND (integrations LIKE ? OR category = ?)
LIMIT ?
""",
(workflow_id, f"%{current_integrations[:50]}%", current_category, limit),
)
related = []
for row in cursor.fetchall():
related.append({"filename": row[0], "name": row[1], "description": row[2]})
conn.close()
return related
def run(self, host: str = "127.0.0.1", port: int = 8000, debug: bool = False):
"""Run the enhanced API server"""
uvicorn.run(
self.app, host=host, port=port, log_level="debug" if debug else "info"
)
if __name__ == "__main__":
# Initialize and run enhanced API
api = EnhancedAPI()
print("🚀 Starting Enhanced N8N Workflows API...")
print(
"📊 Features: Advanced search, recommendations, analytics, community features"
)
print("🌐 API Documentation: http://127.0.0.1:8000/docs")
api.run(debug=True)
| python | MIT | 61bc7a4455c49d47b0e288848e72ccd5778a7470 | 2026-01-04T14:39:30.370607Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/scripts/do_django_release.py | scripts/do_django_release.py | #! /usr/bin/env python
"""Helper to build and publish Django artifacts.
Original author: Tim Graham.
Other authors: Mariusz Felisiak, Natalia Bidart.
"""
import hashlib
import os
import re
import subprocess
from datetime import date
PGP_KEY_ID = os.getenv("PGP_KEY_ID")
PGP_KEY_URL = os.getenv("PGP_KEY_URL")
PGP_EMAIL = os.getenv("PGP_EMAIL")
DEST_FOLDER = os.path.expanduser(os.getenv("DEST_FOLDER"))
assert (
PGP_KEY_ID
), "Missing PGP_KEY_ID: Set this env var to your PGP key ID (used for signing)."
assert (
PGP_KEY_URL
), "Missing PGP_KEY_URL: Set this env var to your PGP public key URL (for fetching)."
assert DEST_FOLDER and os.path.exists(
DEST_FOLDER
), "Missing DEST_FOLDER: Set this env var to the local path to place the artifacts."
checksum_file_text = """This file contains MD5, SHA1, and SHA256 checksums for the
source-code tarball and wheel files of Django {django_version}, released {release_date}.
To use this file, you will need a working install of PGP or other
compatible public-key encryption software. You will also need to have
the Django release manager's public key in your keyring. This key has
the ID ``{pgp_key_id}`` and can be imported from the MIT
keyserver, for example, if using the open-source GNU Privacy Guard
implementation of PGP:
gpg --keyserver pgp.mit.edu --recv-key {pgp_key_id}
or via the GitHub API:
curl {pgp_key_url} | gpg --import -
Once the key is imported, verify this file:
gpg --verify {checksum_file_name}
Once you have verified this file, you can use normal MD5, SHA1, or SHA256
checksumming applications to generate the checksums of the Django
package and compare them to the checksums listed below.
Release packages
================
https://www.djangoproject.com/download/{django_version}/tarball/
https://www.djangoproject.com/download/{django_version}/wheel/
MD5 checksums
=============
{md5_tarball} {tarball_name}
{md5_wheel} {wheel_name}
SHA1 checksums
==============
{sha1_tarball} {tarball_name}
{sha1_wheel} {wheel_name}
SHA256 checksums
================
{sha256_tarball} {tarball_name}
{sha256_wheel} {wheel_name}
"""
def build_artifacts():
from build.__main__ import main as build_main
build_main([])
def do_checksum(checksum_algo, release_file):
with open(os.path.join(dist_path, release_file), "rb") as f:
return checksum_algo(f.read()).hexdigest()
# Ensure the working directory is clean.
subprocess.call(["git", "clean", "-fdx"])
django_repo_path = os.path.abspath(os.path.curdir)
dist_path = os.path.join(django_repo_path, "dist")
# Build release files.
build_artifacts()
release_files = os.listdir(dist_path)
wheel_name = None
tarball_name = None
for f in release_files:
if f.endswith(".whl"):
wheel_name = f
if f.endswith(".tar.gz"):
tarball_name = f
assert wheel_name is not None
assert tarball_name is not None
django_version = wheel_name.split("-")[1]
django_major_version = ".".join(django_version.split(".")[:2])
artifacts_path = os.path.join(os.path.expanduser(DEST_FOLDER), django_version)
os.makedirs(artifacts_path, exist_ok=True)
# Chop alpha/beta/rc suffix
match = re.search("[abrc]", django_major_version)
if match:
django_major_version = django_major_version[: match.start()]
release_date = date.today().strftime("%B %-d, %Y")
checksum_file_name = f"Django-{django_version}.checksum.txt"
checksum_file_kwargs = dict(
release_date=release_date,
pgp_key_id=PGP_KEY_ID,
django_version=django_version,
pgp_key_url=PGP_KEY_URL,
checksum_file_name=checksum_file_name,
wheel_name=wheel_name,
tarball_name=tarball_name,
)
checksums = (
("md5", hashlib.md5),
("sha1", hashlib.sha1),
("sha256", hashlib.sha256),
)
for checksum_name, checksum_algo in checksums:
checksum_file_kwargs[f"{checksum_name}_tarball"] = do_checksum(
checksum_algo, tarball_name
)
checksum_file_kwargs[f"{checksum_name}_wheel"] = do_checksum(
checksum_algo, wheel_name
)
# Create the checksum file
checksum_file_text = checksum_file_text.format(**checksum_file_kwargs)
checksum_file_path = os.path.join(artifacts_path, checksum_file_name)
with open(checksum_file_path, "wb") as f:
f.write(checksum_file_text.encode("ascii"))
print("\n\nDiffing release with checkout for sanity check.")
# Unzip and diff...
unzip_command = [
"unzip",
"-q",
os.path.join(dist_path, wheel_name),
"-d",
os.path.join(dist_path, django_major_version),
]
subprocess.run(unzip_command)
diff_command = [
"diff",
"-qr",
"./django/",
os.path.join(dist_path, django_major_version, "django"),
]
subprocess.run(diff_command)
subprocess.run(
[
"rm",
"-rf",
os.path.join(dist_path, django_major_version),
]
)
print("\n\n=> Commands to run NOW:")
# Sign the checksum file, this may prompt for a passphrase.
pgp_email = f"-u {PGP_EMAIL} " if PGP_EMAIL else ""
print(f"gpg --clearsign {pgp_email}--digest-algo SHA256 {checksum_file_path}")
# Create, verify and push tag
print(f'git tag --sign --message="Tag {django_version}" {django_version}')
print(f"git tag --verify {django_version}")
# Copy binaries outside the current repo tree to avoid lossing them.
subprocess.run(["cp", "-r", dist_path, artifacts_path])
# Make the binaries available to the world
print(
"\n\n=> These ONLY 15 MINUTES BEFORE RELEASE TIME (consider new terminal "
"session with isolated venv)!"
)
# Upload the checksum file and release artifacts to the djangoproject admin.
print(
"\n==> ACTION Add tarball, wheel, and checksum files to the Release entry at:"
f"https://www.djangoproject.com/admin/releases/release/{django_version}"
)
print(
f"* Tarball and wheel from {artifacts_path}\n"
f"* Signed checksum {checksum_file_path}.asc"
)
# Test the new version and confirm the signature using Jenkins.
print("\n==> ACTION Test the release artifacts:")
print(f"VERSION={django_version} test_new_version.sh")
print("\n==> ACTION Run confirm-release job:")
print(f"VERSION={django_version} confirm_release.sh")
# Upload to PyPI.
print("\n==> ACTION Upload to PyPI, ensure your release venv is activated:")
print(f"cd {artifacts_path}")
print("pip install -U pip twine")
print("twine upload --repository django dist/*")
# Push the tags.
print("\n==> ACTION Push the tags:")
print("git push --tags")
print("\n\nDONE!!!")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/scripts/manage_translations.py | scripts/manage_translations.py | #!/usr/bin/env python
#
# This Python file contains utility scripts to manage Django translations.
# It has to be run inside the django git root directory.
#
# The following commands are available:
#
# * update_catalogs: check for new strings in core and contrib catalogs, and
# output how much strings are new/changed.
#
# * lang_stats: output statistics for each catalog/language combination
#
# * fetch: fetch translations from transifex.com
#
# Each command support the --languages and --resources options to limit their
# operation to the specified language or resource. For example, to get stats
# for Spanish in contrib.admin, run:
#
# $ python scripts/manage_translations.py lang_stats -l es -r admin
#
# Also each command supports a --verbosity option to get progress feedback.
import json
import os
import subprocess
from argparse import ArgumentParser
from collections import defaultdict
from configparser import ConfigParser
from datetime import datetime
from itertools import product
import requests
import django
from django.conf import settings
from django.core.management import call_command
HAVE_JS = ["admin"]
LANG_OVERRIDES = {
"zh_CN": "zh_Hans",
"zh_TW": "zh_Hant",
}
def run(*args, verbosity=0, **kwargs):
if verbosity > 1:
print(f"\n** subprocess.run ** command: {args=} {kwargs=}")
return subprocess.run(*args, **kwargs)
def get_api_token():
# Read token from ENV, otherwise read from the ~/.transifexrc file.
api_token = os.getenv("TRANSIFEX_API_TOKEN")
if not api_token:
parser = ConfigParser()
parser.read(os.path.expanduser("~/.transifexrc"))
api_token = parser.get("https://www.transifex.com", "token")
assert api_token, "Please define the TRANSIFEX_API_TOKEN env var."
return api_token
def get_api_response(endpoint, api_token=None, params=None, verbosity=0):
if api_token is None:
api_token = get_api_token()
headers = {
"Authorization": f"Bearer {api_token}",
"Accept": "application/vnd.api+json",
"Content-Type": "application/json",
}
endpoint = endpoint.strip("/")
url = f"https://rest.api.transifex.com/{endpoint}"
if verbosity > 2:
print(f"\n>>> GET {url=} {params=}")
response = requests.get(url, headers=headers, params=params)
if verbosity > 2:
print(f">>>> GET {response=}\n")
response.raise_for_status()
return response.json()["data"]
def list_resources_with_updates(
date_since, resources=None, languages=None, verbosity=0
):
api_token = get_api_token()
project = "o:django:p:django"
date_since_iso = date_since.isoformat().strip("Z") + "Z"
if verbosity:
print(f"\n== Starting list_resources_with_updates at {date_since_iso=}")
if not languages:
languages = [ # List languages using Transifex projects API.
d["attributes"]["code"]
for d in get_api_response(
f"projects/{project}/languages", api_token, verbosity=verbosity
)
]
if verbosity > 1:
print(f"\n=== Languages to process: {languages=}")
if not resources:
resources = [ # List resources using Transifex resources API.
d["attributes"]["slug"]
for d in get_api_response(
"resources",
api_token,
params={"filter[project]": project},
verbosity=verbosity,
)
]
else:
resources = [_tx_resource_slug_for_name(r) for r in resources]
if verbosity > 1:
print(f"\n=== Resources to process: {resources=}")
resource_lang_changed = defaultdict(list)
for lang, resource in product(languages, resources):
if verbosity:
print(f"\n=== Getting data for: {lang=} {resource=} {date_since_iso=}")
data = get_api_response(
"resource_translations",
api_token,
params={
"filter[resource]": f"{project}:r:{resource}",
"filter[language]": f"l:{lang}",
"filter[date_translated][gt]": date_since_iso,
},
verbosity=verbosity,
)
local_resource = resource.replace("contrib-", "", 1)
local_lang = lang # XXX: LANG_OVERRIDES.get(lang, lang)
if data:
resource_lang_changed[local_resource].append(local_lang)
if verbosity > 2:
fname = f"{local_resource}-{local_lang}.json"
with open(fname, "w") as f:
f.write(json.dumps(data, sort_keys=True, indent=2))
print(f"==== Stored full data JSON in: {fname}")
if verbosity > 1:
print(f"==== Result for {local_resource=} {local_lang=}: {len(data)=}")
return resource_lang_changed
def _get_locale_dirs(resources, include_core=True):
"""
Return a tuple (contrib name, absolute path) for all locale directories,
optionally including the django core catalog.
If resources list is not None, filter directories matching resources
content.
"""
contrib_dir = os.path.join(os.getcwd(), "django", "contrib")
dirs = []
# Collect all locale directories
for contrib_name in os.listdir(contrib_dir):
path = os.path.join(contrib_dir, contrib_name, "locale")
if os.path.isdir(path):
dirs.append((contrib_name, path))
if contrib_name in HAVE_JS:
dirs.append(("%s-js" % contrib_name, path))
if include_core:
dirs.insert(0, ("core", os.path.join(os.getcwd(), "django", "conf", "locale")))
# Filter by resources, if any
if resources is not None:
res_names = [d[0] for d in dirs]
dirs = [ld for ld in dirs if ld[0] in resources]
if len(resources) > len(dirs):
print(
"You have specified some unknown resources. "
"Available resource names are: %s" % (", ".join(res_names),)
)
exit(1)
return dirs
def _tx_resource_slug_for_name(name):
"""Return the Transifex resource slug for the given name."""
if name != "core":
name = f"contrib-{name}"
return name
def _tx_resource_for_name(name):
"""Return the Transifex resource name."""
return "django." + _tx_resource_slug_for_name(name)
def _check_diff(cat_name, base_path):
"""
Output the approximate number of changed/added strings in the en catalog.
"""
po_path = "%(path)s/en/LC_MESSAGES/django%(ext)s.po" % {
"path": base_path,
"ext": "js" if cat_name.endswith("-js") else "",
}
p = run(
"git diff -U0 %s | egrep '^[-+]msgid' | wc -l" % po_path,
capture_output=True,
shell=True,
)
num_changes = int(p.stdout.strip())
print("%d changed/added messages in '%s' catalog." % (num_changes, cat_name))
def update_catalogs(resources=None, languages=None, verbosity=0):
"""
Update the en/LC_MESSAGES/django.po (main and contrib) files with
new/updated translatable strings.
"""
settings.configure()
django.setup()
if resources is not None:
print("`update_catalogs` will always process all resources.")
contrib_dirs = _get_locale_dirs(None, include_core=False)
os.chdir(os.path.join(os.getcwd(), "django"))
print("Updating en catalogs for Django and contrib apps...")
call_command("makemessages", locale=["en"], verbosity=verbosity)
print("Updating en JS catalogs for Django and contrib apps...")
call_command("makemessages", locale=["en"], domain="djangojs", verbosity=verbosity)
# Output changed stats
_check_diff("core", os.path.join(os.getcwd(), "conf", "locale"))
for name, dir_ in contrib_dirs:
_check_diff(name, dir_)
def lang_stats(resources=None, languages=None, verbosity=0):
"""
Output language statistics of committed translation files for each
Django catalog.
If resources is provided, it should be a list of translation resource to
limit the output (e.g. ['core', 'gis']).
"""
locale_dirs = _get_locale_dirs(resources)
for name, dir_ in locale_dirs:
print("\nShowing translations stats for '%s':" % name)
langs = sorted(d for d in os.listdir(dir_) if not d.startswith("_"))
for lang in langs:
if languages and lang not in languages:
continue
# TODO: merge first with the latest en catalog
po_path = "{path}/{lang}/LC_MESSAGES/django{ext}.po".format(
path=dir_, lang=lang, ext="js" if name.endswith("-js") else ""
)
p = run(
["msgfmt", "-vc", "-o", "/dev/null", po_path],
capture_output=True,
env={"LANG": "C"},
encoding="utf-8",
verbosity=verbosity,
)
if p.returncode == 0:
# msgfmt output stats on stderr
print("%s: %s" % (lang, p.stderr.strip()))
else:
print(
"Errors happened when checking %s translation for %s:\n%s"
% (lang, name, p.stderr)
)
def fetch(resources=None, languages=None, date_since=None, verbosity=0):
"""
Fetch translations from Transifex, wrap long lines, generate mo files.
"""
if date_since is None:
resource_lang_mapping = {}
else:
# Filter resources and languages that were updates after `date_since`
resource_lang_mapping = list_resources_with_updates(
date_since=date_since,
resources=resources,
languages=languages,
verbosity=verbosity,
)
resources = resource_lang_mapping.keys()
locale_dirs = _get_locale_dirs(resources)
errors = []
for name, dir_ in locale_dirs:
cmd = [
"tx",
"pull",
"-r",
_tx_resource_for_name(name),
"-f",
"--minimum-perc=5",
]
per_resource_langs = resource_lang_mapping.get(name, languages)
# Transifex pull
if per_resource_langs is None:
run([*cmd, "--all"], verbosity=verbosity)
target_langs = sorted(
d for d in os.listdir(dir_) if not d.startswith("_") and d != "en"
)
else:
run([*cmd, "-l", ",".join(per_resource_langs)], verbosity=verbosity)
target_langs = per_resource_langs
target_langs = [LANG_OVERRIDES.get(d, d) for d in target_langs]
# msgcat to wrap lines and msgfmt for compilation of .mo file
for lang in target_langs:
po_path = "%(path)s/%(lang)s/LC_MESSAGES/django%(ext)s.po" % {
"path": dir_,
"lang": lang,
"ext": "js" if name.endswith("-js") else "",
}
if not os.path.exists(po_path):
print(
"No %(lang)s translation for resource %(name)s"
% {"lang": lang, "name": name}
)
continue
run(
["msgcat", "--no-location", "-o", po_path, po_path], verbosity=verbosity
)
msgfmt = run(
["msgfmt", "-c", "-o", "%s.mo" % po_path[:-3], po_path],
verbosity=verbosity,
)
if msgfmt.returncode != 0:
errors.append((name, lang))
if errors:
print("\nWARNING: Errors have occurred in following cases:")
for resource, lang in errors:
print("\tResource %s for language %s" % (resource, lang))
exit(1)
if verbosity:
print("\nCOMPLETED.")
def add_common_arguments(parser):
parser.add_argument(
"-r",
"--resources",
action="append",
help="limit operation to the specified resources",
)
parser.add_argument(
"-l",
"--languages",
action="append",
help="limit operation to the specified languages",
)
parser.add_argument(
"-v",
"--verbosity",
default=1,
type=int,
choices=[0, 1, 2, 3],
help=(
"Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, "
"3=very verbose output"
),
)
if __name__ == "__main__":
parser = ArgumentParser()
subparsers = parser.add_subparsers(
dest="cmd", help="choose the operation to perform"
)
parser_update = subparsers.add_parser(
"update_catalogs",
help="update English django.po files with new/updated translatable strings",
)
add_common_arguments(parser_update)
parser_stats = subparsers.add_parser(
"lang_stats",
help="print the approximate number of changed/added strings in the en catalog",
)
add_common_arguments(parser_stats)
parser_fetch = subparsers.add_parser(
"fetch",
help="fetch translations from Transifex, wrap long lines, generate mo files",
)
add_common_arguments(parser_fetch)
parser_fetch.add_argument(
"-s",
"--since",
dest="date_since",
metavar="YYYY-MM-DD",
type=datetime.fromisoformat,
help=(
"fetch translations that were done after this date (ISO format YYYY-MM-DD)."
),
)
options = parser.parse_args()
kwargs = options.__dict__
cmd = kwargs.pop("cmd")
eval(cmd)(**kwargs)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/scripts/archive_eol_stable_branches.py | scripts/archive_eol_stable_branches.py | #! /usr/bin/env python3
import argparse
import os
import subprocess
import sys
def run(cmd, *, cwd=None, env=None, dry_run=True):
"""Run a command with optional dry-run behavior."""
environ = os.environ.copy()
if env:
environ.update(env)
if dry_run:
print("[DRY RUN]", " ".join(cmd))
else:
print("[EXECUTE]", " ".join(cmd))
try:
result = subprocess.check_output(
cmd, cwd=cwd, env=environ, stderr=subprocess.STDOUT
)
except subprocess.CalledProcessError as e:
result = e.output
print(" [ERROR]", result)
raise
else:
print(" [RESULT]", result)
return result.decode().strip()
def validate_env(checkout_dir):
if not checkout_dir:
sys.exit("Error: checkout directory not provided (--checkout-dir).")
if not os.path.exists(checkout_dir):
sys.exit(f"Error: checkout directory '{checkout_dir}' does not exist.")
if not os.path.isdir(checkout_dir):
sys.exit(f"Error: '{checkout_dir}' is not a directory.")
def get_remote_branches(checkout_dir, include_fn):
"""Return list of remote branches filtered by include_fn."""
result = run(
["git", "branch", "--list", "-r"],
cwd=checkout_dir,
dry_run=False,
)
branches = [b.strip() for b in result.split("\n") if b.strip()]
return [b for b in branches if include_fn(b)]
def get_branch_info(checkout_dir, branch):
"""Return (commit_hash, last_update_date) for a given branch."""
commit_hash = run(["git", "rev-parse", branch], cwd=checkout_dir, dry_run=False)
last_update = run(
["git", "show", branch, "--format=format:%ai", "-s"],
cwd=checkout_dir,
dry_run=False,
)
return commit_hash, last_update
def create_tag(checkout_dir, branch, commit_hash, last_update, *, dry_run=True):
"""Create a tag locally for a given branch at its last update."""
tag_name = branch.replace("origin/", "", 1)
msg = f'"Tagged {tag_name} for EOL stable branch removal."'
run(
["git", "tag", "--sign", "--message", msg, tag_name, commit_hash],
cwd=checkout_dir,
env={"GIT_COMMITTER_DATE": last_update},
dry_run=dry_run,
)
return tag_name
def delete_remote_and_local_branch(checkout_dir, branch, *, dry_run=True):
"""Delete a remote branch from origin and the maching local branch."""
try:
run(
["git", "branch", "-D", branch],
cwd=checkout_dir,
dry_run=dry_run,
)
except subprocess.CalledProcessError:
print(f"[ERROR] Local branch {branch} can not be deleted.")
run(
["git", "push", "origin", "--delete", branch.replace("origin/", "", 1)],
cwd=checkout_dir,
dry_run=dry_run,
)
def main():
parser = argparse.ArgumentParser(
description="Archive Django branches into tags and optionally delete them."
)
parser.add_argument(
"--checkout-dir", required=True, help="Path to Django git checkout"
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Print commands instead of executing them",
)
parser.add_argument(
"--branches", nargs="*", help="Specific remote branches to include (optional)"
)
args = parser.parse_args()
validate_env(args.checkout_dir)
dry_run = args.dry_run
checkout_dir = args.checkout_dir
if args.branches:
wanted = set(f"origin/{b}" for b in args.branches)
else:
wanted = set()
branches = get_remote_branches(checkout_dir, include_fn=lambda b: b in wanted)
if not branches:
print("No branches matched inclusion criteria.")
return
print("\nMatched branches:")
print("\n".join(branches))
print()
branch_updates = {b: get_branch_info(checkout_dir, b) for b in branches}
print("\nLast updates:")
for b, (h, d) in branch_updates.items():
print(f"{b}\t{h}\t{d}")
if (
input("\nDelete remote branches and create tags? [y/N]: ").strip().lower()
== "y"
):
for b, (commit_hash, last_update_date) in branch_updates.items():
print(f"Creating tag for {b} at {commit_hash=} with {last_update_date=}")
create_tag(checkout_dir, b, commit_hash, last_update_date, dry_run=dry_run)
print(f"Deleting remote branch {b}")
delete_remote_and_local_branch(checkout_dir, b, dry_run=dry_run)
run(
["git", "push", "--tags"],
cwd=checkout_dir,
dry_run=dry_run,
)
print("Done.")
if __name__ == "__main__":
main()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/shortcuts.py | django/shortcuts.py | """
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
from django.http import (
Http404,
HttpResponse,
HttpResponsePermanentRedirect,
HttpResponseRedirect,
)
from django.template import loader
from django.urls import NoReverseMatch, reverse
from django.utils.functional import Promise
from django.utils.translation import gettext as _
def render(
request, template_name, context=None, content_type=None, status=None, using=None
):
"""
Return an HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
content = loader.render_to_string(template_name, context, request, using=using)
return HttpResponse(content, content_type, status)
def redirect(to, *args, permanent=False, preserve_request=False, **kwargs):
"""
Return an HttpResponseRedirect to the appropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve the name.
* A URL, which will be used as-is for the redirect location.
Issues a temporary redirect by default. Set permanent=True to issue a
permanent redirect. Set preserve_request=True to instruct the user agent
to preserve the original HTTP method and body when following the redirect.
"""
redirect_class = (
HttpResponsePermanentRedirect if permanent else HttpResponseRedirect
)
return redirect_class(
resolve_url(to, *args, **kwargs),
preserve_request=preserve_request,
)
def _get_queryset(klass):
"""
Return a QuerySet or a Manager.
Duck typing in action: any class with a `get()` method (for
get_object_or_404) or a `filter()` method (for get_list_or_404) might do
the job.
"""
# If it is a model class or anything else with ._default_manager
if hasattr(klass, "_default_manager"):
return klass._default_manager.all()
return klass
def get_object_or_404(klass, *args, **kwargs):
"""
Use get() to return an object, or raise an Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
one object is found.
"""
queryset = _get_queryset(klass)
if not hasattr(queryset, "get"):
klass__name = (
klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
)
raise ValueError(
"First argument to get_object_or_404() must be a Model, Manager, "
"or QuerySet, not '%s'." % klass__name
)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
raise Http404(
# Translators: %s is the name of a model, e.g. "No City matches the
# given query."
_("No %s matches the given query.")
% queryset.model._meta.object_name
)
async def aget_object_or_404(klass, *args, **kwargs):
"""See get_object_or_404()."""
queryset = _get_queryset(klass)
if not hasattr(queryset, "aget"):
klass__name = (
klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
)
raise ValueError(
"First argument to aget_object_or_404() must be a Model, Manager, or "
f"QuerySet, not '{klass__name}'."
)
try:
return await queryset.aget(*args, **kwargs)
except queryset.model.DoesNotExist:
raise Http404(
_("No %s matches the given query.") % queryset.model._meta.object_name
)
def get_list_or_404(klass, *args, **kwargs):
"""
Use filter() to return a list of objects, or raise an Http404 exception if
the list is empty.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the filter() query.
"""
queryset = _get_queryset(klass)
if not hasattr(queryset, "filter"):
klass__name = (
klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
)
raise ValueError(
"First argument to get_list_or_404() must be a Model, Manager, or "
"QuerySet, not '%s'." % klass__name
)
obj_list = list(queryset.filter(*args, **kwargs))
if not obj_list:
raise Http404(
_("No %s matches the given query.") % queryset.model._meta.object_name
)
return obj_list
async def aget_list_or_404(klass, *args, **kwargs):
"""See get_list_or_404()."""
queryset = _get_queryset(klass)
if not hasattr(queryset, "filter"):
klass__name = (
klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
)
raise ValueError(
"First argument to aget_list_or_404() must be a Model, Manager, or "
f"QuerySet, not '{klass__name}'."
)
obj_list = [obj async for obj in queryset.filter(*args, **kwargs)]
if not obj_list:
raise Http404(
_("No %s matches the given query.") % queryset.model._meta.object_name
)
return obj_list
def resolve_url(to, *args, **kwargs):
"""
Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urls.reverse()` will be used
to reverse-resolve the name.
* A URL, which will be returned as-is.
"""
# If it's a model, use get_absolute_url()
if hasattr(to, "get_absolute_url"):
return to.get_absolute_url()
if isinstance(to, Promise):
# Expand the lazy instance, as it can cause issues when it is passed
# further to some Python functions like urlparse.
to = str(to)
# Handle relative URLs
if isinstance(to, str) and to.startswith(("./", "../")):
return to
# Next try a reverse URL resolution.
try:
return reverse(to, args=args, kwargs=kwargs)
except NoReverseMatch:
# If this is a callable, re-raise.
if callable(to):
raise
# If this doesn't "feel" like a URL, re-raise.
if "/" not in to and "." not in to:
raise
# Finally, fall back and assume it's a URL
return to
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/__main__.py | django/__main__.py | """
Invokes django-admin when the django module is run as a script.
Example: python -m django check
"""
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/__init__.py | django/__init__.py | from django.utils.version import get_version
VERSION = (6, 1, 0, "alpha", 0)
__version__ = get_version(VERSION)
def setup(set_prefix=True):
"""
Configure the settings (this happens as a side effect of accessing the
first setting), configure logging and populate the app registry.
Set the thread-local urlresolvers script prefix if `set_prefix` is True.
"""
from django.apps import apps
from django.conf import settings
from django.urls import set_script_prefix
from django.utils.log import configure_logging
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
if set_prefix:
set_script_prefix(
"/" if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
)
apps.populate(settings.INSTALLED_APPS)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/tasks/checks.py | django/tasks/checks.py | from django.core import checks
@checks.register
def check_tasks(app_configs=None, **kwargs):
"""Checks all registered Task backends."""
from . import task_backends
for backend in task_backends.all():
yield from backend.check()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/tasks/signals.py | django/tasks/signals.py | import logging
import sys
from asgiref.local import Local
from django.core.signals import setting_changed
from django.dispatch import Signal, receiver
from .base import TaskResultStatus
logger = logging.getLogger("django.tasks")
task_enqueued = Signal()
task_finished = Signal()
task_started = Signal()
@receiver(setting_changed)
def clear_tasks_handlers(*, setting, **kwargs):
"""Reset the connection handler whenever the settings change."""
if setting == "TASKS":
from . import task_backends
task_backends._settings = task_backends.settings = (
task_backends.configure_settings(None)
)
task_backends._connections = Local()
@receiver(task_enqueued)
def log_task_enqueued(sender, task_result, **kwargs):
logger.debug(
"Task id=%s path=%s enqueued backend=%s",
task_result.id,
task_result.task.module_path,
task_result.backend,
)
@receiver(task_started)
def log_task_started(sender, task_result, **kwargs):
logger.info(
"Task id=%s path=%s state=%s",
task_result.id,
task_result.task.module_path,
task_result.status,
)
@receiver(task_finished)
def log_task_finished(sender, task_result, **kwargs):
logger.log(
(
logging.ERROR
if task_result.status == TaskResultStatus.FAILED
else logging.INFO
),
"Task id=%s path=%s state=%s",
task_result.id,
task_result.task.module_path,
task_result.status,
# Signal is sent inside exception handlers, so exc_info() is available.
exc_info=sys.exc_info(),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/tasks/exceptions.py | django/tasks/exceptions.py | from django.core.exceptions import ImproperlyConfigured
class TaskException(Exception):
"""Base class for task-related exceptions. Do not raise directly."""
class InvalidTask(TaskException):
"""The provided Task is invalid."""
class InvalidTaskBackend(ImproperlyConfigured):
"""The provided Task backend is invalid."""
class TaskResultDoesNotExist(TaskException):
"""The requested TaskResult does not exist."""
class TaskResultMismatch(TaskException):
"""The requested TaskResult is invalid."""
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/tasks/__init__.py | django/tasks/__init__.py | from django.utils.connection import BaseConnectionHandler, ConnectionProxy
from django.utils.module_loading import import_string
from . import checks, signals # NOQA
from .base import (
DEFAULT_TASK_BACKEND_ALIAS,
DEFAULT_TASK_QUEUE_NAME,
Task,
TaskContext,
TaskResult,
TaskResultStatus,
task,
)
from .exceptions import InvalidTaskBackend
__all__ = [
"DEFAULT_TASK_BACKEND_ALIAS",
"DEFAULT_TASK_QUEUE_NAME",
"default_task_backend",
"task",
"task_backends",
"Task",
"TaskContext",
"TaskResult",
"TaskResultStatus",
]
class TaskBackendHandler(BaseConnectionHandler):
settings_name = "TASKS"
exception_class = InvalidTaskBackend
def create_connection(self, alias):
params = self.settings[alias]
backend = params["BACKEND"]
try:
backend_cls = import_string(backend)
except ImportError as e:
raise InvalidTaskBackend(f"Could not find backend '{backend}': {e}") from e
return backend_cls(alias=alias, params=params)
task_backends = TaskBackendHandler()
default_task_backend = ConnectionProxy(task_backends, DEFAULT_TASK_BACKEND_ALIAS)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/tasks/base.py | django/tasks/base.py | from dataclasses import dataclass, field, replace
from datetime import datetime
from inspect import isclass, iscoroutinefunction
from typing import Any, Callable, Dict, Optional
from asgiref.sync import async_to_sync, sync_to_async
from django.db.models.enums import TextChoices
from django.utils.json import normalize_json
from django.utils.module_loading import import_string
from django.utils.translation import pgettext_lazy
from .exceptions import TaskResultMismatch
DEFAULT_TASK_BACKEND_ALIAS = "default"
DEFAULT_TASK_PRIORITY = 0
DEFAULT_TASK_QUEUE_NAME = "default"
TASK_MAX_PRIORITY = 100
TASK_MIN_PRIORITY = -100
TASK_REFRESH_ATTRS = {
"errors",
"_return_value",
"finished_at",
"started_at",
"last_attempted_at",
"status",
"enqueued_at",
"worker_ids",
}
class TaskResultStatus(TextChoices):
# The Task has just been enqueued, or is ready to be executed again.
READY = ("READY", pgettext_lazy("Task", "Ready"))
# The Task is currently running.
RUNNING = ("RUNNING", pgettext_lazy("Task", "Running"))
# The Task raised an exception during execution, or was unable to start.
FAILED = ("FAILED", pgettext_lazy("Task", "Failed"))
# The Task has finished running successfully.
SUCCESSFUL = ("SUCCESSFUL", pgettext_lazy("Task", "Successful"))
@dataclass(frozen=True, slots=True, kw_only=True)
class Task:
priority: int
func: Callable # The Task function.
backend: str
queue_name: str
run_after: Optional[datetime] # The earliest this Task will run.
# Whether the Task receives the Task context when executed.
takes_context: bool = False
def __post_init__(self):
self.get_backend().validate_task(self)
@property
def name(self):
return self.func.__name__
def using(
self,
*,
priority=None,
queue_name=None,
run_after=None,
backend=None,
):
"""Create a new Task with modified defaults."""
changes = {}
if priority is not None:
changes["priority"] = priority
if queue_name is not None:
changes["queue_name"] = queue_name
if run_after is not None:
changes["run_after"] = run_after
if backend is not None:
changes["backend"] = backend
return replace(self, **changes)
def enqueue(self, *args, **kwargs):
"""Queue up the Task to be executed."""
return self.get_backend().enqueue(self, args, kwargs)
async def aenqueue(self, *args, **kwargs):
"""Queue up the Task to be executed."""
return await self.get_backend().aenqueue(self, args, kwargs)
def get_result(self, result_id):
"""
Retrieve a task result by id.
Raise TaskResultDoesNotExist if such result does not exist, or raise
TaskResultMismatch if the result exists but belongs to another Task.
"""
result = self.get_backend().get_result(result_id)
if result.task.func != self.func:
raise TaskResultMismatch(
f"Task does not match (received {result.task.module_path!r})"
)
return result
async def aget_result(self, result_id):
"""See get_result()."""
result = await self.get_backend().aget_result(result_id)
if result.task.func != self.func:
raise TaskResultMismatch(
f"Task does not match (received {result.task.module_path!r})"
)
return result
def call(self, *args, **kwargs):
if iscoroutinefunction(self.func):
return async_to_sync(self.func)(*args, **kwargs)
return self.func(*args, **kwargs)
async def acall(self, *args, **kwargs):
if iscoroutinefunction(self.func):
return await self.func(*args, **kwargs)
return await sync_to_async(self.func)(*args, **kwargs)
def get_backend(self):
from . import task_backends
return task_backends[self.backend]
@property
def module_path(self):
return f"{self.func.__module__}.{self.func.__qualname__}"
def task(
function=None,
*,
priority=DEFAULT_TASK_PRIORITY,
queue_name=DEFAULT_TASK_QUEUE_NAME,
backend=DEFAULT_TASK_BACKEND_ALIAS,
takes_context=False,
):
from . import task_backends
def wrapper(f):
return task_backends[backend].task_class(
priority=priority,
func=f,
queue_name=queue_name,
backend=backend,
takes_context=takes_context,
run_after=None,
)
if function:
return wrapper(function)
return wrapper
@dataclass(frozen=True, slots=True, kw_only=True)
class TaskError:
exception_class_path: str
traceback: str
@property
def exception_class(self):
# Lazy resolve the exception class.
exception_class = import_string(self.exception_class_path)
if not isclass(exception_class) or not issubclass(
exception_class, BaseException
):
raise ValueError(
f"{self.exception_class_path!r} does not reference a valid exception."
)
return exception_class
@dataclass(frozen=True, slots=True, kw_only=True)
class TaskResult:
task: Task
id: str # Unique identifier for the task result.
status: TaskResultStatus
enqueued_at: Optional[datetime] # Time the task was enqueued.
started_at: Optional[datetime] # Time the task was started.
finished_at: Optional[datetime] # Time the task was finished.
# Time the task was last attempted to be run.
last_attempted_at: Optional[datetime]
args: list # Arguments to pass to the task function.
kwargs: Dict[str, Any] # Keyword arguments to pass to the task function.
backend: str
errors: list[TaskError] # Errors raised when running the task.
worker_ids: list[str] # Workers which have processed the task.
_return_value: Optional[Any] = field(init=False, default=None)
def __post_init__(self):
object.__setattr__(self, "args", normalize_json(self.args))
object.__setattr__(self, "kwargs", normalize_json(self.kwargs))
@property
def return_value(self):
"""
The return value of the task.
If the task didn't succeed, an exception is raised.
This is to distinguish against the task returning None.
"""
if self.status == TaskResultStatus.SUCCESSFUL:
return self._return_value
elif self.status == TaskResultStatus.FAILED:
raise ValueError("Task failed")
else:
raise ValueError("Task has not finished yet")
@property
def is_finished(self):
return self.status in {TaskResultStatus.FAILED, TaskResultStatus.SUCCESSFUL}
@property
def attempts(self):
return len(self.worker_ids)
def refresh(self):
"""Reload the cached task data from the task store."""
refreshed_task = self.task.get_backend().get_result(self.id)
for attr in TASK_REFRESH_ATTRS:
object.__setattr__(self, attr, getattr(refreshed_task, attr))
async def arefresh(self):
"""
Reload the cached task data from the task store
"""
refreshed_task = await self.task.get_backend().aget_result(self.id)
for attr in TASK_REFRESH_ATTRS:
object.__setattr__(self, attr, getattr(refreshed_task, attr))
@dataclass(frozen=True, slots=True, kw_only=True)
class TaskContext:
task_result: TaskResult
@property
def attempt(self):
return self.task_result.attempts
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/tasks/backends/dummy.py | django/tasks/backends/dummy.py | from copy import deepcopy
from django.tasks.base import TaskResult, TaskResultStatus
from django.tasks.exceptions import TaskResultDoesNotExist
from django.tasks.signals import task_enqueued
from django.utils import timezone
from django.utils.crypto import get_random_string
from .base import BaseTaskBackend
class DummyBackend(BaseTaskBackend):
supports_defer = True
supports_async_task = True
supports_priority = True
def __init__(self, alias, params):
super().__init__(alias, params)
self.results = []
def _store_result(self, result):
object.__setattr__(result, "enqueued_at", timezone.now())
self.results.append(result)
task_enqueued.send(type(self), task_result=result)
def enqueue(self, task, args, kwargs):
self.validate_task(task)
result = TaskResult(
task=task,
id=get_random_string(32),
status=TaskResultStatus.READY,
enqueued_at=None,
started_at=None,
last_attempted_at=None,
finished_at=None,
args=args,
kwargs=kwargs,
backend=self.alias,
errors=[],
worker_ids=[],
)
self._store_result(result)
# Copy the task to prevent mutation issues.
return deepcopy(result)
def get_result(self, result_id):
# Results are only scoped to the current thread, hence
# supports_get_result is False.
try:
return next(result for result in self.results if result.id == result_id)
except StopIteration:
raise TaskResultDoesNotExist(result_id) from None
async def aget_result(self, result_id):
try:
return next(result for result in self.results if result.id == result_id)
except StopIteration:
raise TaskResultDoesNotExist(result_id) from None
def clear(self):
self.results.clear()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/tasks/backends/immediate.py | django/tasks/backends/immediate.py | import logging
from traceback import format_exception
from django.tasks.base import TaskContext, TaskError, TaskResult, TaskResultStatus
from django.tasks.signals import task_enqueued, task_finished, task_started
from django.utils import timezone
from django.utils.crypto import get_random_string
from django.utils.json import normalize_json
from .base import BaseTaskBackend
logger = logging.getLogger(__name__)
class ImmediateBackend(BaseTaskBackend):
supports_async_task = True
supports_priority = True
def __init__(self, alias, params):
super().__init__(alias, params)
self.worker_id = get_random_string(32)
def _execute_task(self, task_result):
"""
Execute the Task for the given TaskResult, mutating it with the
outcome.
"""
object.__setattr__(task_result, "enqueued_at", timezone.now())
task_enqueued.send(type(self), task_result=task_result)
task = task_result.task
task_start_time = timezone.now()
object.__setattr__(task_result, "status", TaskResultStatus.RUNNING)
object.__setattr__(task_result, "started_at", task_start_time)
object.__setattr__(task_result, "last_attempted_at", task_start_time)
task_result.worker_ids.append(self.worker_id)
task_started.send(sender=type(self), task_result=task_result)
try:
if task.takes_context:
raw_return_value = task.call(
TaskContext(task_result=task_result),
*task_result.args,
**task_result.kwargs,
)
else:
raw_return_value = task.call(*task_result.args, **task_result.kwargs)
object.__setattr__(
task_result,
"_return_value",
normalize_json(raw_return_value),
)
except KeyboardInterrupt:
# If the user tried to terminate, let them
raise
except BaseException as e:
object.__setattr__(task_result, "finished_at", timezone.now())
exception_type = type(e)
task_result.errors.append(
TaskError(
exception_class_path=(
f"{exception_type.__module__}.{exception_type.__qualname__}"
),
traceback="".join(format_exception(e)),
)
)
object.__setattr__(task_result, "status", TaskResultStatus.FAILED)
task_finished.send(type(self), task_result=task_result)
else:
object.__setattr__(task_result, "finished_at", timezone.now())
object.__setattr__(task_result, "status", TaskResultStatus.SUCCESSFUL)
task_finished.send(type(self), task_result=task_result)
def enqueue(self, task, args, kwargs):
self.validate_task(task)
task_result = TaskResult(
task=task,
id=get_random_string(32),
status=TaskResultStatus.READY,
enqueued_at=None,
started_at=None,
last_attempted_at=None,
finished_at=None,
args=args,
kwargs=kwargs,
backend=self.alias,
errors=[],
worker_ids=[],
)
self._execute_task(task_result)
return task_result
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/tasks/backends/__init__.py | django/tasks/backends/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/tasks/backends/base.py | django/tasks/backends/base.py | from abc import ABCMeta, abstractmethod
from inspect import iscoroutinefunction
from asgiref.sync import sync_to_async
from django.conf import settings
from django.tasks import DEFAULT_TASK_QUEUE_NAME
from django.tasks.base import (
DEFAULT_TASK_PRIORITY,
TASK_MAX_PRIORITY,
TASK_MIN_PRIORITY,
Task,
)
from django.tasks.exceptions import InvalidTask
from django.utils import timezone
from django.utils.inspect import get_func_args, is_module_level_function
class BaseTaskBackend(metaclass=ABCMeta):
task_class = Task
# Does the backend support Tasks to be enqueued with the run_after
# attribute?
supports_defer = False
# Does the backend support coroutines to be enqueued?
supports_async_task = False
# Does the backend support results being retrieved (from any
# thread/process)?
supports_get_result = False
# Does the backend support executing Tasks in a given
# priority order?
supports_priority = False
def __init__(self, alias, params):
self.alias = alias
self.queues = set(params.get("QUEUES", [DEFAULT_TASK_QUEUE_NAME]))
self.options = params.get("OPTIONS", {})
def validate_task(self, task):
"""
Determine whether the provided Task can be executed by the backend.
"""
if not is_module_level_function(task.func):
raise InvalidTask("Task function must be defined at a module level.")
if not self.supports_async_task and iscoroutinefunction(task.func):
raise InvalidTask("Backend does not support async Tasks.")
task_func_args = get_func_args(task.func)
if task.takes_context and (
not task_func_args or task_func_args[0] != "context"
):
raise InvalidTask(
"Task takes context but does not have a first argument of 'context'."
)
if not self.supports_priority and task.priority != DEFAULT_TASK_PRIORITY:
raise InvalidTask("Backend does not support setting priority of tasks.")
if (
task.priority < TASK_MIN_PRIORITY
or task.priority > TASK_MAX_PRIORITY
or int(task.priority) != task.priority
):
raise InvalidTask(
f"priority must be a whole number between {TASK_MIN_PRIORITY} and "
f"{TASK_MAX_PRIORITY}."
)
if not self.supports_defer and task.run_after is not None:
raise InvalidTask("Backend does not support run_after.")
if (
settings.USE_TZ
and task.run_after is not None
and not timezone.is_aware(task.run_after)
):
raise InvalidTask("run_after must be an aware datetime.")
if self.queues and task.queue_name not in self.queues:
raise InvalidTask(f"Queue '{task.queue_name}' is not valid for backend.")
@abstractmethod
def enqueue(self, task, args, kwargs):
"""Queue up a task to be executed."""
async def aenqueue(self, task, args, kwargs):
"""Queue up a task function (or coroutine) to be executed."""
return await sync_to_async(self.enqueue, thread_sensitive=True)(
task=task, args=args, kwargs=kwargs
)
def get_result(self, result_id):
"""
Retrieve a task result by id.
Raise TaskResultDoesNotExist if such result does not exist.
"""
raise NotImplementedError(
"This backend does not support retrieving or refreshing results."
)
async def aget_result(self, result_id):
"""See get_result()."""
return await sync_to_async(self.get_result, thread_sensitive=True)(
result_id=result_id
)
def check(self, **kwargs):
return []
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/templatetags/tz.py | django/templatetags/tz.py | import zoneinfo
from datetime import UTC, datetime, tzinfo
from django.template import Library, Node, TemplateSyntaxError
from django.utils import timezone
register = Library()
# HACK: datetime instances cannot be assigned new attributes. Define a subclass
# in order to define new attributes in do_timezone().
class datetimeobject(datetime):
pass
# Template filters
@register.filter
def localtime(value):
"""
Convert a datetime to local time in the active time zone.
This only makes sense within a {% localtime off %} block.
"""
return do_timezone(value, timezone.get_current_timezone())
@register.filter
def utc(value):
"""
Convert a datetime to UTC.
"""
return do_timezone(value, UTC)
@register.filter("timezone")
def do_timezone(value, arg):
"""
Convert a datetime to local time in a given time zone.
The argument must be an instance of a tzinfo subclass or a time zone name.
Naive datetimes are assumed to be in local time in the default time zone.
"""
if not isinstance(value, datetime):
return ""
# Obtain a timezone-aware datetime
try:
if timezone.is_naive(value):
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
# Filters must never raise exceptionsm, so catch everything.
except Exception:
return ""
# Obtain a tzinfo instance
if isinstance(arg, tzinfo):
tz = arg
elif isinstance(arg, str):
try:
tz = zoneinfo.ZoneInfo(arg)
except zoneinfo.ZoneInfoNotFoundError:
return ""
else:
return ""
result = timezone.localtime(value, tz)
# HACK: the convert_to_local_time flag will prevent
# automatic conversion of the value to local time.
result = datetimeobject(
result.year,
result.month,
result.day,
result.hour,
result.minute,
result.second,
result.microsecond,
result.tzinfo,
)
result.convert_to_local_time = False
return result
# Template tags
class LocalTimeNode(Node):
"""
Template node class used by ``localtime_tag``.
"""
def __init__(self, nodelist, use_tz):
self.nodelist = nodelist
self.use_tz = use_tz
def render(self, context):
old_setting = context.use_tz
context.use_tz = self.use_tz
output = self.nodelist.render(context)
context.use_tz = old_setting
return output
class TimezoneNode(Node):
"""
Template node class used by ``timezone_tag``.
"""
def __init__(self, nodelist, tz):
self.nodelist = nodelist
self.tz = tz
def render(self, context):
with timezone.override(self.tz.resolve(context)):
output = self.nodelist.render(context)
return output
class GetCurrentTimezoneNode(Node):
"""
Template node class used by ``get_current_timezone_tag``.
"""
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = timezone.get_current_timezone_name()
return ""
@register.tag("localtime")
def localtime_tag(parser, token):
"""
Force or prevent conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
"""
bits = token.split_contents()
if len(bits) == 1:
use_tz = True
elif len(bits) > 2 or bits[1] not in ("on", "off"):
raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0])
else:
use_tz = bits[1] == "on"
nodelist = parser.parse(("endlocaltime",))
parser.delete_first_token()
return LocalTimeNode(nodelist, use_tz)
@register.tag("timezone")
def timezone_tag(parser, token):
"""
Enable a given time zone just for this block.
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
time zone name, or ``None``. If it is ``None``, the default time zone is
used within the block.
Sample usage::
{% timezone "Europe/Paris" %}
It is {{ now }} in Paris.
{% endtimezone %}
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' takes one argument (timezone)" % bits[0])
tz = parser.compile_filter(bits[1])
nodelist = parser.parse(("endtimezone",))
parser.delete_first_token()
return TimezoneNode(nodelist, tz)
@register.tag("get_current_timezone")
def get_current_timezone_tag(parser, token):
"""
Store the name of the current time zone in the context.
Usage::
{% get_current_timezone as TIME_ZONE %}
This will fetch the currently active time zone and put its name
into the ``TIME_ZONE`` context variable.
"""
# token.split_contents() isn't useful here because this tag doesn't accept
# variable as arguments.
args = token.contents.split()
if len(args) != 3 or args[1] != "as":
raise TemplateSyntaxError(
"'get_current_timezone' requires 'as variable' (got %r)" % args
)
return GetCurrentTimezoneNode(args[2])
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/templatetags/i18n.py | django/templatetags/i18n.py | from decimal import Decimal
from django.conf import settings
from django.template import Library, Node, TemplateSyntaxError, Variable
from django.template.base import TokenType, render_value_in_context
from django.template.defaulttags import token_kwargs
from django.utils import translation
from django.utils.safestring import SafeData, SafeString, mark_safe
register = Library()
class GetAvailableLanguagesNode(Node):
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = [
(k, translation.gettext(v)) for k, v in settings.LANGUAGES
]
return ""
class GetLanguageInfoNode(Node):
def __init__(self, lang_code, variable):
self.lang_code = lang_code
self.variable = variable
def render(self, context):
lang_code = self.lang_code.resolve(context)
context[self.variable] = translation.get_language_info(lang_code)
return ""
class GetLanguageInfoListNode(Node):
def __init__(self, languages, variable):
self.languages = languages
self.variable = variable
def get_language_info(self, language):
# ``language`` is either a language code string or a sequence
# with the language code as its first item
if len(language[0]) > 1:
return translation.get_language_info(language[0])
else:
return translation.get_language_info(str(language))
def render(self, context):
langs = self.languages.resolve(context)
context[self.variable] = [self.get_language_info(lang) for lang in langs]
return ""
class GetCurrentLanguageNode(Node):
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = translation.get_language()
return ""
class GetCurrentLanguageBidiNode(Node):
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = translation.get_language_bidi()
return ""
class TranslateNode(Node):
child_nodelists = ()
def __init__(self, filter_expression, noop, asvar=None, message_context=None):
self.noop = noop
self.asvar = asvar
self.message_context = message_context
self.filter_expression = filter_expression
if isinstance(self.filter_expression.var, str):
self.filter_expression.is_var = True
self.filter_expression.var = Variable("'%s'" % self.filter_expression.var)
def render(self, context):
self.filter_expression.var.translate = not self.noop
if self.message_context:
self.filter_expression.var.message_context = self.message_context.resolve(
context
)
output = self.filter_expression.resolve(context)
value = render_value_in_context(output, context)
# Restore percent signs. Percent signs in template text are doubled
# so they are not interpreted as string format flags.
is_safe = isinstance(value, SafeData)
value = value.replace("%%", "%")
value = mark_safe(value) if is_safe else value
if self.asvar:
context[self.asvar] = value
return ""
else:
return value
class BlockTranslateNode(Node):
def __init__(
self,
extra_context,
singular,
plural=None,
countervar=None,
counter=None,
message_context=None,
trimmed=False,
asvar=None,
tag_name="blocktranslate",
):
self.extra_context = extra_context
self.singular = singular
self.plural = plural
self.countervar = countervar
self.counter = counter
self.message_context = message_context
self.trimmed = trimmed
self.asvar = asvar
self.tag_name = tag_name
def __repr__(self):
return (
f"<{self.__class__.__qualname__}: "
f"extra_context={self.extra_context!r} "
f"singular={self.singular!r} plural={self.plural!r}>"
)
def render_token_list(self, tokens):
result = []
vars = []
for token in tokens:
if token.token_type == TokenType.TEXT:
result.append(token.contents.replace("%", "%%"))
elif token.token_type == TokenType.VAR:
result.append("%%(%s)s" % token.contents)
vars.append(token.contents)
msg = "".join(result)
if self.trimmed:
msg = translation.trim_whitespace(msg)
return msg, vars
def render(self, context, nested=False):
if self.message_context:
message_context = self.message_context.resolve(context)
else:
message_context = None
# Update() works like a push(), so corresponding context.pop() is at
# the end of function
context.update(
{var: val.resolve(context) for var, val in self.extra_context.items()}
)
singular, vars = self.render_token_list(self.singular)
if self.plural and self.countervar and self.counter:
count = self.counter.resolve(context)
if not isinstance(count, (Decimal, float, int)):
raise TemplateSyntaxError(
"%r argument to %r tag must be a number."
% (self.countervar, self.tag_name)
)
context[self.countervar] = count
plural, plural_vars = self.render_token_list(self.plural)
if message_context:
result = translation.npgettext(message_context, singular, plural, count)
else:
result = translation.ngettext(singular, plural, count)
vars.extend(plural_vars)
else:
if message_context:
result = translation.pgettext(message_context, singular)
else:
result = translation.gettext(singular)
default_value = context.template.engine.string_if_invalid
def render_value(key):
if key in context:
val = context[key]
else:
val = default_value % key if "%s" in default_value else default_value
return render_value_in_context(val, context)
data = {v: render_value(v) for v in vars}
context.pop()
try:
result %= data
except (KeyError, ValueError):
if nested:
# Either string is malformed, or it's a bug
raise TemplateSyntaxError(
"%r is unable to format string returned by gettext: %r "
"using %r" % (self.tag_name, result, data)
)
with translation.override(None):
result = self.render(context, nested=True)
if self.asvar:
context[self.asvar] = SafeString(result)
return ""
else:
return result
class LanguageNode(Node):
def __init__(self, nodelist, language):
self.nodelist = nodelist
self.language = language
def render(self, context):
with translation.override(self.language.resolve(context)):
output = self.nodelist.render(context)
return output
@register.tag("get_available_languages")
def do_get_available_languages(parser, token):
"""
Store a list of available languages in the context.
Usage::
{% get_available_languages as languages %}
{% for language in languages %}
...
{% endfor %}
This puts settings.LANGUAGES into the named variable.
"""
# token.split_contents() isn't useful here because this tag doesn't accept
# variable as arguments.
args = token.contents.split()
if len(args) != 3 or args[1] != "as":
raise TemplateSyntaxError(
"'get_available_languages' requires 'as variable' (got %r)" % args
)
return GetAvailableLanguagesNode(args[2])
@register.tag("get_language_info")
def do_get_language_info(parser, token):
"""
Store the language information dictionary for the given language code in a
context variable.
Usage::
{% get_language_info for LANGUAGE_CODE as l %}
{{ l.code }}
{{ l.name }}
{{ l.name_translated }}
{{ l.name_local }}
{{ l.bidi|yesno:"bi-directional,uni-directional" }}
"""
args = token.split_contents()
if len(args) != 5 or args[1] != "for" or args[3] != "as":
raise TemplateSyntaxError(
"'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])
)
return GetLanguageInfoNode(parser.compile_filter(args[2]), args[4])
@register.tag("get_language_info_list")
def do_get_language_info_list(parser, token):
"""
Store a list of language information dictionaries for the given language
codes in a context variable. The language codes can be specified either as
a list of strings or a settings.LANGUAGES style list (or any sequence of
sequences whose first items are language codes).
Usage::
{% get_language_info_list for LANGUAGES as langs %}
{% for l in langs %}
{{ l.code }}
{{ l.name }}
{{ l.name_translated }}
{{ l.name_local }}
{{ l.bidi|yesno:"bi-directional,uni-directional" }}
{% endfor %}
"""
args = token.split_contents()
if len(args) != 5 or args[1] != "for" or args[3] != "as":
raise TemplateSyntaxError(
"'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:])
)
return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4])
@register.filter
def language_name(lang_code):
return translation.get_language_info(lang_code)["name"]
@register.filter
def language_name_translated(lang_code):
english_name = translation.get_language_info(lang_code)["name"]
return translation.gettext(english_name)
@register.filter
def language_name_local(lang_code):
return translation.get_language_info(lang_code)["name_local"]
@register.filter
def language_bidi(lang_code):
return translation.get_language_info(lang_code)["bidi"]
@register.tag("get_current_language")
def do_get_current_language(parser, token):
"""
Store the current language in the context.
Usage::
{% get_current_language as language %}
This fetches the currently active language and puts its value into the
``language`` context variable.
"""
# token.split_contents() isn't useful here because this tag doesn't accept
# variable as arguments.
args = token.contents.split()
if len(args) != 3 or args[1] != "as":
raise TemplateSyntaxError(
"'get_current_language' requires 'as variable' (got %r)" % args
)
return GetCurrentLanguageNode(args[2])
@register.tag("get_current_language_bidi")
def do_get_current_language_bidi(parser, token):
"""
Store the current language layout in the context.
Usage::
{% get_current_language_bidi as bidi %}
This fetches the currently active language's layout and puts its value into
the ``bidi`` context variable. True indicates right-to-left layout,
otherwise left-to-right.
"""
# token.split_contents() isn't useful here because this tag doesn't accept
# variable as arguments.
args = token.contents.split()
if len(args) != 3 or args[1] != "as":
raise TemplateSyntaxError(
"'get_current_language_bidi' requires 'as variable' (got %r)" % args
)
return GetCurrentLanguageBidiNode(args[2])
@register.tag("translate")
@register.tag("trans")
def do_translate(parser, token):
"""
Mark a string for translation and translate the string for the current
language.
Usage::
{% translate "this is a test" %}
This marks the string for translation so it will be pulled out by
makemessages into the .po files and runs the string through the translation
engine.
There is a second form::
{% translate "this is a test" noop %}
This marks the string for translation, but returns the string unchanged.
Use it when you need to store values into forms that should be translated
later on.
You can use variables instead of constant strings
to translate stuff you marked somewhere else::
{% translate variable %}
This tries to translate the contents of the variable ``variable``. Make
sure that the string in there is something that is in the .po file.
It is possible to store the translated string into a variable::
{% translate "this is a test" as var %}
{{ var }}
Contextual translations are also supported::
{% translate "this is a test" context "greeting" %}
This is equivalent to calling pgettext instead of (u)gettext.
"""
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0])
message_string = parser.compile_filter(bits[1])
remaining = bits[2:]
noop = False
asvar = None
message_context = None
seen = set()
invalid_context = {"as", "noop"}
while remaining:
option = remaining.pop(0)
if option in seen:
raise TemplateSyntaxError(
"The '%s' option was specified more than once." % option,
)
elif option == "noop":
noop = True
elif option == "context":
try:
value = remaining.pop(0)
except IndexError:
raise TemplateSyntaxError(
"No argument provided to the '%s' tag for the context option."
% bits[0]
)
if value in invalid_context:
raise TemplateSyntaxError(
"Invalid argument '%s' provided to the '%s' tag for the context "
"option" % (value, bits[0]),
)
message_context = parser.compile_filter(value)
elif option == "as":
try:
value = remaining.pop(0)
except IndexError:
raise TemplateSyntaxError(
"No argument provided to the '%s' tag for the as option." % bits[0]
)
asvar = value
else:
raise TemplateSyntaxError(
"Unknown argument for '%s' tag: '%s'. The only options "
"available are 'noop', 'context' \"xxx\", and 'as VAR'."
% (
bits[0],
option,
)
)
seen.add(option)
return TranslateNode(message_string, noop, asvar, message_context)
@register.tag("blocktranslate")
@register.tag("blocktrans")
def do_block_translate(parser, token):
"""
Translate a block of text with parameters.
Usage::
{% blocktranslate with bar=foo|filter boo=baz|filter %}
This is {{ bar }} and {{ boo }}.
{% endblocktranslate %}
Additionally, this supports pluralization::
{% blocktranslate count count=var|length %}
There is {{ count }} object.
{% plural %}
There are {{ count }} objects.
{% endblocktranslate %}
This is much like ngettext, only in template syntax.
The "var as value" legacy format is still supported::
{% blocktranslate with foo|filter as bar and baz|filter as boo %}
{% blocktranslate count var|length as count %}
The translated string can be stored in a variable using `asvar`::
{% blocktranslate with bar=foo|filter boo=baz|filter asvar var %}
This is {{ bar }} and {{ boo }}.
{% endblocktranslate %}
{{ var }}
Contextual translations are supported::
{% blocktranslate with bar=foo|filter context "greeting" %}
This is {{ bar }}.
{% endblocktranslate %}
This is equivalent to calling pgettext/npgettext instead of
(u)gettext/(u)ngettext.
"""
bits = token.split_contents()
options = {}
remaining_bits = bits[1:]
asvar = None
while remaining_bits:
option = remaining_bits.pop(0)
if option in options:
raise TemplateSyntaxError(
"The %r option was specified more than once." % option
)
if option == "with":
value = token_kwargs(remaining_bits, parser, support_legacy=True)
if not value:
raise TemplateSyntaxError(
'"with" in %r tag needs at least one keyword argument.' % bits[0]
)
elif option == "count":
value = token_kwargs(remaining_bits, parser, support_legacy=True)
if len(value) != 1:
raise TemplateSyntaxError(
'"count" in %r tag expected exactly '
"one keyword argument." % bits[0]
)
elif option == "context":
try:
value = remaining_bits.pop(0)
value = parser.compile_filter(value)
except Exception:
raise TemplateSyntaxError(
'"context" in %r tag expected exactly one argument.' % bits[0]
)
elif option == "trimmed":
value = True
elif option == "asvar":
try:
value = remaining_bits.pop(0)
except IndexError:
raise TemplateSyntaxError(
"No argument provided to the '%s' tag for the asvar option."
% bits[0]
)
asvar = value
else:
raise TemplateSyntaxError(
"Unknown argument for %r tag: %r." % (bits[0], option)
)
options[option] = value
if "count" in options:
countervar, counter = next(iter(options["count"].items()))
else:
countervar, counter = None, None
if "context" in options:
message_context = options["context"]
else:
message_context = None
extra_context = options.get("with", {})
trimmed = options.get("trimmed", False)
singular = []
plural = []
while parser.tokens:
token = parser.next_token()
if token.token_type in (TokenType.VAR, TokenType.TEXT):
singular.append(token)
else:
break
if countervar and counter:
if token.contents.strip() != "plural":
raise TemplateSyntaxError(
"%r doesn't allow other block tags inside it" % bits[0]
)
while parser.tokens:
token = parser.next_token()
if token.token_type in (TokenType.VAR, TokenType.TEXT):
plural.append(token)
else:
break
end_tag_name = "end%s" % bits[0]
if token.contents.strip() != end_tag_name:
raise TemplateSyntaxError(
"%r doesn't allow other block tags (seen %r) inside it"
% (bits[0], token.contents)
)
return BlockTranslateNode(
extra_context,
singular,
plural,
countervar,
counter,
message_context,
trimmed=trimmed,
asvar=asvar,
tag_name=bits[0],
)
@register.tag
def language(parser, token):
"""
Enable the given language just for this block.
Usage::
{% language "de" %}
This is {{ bar }} and {{ boo }}.
{% endlanguage %}
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0])
language = parser.compile_filter(bits[1])
nodelist = parser.parse(("endlanguage",))
parser.delete_first_token()
return LanguageNode(nodelist, language)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/templatetags/l10n.py | django/templatetags/l10n.py | from django.template import Library, Node, TemplateSyntaxError
from django.utils import formats
register = Library()
@register.filter(is_safe=False)
def localize(value):
"""
Force a value to be rendered as a localized value.
"""
return str(formats.localize(value, use_l10n=True))
@register.filter(is_safe=False)
def unlocalize(value):
"""
Force a value to be rendered as a non-localized value.
"""
return str(formats.localize(value, use_l10n=False))
class LocalizeNode(Node):
def __init__(self, nodelist, use_l10n):
self.nodelist = nodelist
self.use_l10n = use_l10n
def __repr__(self):
return "<%s>" % self.__class__.__name__
def render(self, context):
old_setting = context.use_l10n
context.use_l10n = self.use_l10n
output = self.nodelist.render(context)
context.use_l10n = old_setting
return output
@register.tag("localize")
def localize_tag(parser, token):
"""
Force or prevents localization of values.
Sample usage::
{% localize off %}
var pi = {{ 3.1415 }};
{% endlocalize %}
"""
use_l10n = None
bits = list(token.split_contents())
if len(bits) == 1:
use_l10n = True
elif len(bits) > 2 or bits[1] not in ("on", "off"):
raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0])
else:
use_l10n = bits[1] == "on"
nodelist = parser.parse(("endlocalize",))
parser.delete_first_token()
return LocalizeNode(nodelist, use_l10n)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/templatetags/__init__.py | django/templatetags/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/templatetags/static.py | django/templatetags/static.py | from urllib.parse import quote, urljoin
from django import template
from django.apps import apps
from django.utils.encoding import iri_to_uri
from django.utils.html import conditional_escape
register = template.Library()
class PrefixNode(template.Node):
def __repr__(self):
return "<PrefixNode for %r>" % self.name
def __init__(self, varname=None, name=None):
if name is None:
raise template.TemplateSyntaxError(
"Prefix nodes must be given a name to return."
)
self.varname = varname
self.name = name
@classmethod
def handle_token(cls, parser, token, name):
"""
Class method to parse prefix node and return a Node.
"""
# token.split_contents() isn't useful here because tags using this
# method don't accept variable as arguments.
tokens = token.contents.split()
if len(tokens) > 1 and tokens[1] != "as":
raise template.TemplateSyntaxError(
"First argument in '%s' must be 'as'" % tokens[0]
)
if len(tokens) > 1:
varname = tokens[2]
else:
varname = None
return cls(varname, name)
@classmethod
def handle_simple(cls, name):
try:
from django.conf import settings
except ImportError:
prefix = ""
else:
prefix = iri_to_uri(getattr(settings, name, ""))
return prefix
def render(self, context):
prefix = self.handle_simple(self.name)
if self.varname is None:
return prefix
context[self.varname] = prefix
return ""
@register.tag
def get_static_prefix(parser, token):
"""
Populate a template variable with the static prefix,
``settings.STATIC_URL``.
Usage::
{% get_static_prefix [as varname] %}
Examples::
{% get_static_prefix %}
{% get_static_prefix as static_prefix %}
"""
return PrefixNode.handle_token(parser, token, "STATIC_URL")
@register.tag
def get_media_prefix(parser, token):
"""
Populate a template variable with the media prefix,
``settings.MEDIA_URL``.
Usage::
{% get_media_prefix [as varname] %}
Examples::
{% get_media_prefix %}
{% get_media_prefix as media_prefix %}
"""
return PrefixNode.handle_token(parser, token, "MEDIA_URL")
class StaticNode(template.Node):
child_nodelists = ()
def __init__(self, varname=None, path=None):
if path is None:
raise template.TemplateSyntaxError(
"Static template nodes must be given a path to return."
)
self.path = path
self.varname = varname
def __repr__(self):
return (
f"{self.__class__.__name__}(varname={self.varname!r}, path={self.path!r})"
)
def url(self, context):
path = self.path.resolve(context)
return self.handle_simple(path)
def render(self, context):
url = self.url(context)
if context.autoescape:
url = conditional_escape(url)
if self.varname is None:
return url
context[self.varname] = url
return ""
@classmethod
def handle_simple(cls, path):
if apps.is_installed("django.contrib.staticfiles"):
from django.contrib.staticfiles.storage import staticfiles_storage
return staticfiles_storage.url(path)
else:
return urljoin(PrefixNode.handle_simple("STATIC_URL"), quote(path))
@classmethod
def handle_token(cls, parser, token):
"""
Class method to parse prefix node and return a Node.
"""
bits = token.split_contents()
if len(bits) < 2:
raise template.TemplateSyntaxError(
"'%s' takes at least one argument (path to file)" % bits[0]
)
path = parser.compile_filter(bits[1])
if len(bits) >= 2 and bits[-2] == "as":
varname = bits[3]
else:
varname = None
return cls(varname, path)
@register.tag("static")
def do_static(parser, token):
"""
Join the given path with the STATIC_URL setting.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% static variable_with_path as varname %}
"""
return StaticNode.handle_token(parser, token)
def static(path):
"""
Given a relative path to a static asset, return the absolute path to the
asset.
"""
return StaticNode.handle_simple(path)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/templatetags/cache.py | django/templatetags/cache.py | from django.core.cache import InvalidCacheBackendError, caches
from django.core.cache.utils import make_template_fragment_key
from django.template import Library, Node, TemplateSyntaxError, VariableDoesNotExist
register = Library()
class CacheNode(Node):
def __init__(self, nodelist, expire_time_var, fragment_name, vary_on, cache_name):
self.nodelist = nodelist
self.expire_time_var = expire_time_var
self.fragment_name = fragment_name
self.vary_on = vary_on
self.cache_name = cache_name
def render(self, context):
try:
expire_time = self.expire_time_var.resolve(context)
except VariableDoesNotExist:
raise TemplateSyntaxError(
'"cache" tag got an unknown variable: %r' % self.expire_time_var.var
)
if expire_time is not None:
try:
expire_time = int(expire_time)
except (ValueError, TypeError):
raise TemplateSyntaxError(
'"cache" tag got a non-integer timeout value: %r' % expire_time
)
if self.cache_name:
try:
cache_name = self.cache_name.resolve(context)
except VariableDoesNotExist:
raise TemplateSyntaxError(
'"cache" tag got an unknown variable: %r' % self.cache_name.var
)
try:
fragment_cache = caches[cache_name]
except InvalidCacheBackendError:
raise TemplateSyntaxError(
"Invalid cache name specified for cache tag: %r" % cache_name
)
else:
try:
fragment_cache = caches["template_fragments"]
except InvalidCacheBackendError:
fragment_cache = caches["default"]
vary_on = [var.resolve(context) for var in self.vary_on]
cache_key = make_template_fragment_key(self.fragment_name, vary_on)
value = fragment_cache.get(cache_key)
if value is None:
value = self.nodelist.render(context)
fragment_cache.set(cache_key, value, expire_time)
return value
@register.tag("cache")
def do_cache(parser, token):
"""
This will cache the contents of a template fragment for a given amount
of time.
Usage::
{% load cache %}
{% cache [expire_time] [fragment_name] %}
.. some expensive processing ..
{% endcache %}
This tag also supports varying by a list of arguments::
{% load cache %}
{% cache [expire_time] [fragment_name] [var1] [var2] .. %}
.. some expensive processing ..
{% endcache %}
Optionally the cache to use may be specified thus::
{% cache .... using="cachename" %}
Each unique set of arguments will result in a unique cache entry.
"""
nodelist = parser.parse(("endcache",))
parser.delete_first_token()
tokens = token.split_contents()
if len(tokens) < 3:
raise TemplateSyntaxError("'%r' tag requires at least 2 arguments." % tokens[0])
if len(tokens) > 3 and tokens[-1].startswith("using="):
cache_name = parser.compile_filter(tokens[-1].removeprefix("using="))
tokens = tokens[:-1]
else:
cache_name = None
return CacheNode(
nodelist,
parser.compile_filter(tokens[1]),
tokens[2], # fragment_name can't be a variable.
[parser.compile_filter(t) for t in tokens[3:]],
cache_name,
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/apps/registry.py | django/apps/registry.py | import functools
import sys
import threading
import warnings
from collections import Counter, defaultdict
from functools import partial
from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
from .config import AppConfig
class Apps:
"""
A registry that stores the configuration of installed applications.
It also keeps track of models, e.g. to provide reverse relations.
"""
def __init__(self, installed_apps=()):
# installed_apps is set to None when creating the main registry
# because it cannot be populated at that point. Other registries must
# provide a list of installed apps and are populated immediately.
if installed_apps is None and hasattr(sys.modules[__name__], "apps"):
raise RuntimeError("You must supply an installed_apps argument.")
# Mapping of app labels => model names => model classes. Every time a
# model is imported, ModelBase.__new__ calls apps.register_model which
# creates an entry in all_models. All imported models are registered,
# regardless of whether they're defined in an installed application
# and whether the registry has been populated. Since it isn't possible
# to reimport a module safely (it could reexecute initialization code)
# all_models is never overridden or reset.
self.all_models = defaultdict(dict)
# Mapping of labels to AppConfig instances for installed apps.
self.app_configs = {}
# Stack of app_configs. Used to store the current state in
# set_available_apps and set_installed_apps.
self.stored_app_configs = []
# Whether the registry is populated.
self.apps_ready = self.models_ready = self.ready = False
# For the autoreloader.
self.ready_event = threading.Event()
# Lock for thread-safe population.
self._lock = threading.RLock()
self.loading = False
# Maps ("app_label", "modelname") tuples to lists of functions to be
# called when the corresponding model is ready. Used by this class's
# `lazy_model_operation()` and `do_pending_operations()` methods.
self._pending_operations = defaultdict(list)
# Populate apps and models, unless it's the main registry.
if installed_apps is not None:
self.populate(installed_apps)
def populate(self, installed_apps=None):
"""
Load application configurations and models.
Import each application module and then each model module.
It is thread-safe and idempotent, but not reentrant.
"""
if self.ready:
return
# populate() might be called by two threads in parallel on servers
# that create threads before initializing the WSGI callable.
with self._lock:
if self.ready:
return
# An RLock prevents other threads from entering this section. The
# compare and set operation below is atomic.
if self.loading:
# Prevent reentrant calls to avoid running AppConfig.ready()
# methods twice.
raise RuntimeError("populate() isn't reentrant")
self.loading = True
# Phase 1: initialize app configs and import app modules.
for entry in installed_apps:
if isinstance(entry, AppConfig):
app_config = entry
else:
app_config = AppConfig.create(entry)
if app_config.label in self.app_configs:
raise ImproperlyConfigured(
"Application labels aren't unique, "
"duplicates: %s" % app_config.label
)
self.app_configs[app_config.label] = app_config
app_config.apps = self
# Check for duplicate app names.
counts = Counter(
app_config.name for app_config in self.app_configs.values()
)
duplicates = [name for name, count in counts.most_common() if count > 1]
if duplicates:
raise ImproperlyConfigured(
"Application names aren't unique, "
"duplicates: %s" % ", ".join(duplicates)
)
self.apps_ready = True
# Phase 2: import models modules.
for app_config in self.app_configs.values():
app_config.import_models()
self.clear_cache()
self.models_ready = True
# Phase 3: run ready() methods of app configs.
for app_config in self.get_app_configs():
app_config.ready()
self.ready = True
self.ready_event.set()
def check_apps_ready(self):
"""Raise an exception if all apps haven't been imported yet."""
if not self.apps_ready:
from django.conf import settings
# If "not ready" is due to unconfigured settings, accessing
# INSTALLED_APPS raises a more helpful ImproperlyConfigured
# exception.
settings.INSTALLED_APPS
raise AppRegistryNotReady("Apps aren't loaded yet.")
def check_models_ready(self):
"""Raise an exception if all models haven't been imported yet."""
if not self.models_ready:
raise AppRegistryNotReady("Models aren't loaded yet.")
def get_app_configs(self):
"""Import applications and return an iterable of app configs."""
self.check_apps_ready()
return self.app_configs.values()
def get_app_config(self, app_label):
"""
Import applications and returns an app config for the given label.
Raise LookupError if no application exists with this label.
"""
self.check_apps_ready()
try:
return self.app_configs[app_label]
except KeyError:
message = "No installed app with label '%s'." % app_label
for app_config in self.get_app_configs():
if app_config.name == app_label:
message += " Did you mean '%s'?" % app_config.label
break
raise LookupError(message)
# This method is performance-critical at least for Django's test suite.
@functools.cache
def get_models(self, include_auto_created=False, include_swapped=False):
"""
Return a list of all installed models.
By default, the following models aren't included:
- auto-created models for many-to-many relations without
an explicit intermediate table,
- models that have been swapped out.
Set the corresponding keyword argument to True to include such models.
"""
self.check_models_ready()
result = []
for app_config in self.app_configs.values():
result.extend(app_config.get_models(include_auto_created, include_swapped))
return result
def get_model(self, app_label, model_name=None, require_ready=True):
"""
Return the model matching the given app_label and model_name.
As a shortcut, app_label may be in the form <app_label>.<model_name>.
model_name is case-insensitive.
Raise LookupError if no application exists with this label, or no
model exists with this name in the application. Raise ValueError if
called with a single argument that doesn't contain exactly one dot.
"""
if require_ready:
self.check_models_ready()
else:
self.check_apps_ready()
if model_name is None:
app_label, model_name = app_label.split(".")
app_config = self.get_app_config(app_label)
if not require_ready and app_config.models is None:
app_config.import_models()
return app_config.get_model(model_name, require_ready=require_ready)
def register_model(self, app_label, model):
# Since this method is called when models are imported, it cannot
# perform imports because of the risk of import loops. It mustn't
# call get_app_config().
model_name = model._meta.model_name
app_models = self.all_models[app_label]
if model_name in app_models:
if (
model.__name__ == app_models[model_name].__name__
and model.__module__ == app_models[model_name].__module__
):
warnings.warn(
"Model '%s.%s' was already registered. Reloading models is not "
"advised as it can lead to inconsistencies, most notably with "
"related models." % (app_label, model_name),
RuntimeWarning,
stacklevel=2,
)
else:
raise RuntimeError(
"Conflicting '%s' models in application '%s': %s and %s."
% (model_name, app_label, app_models[model_name], model)
)
app_models[model_name] = model
self.do_pending_operations(model)
self.clear_cache()
def is_installed(self, app_name):
"""
Check whether an application with this name exists in the registry.
app_name is the full name of the app e.g. 'django.contrib.admin'.
"""
self.check_apps_ready()
return any(ac.name == app_name for ac in self.app_configs.values())
def get_containing_app_config(self, object_name):
"""
Look for an app config containing a given object.
object_name is the dotted Python path to the object.
Return the app config for the inner application in case of nesting.
Return None if the object isn't in any registered app config.
"""
self.check_apps_ready()
candidates = []
for app_config in self.app_configs.values():
if object_name.startswith(app_config.name):
subpath = object_name.removeprefix(app_config.name)
if subpath == "" or subpath[0] == ".":
candidates.append(app_config)
if candidates:
return sorted(candidates, key=lambda ac: -len(ac.name))[0]
def get_registered_model(self, app_label, model_name):
"""
Similar to get_model(), but doesn't require that an app exists with
the given app_label.
It's safe to call this method at import time, even while the registry
is being populated.
"""
model = self.all_models[app_label].get(model_name.lower())
if model is None:
raise LookupError("Model '%s.%s' not registered." % (app_label, model_name))
return model
@functools.cache
def get_swappable_settings_name(self, to_string):
"""
For a given model string (e.g. "auth.User"), return the name of the
corresponding settings name if it refers to a swappable model. If the
referred model is not swappable, return None.
This method is decorated with @functools.cache because it's performance
critical when it comes to migrations. Since the swappable settings
don't change after Django has loaded the settings, there is no reason
to get the respective settings attribute over and over again.
"""
to_string = to_string.lower()
for model in self.get_models(include_swapped=True):
swapped = model._meta.swapped
# Is this model swapped out for the model given by to_string?
if swapped and swapped.lower() == to_string:
return model._meta.swappable
# Is this model swappable and the one given by to_string?
if model._meta.swappable and model._meta.label_lower == to_string:
return model._meta.swappable
return None
def set_available_apps(self, available):
"""
Restrict the set of installed apps used by get_app_config[s].
available must be an iterable of application names.
set_available_apps() must be balanced with unset_available_apps().
Primarily used for performance optimization in TransactionTestCase.
This method is safe in the sense that it doesn't trigger any imports.
"""
available = set(available)
installed = {app_config.name for app_config in self.get_app_configs()}
if not available.issubset(installed):
raise ValueError(
"Available apps isn't a subset of installed apps, extra apps: %s"
% ", ".join(available - installed)
)
self.stored_app_configs.append(self.app_configs)
self.app_configs = {
label: app_config
for label, app_config in self.app_configs.items()
if app_config.name in available
}
self.clear_cache()
def unset_available_apps(self):
"""Cancel a previous call to set_available_apps()."""
self.app_configs = self.stored_app_configs.pop()
self.clear_cache()
def set_installed_apps(self, installed):
"""
Enable a different set of installed apps for get_app_config[s].
installed must be an iterable in the same format as INSTALLED_APPS.
set_installed_apps() must be balanced with unset_installed_apps(),
even if it exits with an exception.
Primarily used as a receiver of the setting_changed signal in tests.
This method may trigger new imports, which may add new models to the
registry of all imported models. They will stay in the registry even
after unset_installed_apps(). Since it isn't possible to replay
imports safely (e.g. that could lead to registering listeners twice),
models are registered when they're imported and never removed.
"""
if not self.ready:
raise AppRegistryNotReady("App registry isn't ready yet.")
self.stored_app_configs.append(self.app_configs)
self.app_configs = {}
self.apps_ready = self.models_ready = self.loading = self.ready = False
self.clear_cache()
self.populate(installed)
def unset_installed_apps(self):
"""Cancel a previous call to set_installed_apps()."""
self.app_configs = self.stored_app_configs.pop()
self.apps_ready = self.models_ready = self.ready = True
self.clear_cache()
def clear_cache(self):
"""
Clear all internal caches, for methods that alter the app registry.
This is mostly used in tests.
"""
self.get_swappable_settings_name.cache_clear()
# Call expire cache on each model. This will purge
# the relation tree and the fields cache.
self.get_models.cache_clear()
if self.ready:
# Circumvent self.get_models() to prevent that the cache is
# refilled. This particularly prevents that an empty value is
# cached while cloning.
for app_config in self.app_configs.values():
for model in app_config.get_models(include_auto_created=True):
model._meta._expire_cache()
def lazy_model_operation(self, function, *model_keys):
"""
Take a function and a number of ("app_label", "modelname") tuples, and
when all the corresponding models have been imported and registered,
call the function with the model classes as its arguments.
The function passed to this method must accept exactly n models as
arguments, where n=len(model_keys).
"""
# Base case: no arguments, just execute the function.
if not model_keys:
function()
# Recursive case: take the head of model_keys, wait for the
# corresponding model class to be imported and registered, then apply
# that argument to the supplied function. Pass the resulting partial
# to lazy_model_operation() along with the remaining model args and
# repeat until all models are loaded and all arguments are applied.
else:
next_model, *more_models = model_keys
# This will be executed after the class corresponding to next_model
# has been imported and registered. The `func` attribute provides
# duck-type compatibility with partials.
def apply_next_model(model):
next_function = partial(apply_next_model.func, model)
self.lazy_model_operation(next_function, *more_models)
apply_next_model.func = function
# If the model has already been imported and registered, partially
# apply it to the function now. If not, add it to the list of
# pending operations for the model, where it will be executed with
# the model class as its sole argument once the model is ready.
try:
model_class = self.get_registered_model(*next_model)
except LookupError:
self._pending_operations[next_model].append(apply_next_model)
else:
apply_next_model(model_class)
def do_pending_operations(self, model):
"""
Take a newly-prepared model and pass it to each function waiting for
it. This is called at the very end of Apps.register_model().
"""
key = model._meta.app_label, model._meta.model_name
for function in self._pending_operations.pop(key, []):
function(model)
apps = Apps(installed_apps=None)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/apps/config.py | django/apps/config.py | import inspect
import os
from importlib import import_module
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import cached_property
from django.utils.module_loading import import_string, module_has_submodule
APPS_MODULE_NAME = "apps"
MODELS_MODULE_NAME = "models"
class AppConfig:
"""Class representing a Django application and its configuration."""
def __init__(self, app_name, app_module):
# Full Python path to the application e.g. 'django.contrib.admin'.
self.name = app_name
# Root module for the application e.g. <module 'django.contrib.admin'
# from 'django/contrib/admin/__init__.py'>.
self.module = app_module
# Reference to the Apps registry that holds this AppConfig. Set by the
# registry when it registers the AppConfig instance.
self.apps = None
# The following attributes could be defined at the class level in a
# subclass, hence the test-and-set pattern.
# Last component of the Python path to the application e.g. 'admin'.
# This value must be unique across a Django project.
if not hasattr(self, "label"):
self.label = app_name.rpartition(".")[2]
if not self.label.isidentifier():
raise ImproperlyConfigured(
"The app label '%s' is not a valid Python identifier." % self.label
)
# Human-readable name for the application e.g. "Admin".
if not hasattr(self, "verbose_name"):
self.verbose_name = self.label.title()
# Filesystem path to the application directory e.g.
# '/path/to/django/contrib/admin'.
if not hasattr(self, "path"):
self.path = self._path_from_module(app_module)
# Module containing models e.g. <module 'django.contrib.admin.models'
# from 'django/contrib/admin/models.py'>. Set by import_models().
# None if the application doesn't have a models module.
self.models_module = None
# Mapping of lowercase model names to model classes. Initially set to
# None to prevent accidental access before import_models() runs.
self.models = None
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self.label)
@cached_property
def default_auto_field(self):
from django.conf import settings
return settings.DEFAULT_AUTO_FIELD
@property
def _is_default_auto_field_overridden(self):
return self.__class__.default_auto_field is not AppConfig.default_auto_field
def _path_from_module(self, module):
"""Attempt to determine app's filesystem path from its module."""
# See #21874 for extended discussion of the behavior of this method in
# various cases.
# Convert to list because __path__ may not support indexing.
paths = list(getattr(module, "__path__", []))
if len(paths) != 1:
filename = getattr(module, "__file__", None)
if filename is not None:
paths = [os.path.dirname(filename)]
else:
# For unknown reasons, sometimes the list returned by __path__
# contains duplicates that must be removed (#25246).
paths = list(set(paths))
if len(paths) > 1:
raise ImproperlyConfigured(
"The app module %r has multiple filesystem locations (%r); "
"you must configure this app with an AppConfig subclass "
"with a 'path' class attribute." % (module, paths)
)
elif not paths:
raise ImproperlyConfigured(
"The app module %r has no filesystem location, "
"you must configure this app with an AppConfig subclass "
"with a 'path' class attribute." % module
)
return paths[0]
@classmethod
def create(cls, entry):
"""
Factory that creates an app config from an entry in INSTALLED_APPS.
"""
# create() eventually returns app_config_class(app_name, app_module).
app_config_class = None
app_name = None
app_module = None
# If import_module succeeds, entry points to the app module.
try:
app_module = import_module(entry)
except Exception:
pass
else:
# If app_module has an apps submodule that defines a single
# AppConfig subclass, use it automatically.
# To prevent this, an AppConfig subclass can declare a class
# variable default = False.
# If the apps module defines more than one AppConfig subclass,
# the default one can declare default = True.
if module_has_submodule(app_module, APPS_MODULE_NAME):
mod_path = "%s.%s" % (entry, APPS_MODULE_NAME)
mod = import_module(mod_path)
# Check if there's exactly one AppConfig candidate,
# excluding those that explicitly define default = False.
app_configs = [
(name, candidate)
for name, candidate in inspect.getmembers(mod, inspect.isclass)
if (
issubclass(candidate, cls)
and candidate is not cls
and getattr(candidate, "default", True)
)
]
if len(app_configs) == 1:
app_config_class = app_configs[0][1]
else:
# Check if there's exactly one AppConfig subclass,
# among those that explicitly define default = True.
app_configs = [
(name, candidate)
for name, candidate in app_configs
if getattr(candidate, "default", False)
]
if len(app_configs) > 1:
candidates = [repr(name) for name, _ in app_configs]
raise RuntimeError(
"%r declares more than one default AppConfig: "
"%s." % (mod_path, ", ".join(candidates))
)
elif len(app_configs) == 1:
app_config_class = app_configs[0][1]
# Use the default app config class if we didn't find anything.
if app_config_class is None:
app_config_class = cls
app_name = entry
# If import_string succeeds, entry is an app config class.
if app_config_class is None:
try:
app_config_class = import_string(entry)
except Exception:
pass
# If both import_module and import_string failed, it means that entry
# doesn't have a valid value.
if app_module is None and app_config_class is None:
# If the last component of entry starts with an uppercase letter,
# then it was likely intended to be an app config class; if not,
# an app module. Provide a nice error message in both cases.
mod_path, _, cls_name = entry.rpartition(".")
if mod_path and cls_name[0].isupper():
# We could simply re-trigger the string import exception, but
# we're going the extra mile and providing a better error
# message for typos in INSTALLED_APPS.
# This may raise ImportError, which is the best exception
# possible if the module at mod_path cannot be imported.
mod = import_module(mod_path)
candidates = [
repr(name)
for name, candidate in inspect.getmembers(mod, inspect.isclass)
if issubclass(candidate, cls) and candidate is not cls
]
msg = "Module '%s' does not contain a '%s' class." % (
mod_path,
cls_name,
)
if candidates:
msg += " Choices are: %s." % ", ".join(candidates)
raise ImportError(msg)
else:
# Re-trigger the module import exception.
import_module(entry)
# Check for obvious errors. (This check prevents duck typing, but
# it could be removed if it became a problem in practice.)
if not issubclass(app_config_class, AppConfig):
raise ImproperlyConfigured("'%s' isn't a subclass of AppConfig." % entry)
# Obtain app name here rather than in AppClass.__init__ to keep
# all error checking for entries in INSTALLED_APPS in one place.
if app_name is None:
try:
app_name = app_config_class.name
except AttributeError:
raise ImproperlyConfigured("'%s' must supply a name attribute." % entry)
# Ensure app_name points to a valid module.
try:
app_module = import_module(app_name)
except ImportError:
raise ImproperlyConfigured(
"Cannot import '%s'. Check that '%s.%s.name' is correct."
% (
app_name,
app_config_class.__module__,
app_config_class.__qualname__,
)
)
# Entry is a path to an app config class.
return app_config_class(app_name, app_module)
def get_model(self, model_name, require_ready=True):
"""
Return the model with the given case-insensitive model_name.
Raise LookupError if no model exists with this name.
"""
if require_ready:
self.apps.check_models_ready()
else:
self.apps.check_apps_ready()
try:
return self.models[model_name.lower()]
except KeyError:
raise LookupError(
"App '%s' doesn't have a '%s' model." % (self.label, model_name)
)
def get_models(self, include_auto_created=False, include_swapped=False):
"""
Return an iterable of models.
By default, the following models aren't included:
- auto-created models for many-to-many relations without
an explicit intermediate table,
- models that have been swapped out.
Set the corresponding keyword argument to True to include such models.
Keyword arguments aren't documented; they're a private API.
"""
self.apps.check_models_ready()
for model in self.models.values():
if model._meta.auto_created and not include_auto_created:
continue
if model._meta.swapped and not include_swapped:
continue
yield model
def import_models(self):
# Dictionary of models for this app, primarily maintained in the
# 'all_models' attribute of the Apps this AppConfig is attached to.
self.models = self.apps.all_models[self.label]
if module_has_submodule(self.module, MODELS_MODULE_NAME):
models_module_name = "%s.%s" % (self.name, MODELS_MODULE_NAME)
self.models_module = import_module(models_module_name)
def ready(self):
"""
Override this method in subclasses to run code when Django starts.
"""
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/apps/__init__.py | django/apps/__init__.py | from .config import AppConfig
from .registry import apps
__all__ = ["AppConfig", "apps"]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/__init__.py | django/contrib/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/search.py | django/contrib/postgres/search.py | from django.db.backends.postgresql.psycopg_any import is_psycopg3
from django.db.models import (
CharField,
Expression,
Field,
FloatField,
Func,
Lookup,
TextField,
Value,
)
from django.db.models.expressions import CombinedExpression, register_combinable_fields
from django.db.models.functions import Cast, Coalesce
from django.utils.regex_helper import _lazy_re_compile
from .utils import CheckPostgresInstalledMixin
if is_psycopg3:
from psycopg.adapt import Dumper
class UTF8Dumper(Dumper):
def dump(self, obj):
return bytes(obj, "utf-8")
def quote_lexeme(value):
return UTF8Dumper(str).quote(psql_escape(value)).decode()
else:
from psycopg2.extensions import adapt
def quote_lexeme(value):
adapter = adapt(psql_escape(value))
adapter.encoding = "utf-8"
return adapter.getquoted().decode()
spec_chars_re = _lazy_re_compile(r"['\0\[\]()|&:*!@<>\\]")
multiple_spaces_re = _lazy_re_compile(r"\s{2,}")
def normalize_spaces(val):
"""Convert multiple spaces to single and strip from both sides."""
if not (val := val.strip()):
return None
return multiple_spaces_re.sub(" ", val)
def psql_escape(query):
"""Replace chars not fit for use in search queries with a single space."""
query = spec_chars_re.sub(" ", query)
return normalize_spaces(query)
class SearchVectorExact(Lookup):
lookup_name = "exact"
def process_rhs(self, qn, connection):
if not isinstance(self.rhs, (SearchQuery, CombinedSearchQuery)):
config = getattr(self.lhs, "config", None)
self.rhs = SearchQuery(self.rhs, config=config)
rhs, rhs_params = super().process_rhs(qn, connection)
return rhs, rhs_params
def as_sql(self, qn, connection):
lhs, lhs_params = self.process_lhs(qn, connection)
rhs, rhs_params = self.process_rhs(qn, connection)
params = (*lhs_params, *rhs_params)
return "%s @@ %s" % (lhs, rhs), params
class SearchVectorField(CheckPostgresInstalledMixin, Field):
def db_type(self, connection):
return "tsvector"
class SearchQueryField(CheckPostgresInstalledMixin, Field):
def db_type(self, connection):
return "tsquery"
class _Float4Field(Field):
def db_type(self, connection):
return "float4"
class SearchConfig(Expression):
def __init__(self, config):
super().__init__()
if not hasattr(config, "resolve_expression"):
config = Value(config)
self.config = config
@classmethod
def from_parameter(cls, config):
if config is None or isinstance(config, cls):
return config
return cls(config)
def get_source_expressions(self):
return [self.config]
def set_source_expressions(self, exprs):
(self.config,) = exprs
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.config)
return "%s::regconfig" % sql, params
class SearchVectorCombinable:
ADD = "||"
def _combine(self, other, connector, reversed):
if not isinstance(other, SearchVectorCombinable):
raise TypeError(
"SearchVector can only be combined with other SearchVector "
"instances, got %s." % type(other).__name__
)
if reversed:
return CombinedSearchVector(other, connector, self, self.config)
return CombinedSearchVector(self, connector, other, self.config)
register_combinable_fields(
SearchVectorField, SearchVectorCombinable.ADD, SearchVectorField, SearchVectorField
)
class SearchVector(SearchVectorCombinable, Func):
function = "to_tsvector"
arg_joiner = " || ' ' || "
output_field = SearchVectorField()
def __init__(self, *expressions, config=None, weight=None):
super().__init__(*expressions)
self.config = SearchConfig.from_parameter(config)
if weight is not None and not hasattr(weight, "resolve_expression"):
weight = Value(weight)
self.weight = weight
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
resolved = super().resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
if self.config:
resolved.config = self.config.resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
return resolved
def as_sql(self, compiler, connection, function=None, template=None):
clone = self.copy()
clone.set_source_expressions(
[
Coalesce(
(
expression
if isinstance(expression.output_field, (CharField, TextField))
else Cast(expression, TextField())
),
Value(""),
)
for expression in clone.get_source_expressions()
]
)
config_sql = None
config_params = []
if template is None:
if clone.config:
config_sql, config_params = compiler.compile(clone.config)
template = "%(function)s(%(config)s, %(expressions)s)"
else:
template = clone.template
sql, params = super(SearchVector, clone).as_sql(
compiler,
connection,
function=function,
template=template,
config=config_sql,
)
extra_params = []
if clone.weight:
weight_sql, extra_params = compiler.compile(clone.weight)
sql = "setweight({}, {})".format(sql, weight_sql)
return sql, (*config_params, *params, *extra_params)
class CombinedSearchVector(SearchVectorCombinable, CombinedExpression):
def __init__(self, lhs, connector, rhs, config, output_field=None):
self.config = config
super().__init__(lhs, connector, rhs, output_field)
class SearchQueryCombinable:
BITAND = "&&"
BITOR = "||"
def _combine(self, other, connector, reversed):
if not isinstance(other, SearchQueryCombinable):
raise TypeError(
"SearchQuery can only be combined with other SearchQuery "
"instances, got %s." % type(other).__name__
)
if reversed:
return CombinedSearchQuery(other, connector, self, self.config)
return CombinedSearchQuery(self, connector, other, self.config)
# On Combinable, these are not implemented to reduce confusion with Q. In
# this case we are actually (ab)using them to do logical combination so
# it's consistent with other usage in Django.
def __or__(self, other):
return self._combine(other, self.BITOR, False)
def __ror__(self, other):
return self._combine(other, self.BITOR, True)
def __and__(self, other):
return self._combine(other, self.BITAND, False)
def __rand__(self, other):
return self._combine(other, self.BITAND, True)
class SearchQuery(SearchQueryCombinable, Func):
output_field = SearchQueryField()
SEARCH_TYPES = {
"plain": "plainto_tsquery",
"phrase": "phraseto_tsquery",
"raw": "to_tsquery",
"websearch": "websearch_to_tsquery",
}
def __init__(
self,
value,
output_field=None,
*,
config=None,
invert=False,
search_type="plain",
):
if isinstance(value, LexemeCombinable):
search_type = "raw"
self.function = self.SEARCH_TYPES.get(search_type)
if self.function is None:
raise ValueError("Unknown search_type argument '%s'." % search_type)
if not hasattr(value, "resolve_expression"):
value = Value(value)
expressions = (value,)
self.config = SearchConfig.from_parameter(config)
if self.config is not None:
expressions = [self.config, *expressions]
self.invert = invert
super().__init__(*expressions, output_field=output_field)
def as_sql(self, compiler, connection, function=None, template=None):
sql, params = super().as_sql(compiler, connection, function, template)
if self.invert:
sql = "!!(%s)" % sql
return sql, params
def __invert__(self):
clone = self.copy()
clone.invert = not self.invert
return clone
def __str__(self):
result = super().__str__()
return ("~%s" % result) if self.invert else result
class CombinedSearchQuery(SearchQueryCombinable, CombinedExpression):
def __init__(self, lhs, connector, rhs, config, output_field=None):
self.config = config
super().__init__(lhs, connector, rhs, output_field)
def __str__(self):
return "(%s)" % super().__str__()
class SearchRank(Func):
function = "ts_rank"
output_field = FloatField()
def __init__(
self,
vector,
query,
weights=None,
normalization=None,
cover_density=False,
):
from .fields.array import ArrayField
if not hasattr(vector, "resolve_expression"):
vector = SearchVector(vector)
if not hasattr(query, "resolve_expression"):
query = SearchQuery(query)
expressions = [vector, query]
if weights is not None:
if not hasattr(weights, "resolve_expression"):
weights = Value(weights)
weights = Cast(weights, ArrayField(_Float4Field()))
expressions = [weights, *expressions]
if normalization is not None:
if not hasattr(normalization, "resolve_expression"):
normalization = Value(normalization)
expressions.append(normalization)
if cover_density:
self.function = "ts_rank_cd"
super().__init__(*expressions)
class SearchHeadline(Func):
function = "ts_headline"
template = "%(function)s(%(expressions)s%(options)s)"
output_field = TextField()
def __init__(
self,
expression,
query,
*,
config=None,
start_sel=None,
stop_sel=None,
max_words=None,
min_words=None,
short_word=None,
highlight_all=None,
max_fragments=None,
fragment_delimiter=None,
):
if not hasattr(query, "resolve_expression"):
query = SearchQuery(query)
options = {
"StartSel": start_sel,
"StopSel": stop_sel,
"MaxWords": max_words,
"MinWords": min_words,
"ShortWord": short_word,
"HighlightAll": highlight_all,
"MaxFragments": max_fragments,
"FragmentDelimiter": fragment_delimiter,
}
self.options = {
option: value for option, value in options.items() if value is not None
}
expressions = (expression, query)
if config is not None:
config = SearchConfig.from_parameter(config)
expressions = (config, *expressions)
super().__init__(*expressions)
def as_sql(self, compiler, connection, function=None, template=None):
options_sql = ""
options_params = ()
if self.options:
options_params = (
", ".join(
connection.ops.compose_sql(f"{option}=%s", [value])
for option, value in self.options.items()
),
)
options_sql = ", %s"
sql, params = super().as_sql(
compiler,
connection,
function=function,
template=template,
options=options_sql,
)
return sql, params + options_params
SearchVectorField.register_lookup(SearchVectorExact)
class TrigramBase(Func):
output_field = FloatField()
def __init__(self, expression, string, **extra):
if not hasattr(string, "resolve_expression"):
string = Value(string)
super().__init__(expression, string, **extra)
class TrigramWordBase(Func):
output_field = FloatField()
def __init__(self, string, expression, **extra):
if not hasattr(string, "resolve_expression"):
string = Value(string)
super().__init__(string, expression, **extra)
class TrigramSimilarity(TrigramBase):
function = "SIMILARITY"
class TrigramDistance(TrigramBase):
function = ""
arg_joiner = " <-> "
class TrigramWordDistance(TrigramWordBase):
function = ""
arg_joiner = " <<-> "
class TrigramStrictWordDistance(TrigramWordBase):
function = ""
arg_joiner = " <<<-> "
class TrigramWordSimilarity(TrigramWordBase):
function = "WORD_SIMILARITY"
class TrigramStrictWordSimilarity(TrigramWordBase):
function = "STRICT_WORD_SIMILARITY"
class LexemeCombinable:
BITAND = "&"
BITOR = "|"
def _combine(self, other, connector, reversed):
if not isinstance(other, LexemeCombinable):
raise TypeError(
"A Lexeme can only be combined with another Lexeme, "
f"got {other.__class__.__name__}."
)
if reversed:
return CombinedLexeme(other, connector, self)
return CombinedLexeme(self, connector, other)
# On Combinable, these are not implemented to reduce confusion with Q. In
# this case we are actually (ab)using them to do logical combination so
# it's consistent with other usage in Django.
def __or__(self, other):
return self._combine(other, self.BITOR, False)
def __ror__(self, other):
return self._combine(other, self.BITOR, True)
def __and__(self, other):
return self._combine(other, self.BITAND, False)
def __rand__(self, other):
return self._combine(other, self.BITAND, True)
class Lexeme(LexemeCombinable, Value):
_output_field = SearchQueryField()
def __init__(
self, value, output_field=None, *, invert=False, prefix=False, weight=None
):
if value == "":
raise ValueError("Lexeme value cannot be empty.")
if not isinstance(value, str):
raise TypeError(
f"Lexeme value must be a string, got {value.__class__.__name__}."
)
if weight is not None and (
not isinstance(weight, str) or weight.lower() not in {"a", "b", "c", "d"}
):
raise ValueError(
f"Weight must be one of 'A', 'B', 'C', and 'D', got {weight!r}."
)
self.prefix = prefix
self.invert = invert
self.weight = weight
super().__init__(value, output_field=output_field)
def as_sql(self, compiler, connection):
param = quote_lexeme(self.value)
label = ""
if self.prefix:
label += "*"
if self.weight:
label += self.weight
if label:
param = f"{param}:{label}"
if self.invert:
param = f"!{param}"
return "%s", (param,)
def __invert__(self):
cloned = self.copy()
cloned.invert = not self.invert
return cloned
class CombinedLexeme(LexemeCombinable, CombinedExpression):
_output_field = SearchQueryField()
def as_sql(self, compiler, connection):
value_params = []
lsql, params = compiler.compile(self.lhs)
value_params.extend(params)
rsql, params = compiler.compile(self.rhs)
value_params.extend(params)
combined_sql = f"({lsql} {self.connector} {rsql})"
combined_value = combined_sql % tuple(value_params)
return "%s", (combined_value,)
def __invert__(self):
# Apply De Morgan's theorem.
cloned = self.copy()
cloned.connector = self.BITAND if self.connector == self.BITOR else self.BITOR
cloned.lhs = ~self.lhs
cloned.rhs = ~self.rhs
return cloned
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/lookups.py | django/contrib/postgres/lookups.py | from django.db.models import Transform
from django.db.models.lookups import PostgresOperatorLookup
from django.db.models.sql.query import Query
from .search import SearchVector, SearchVectorExact, SearchVectorField
class DataContains(PostgresOperatorLookup):
lookup_name = "contains"
postgres_operator = "@>"
class ContainedBy(PostgresOperatorLookup):
lookup_name = "contained_by"
postgres_operator = "<@"
class Overlap(PostgresOperatorLookup):
lookup_name = "overlap"
postgres_operator = "&&"
def get_prep_lookup(self):
from .expressions import ArraySubquery
if isinstance(self.rhs, Query):
self.rhs = ArraySubquery(self.rhs)
return super().get_prep_lookup()
class HasKey(PostgresOperatorLookup):
lookup_name = "has_key"
postgres_operator = "?"
prepare_rhs = False
class HasKeys(PostgresOperatorLookup):
lookup_name = "has_keys"
postgres_operator = "?&"
def get_prep_lookup(self):
return [str(item) for item in self.rhs]
class HasAnyKeys(HasKeys):
lookup_name = "has_any_keys"
postgres_operator = "?|"
class Unaccent(Transform):
bilateral = True
lookup_name = "unaccent"
function = "UNACCENT"
class SearchLookup(SearchVectorExact):
lookup_name = "search"
def process_lhs(self, qn, connection):
if not isinstance(self.lhs.output_field, SearchVectorField):
config = getattr(self.rhs, "config", None)
self.lhs = SearchVector(self.lhs, config=config)
lhs, lhs_params = super().process_lhs(qn, connection)
return lhs, lhs_params
class TrigramSimilar(PostgresOperatorLookup):
lookup_name = "trigram_similar"
postgres_operator = "%%"
class TrigramWordSimilar(PostgresOperatorLookup):
lookup_name = "trigram_word_similar"
postgres_operator = "%%>"
class TrigramStrictWordSimilar(PostgresOperatorLookup):
lookup_name = "trigram_strict_word_similar"
postgres_operator = "%%>>"
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/operations.py | django/contrib/postgres/operations.py | from django.contrib.postgres.signals import (
get_citext_oids,
get_hstore_oids,
register_type_handlers,
)
from django.db import NotSupportedError, router
from django.db.migrations import AddConstraint, AddIndex, RemoveIndex
from django.db.migrations.operations.base import Operation, OperationCategory
from django.db.models.constraints import CheckConstraint
class CreateExtension(Operation):
reversible = True
category = OperationCategory.ADDITION
def __init__(self, name, hints=None):
self.name = name
self.hints = hints or {}
def state_forwards(self, app_label, state):
pass
def database_forwards(self, app_label, schema_editor, from_state, to_state):
if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate(
schema_editor.connection.alias, app_label, **self.hints
):
return
if not self.extension_exists(schema_editor, self.name):
schema_editor.execute(
"CREATE EXTENSION IF NOT EXISTS %s"
% schema_editor.quote_name(self.name)
)
# Clear cached, stale oids.
get_hstore_oids.cache_clear()
get_citext_oids.cache_clear()
# Registering new type handlers cannot be done before the extension is
# installed, otherwise a subsequent data migration would use the same
# connection.
register_type_handlers(schema_editor.connection)
if hasattr(schema_editor.connection, "register_geometry_adapters"):
schema_editor.connection.register_geometry_adapters(
schema_editor.connection.connection, True
)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
if not router.allow_migrate(
schema_editor.connection.alias, app_label, **self.hints
):
return
if self.extension_exists(schema_editor, self.name):
schema_editor.execute(
"DROP EXTENSION IF EXISTS %s" % schema_editor.quote_name(self.name)
)
# Clear cached, stale oids.
get_hstore_oids.cache_clear()
get_citext_oids.cache_clear()
def extension_exists(self, schema_editor, extension):
with schema_editor.connection.cursor() as cursor:
cursor.execute(
"SELECT 1 FROM pg_extension WHERE extname = %s",
[extension],
)
return bool(cursor.fetchone())
def describe(self):
return "Creates extension %s" % self.name
@property
def migration_name_fragment(self):
return "create_extension_%s" % self.name
class BloomExtension(CreateExtension):
def __init__(self, hints=None):
super().__init__("bloom", hints=hints)
class BtreeGinExtension(CreateExtension):
def __init__(self, hints=None):
super().__init__("btree_gin", hints=hints)
class BtreeGistExtension(CreateExtension):
def __init__(self, hints=None):
super().__init__("btree_gist", hints=hints)
class CITextExtension(CreateExtension):
def __init__(self, hints=None):
super().__init__("citext", hints=hints)
class CryptoExtension(CreateExtension):
def __init__(self, hints=None):
super().__init__("pgcrypto", hints=hints)
class HStoreExtension(CreateExtension):
def __init__(self, hints=None):
super().__init__("hstore", hints=hints)
class TrigramExtension(CreateExtension):
def __init__(self, hints=None):
super().__init__("pg_trgm", hints=hints)
class UnaccentExtension(CreateExtension):
def __init__(self, hints=None):
super().__init__("unaccent", hints=hints)
class NotInTransactionMixin:
def _ensure_not_in_transaction(self, schema_editor):
if schema_editor.connection.in_atomic_block:
raise NotSupportedError(
"The %s operation cannot be executed inside a transaction "
"(set atomic = False on the migration)." % self.__class__.__name__
)
class AddIndexConcurrently(NotInTransactionMixin, AddIndex):
"""Create an index using PostgreSQL's CREATE INDEX CONCURRENTLY syntax."""
atomic = False
category = OperationCategory.ADDITION
def describe(self):
return "Concurrently create index %s on field(s) %s of model %s" % (
self.index.name,
", ".join(self.index.fields),
self.model_name,
)
def database_forwards(self, app_label, schema_editor, from_state, to_state):
self._ensure_not_in_transaction(schema_editor)
model = to_state.apps.get_model(app_label, self.model_name)
if self.allow_migrate_model(schema_editor.connection.alias, model):
schema_editor.add_index(model, self.index, concurrently=True)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
self._ensure_not_in_transaction(schema_editor)
model = from_state.apps.get_model(app_label, self.model_name)
if self.allow_migrate_model(schema_editor.connection.alias, model):
schema_editor.remove_index(model, self.index, concurrently=True)
class RemoveIndexConcurrently(NotInTransactionMixin, RemoveIndex):
"""Remove an index using PostgreSQL's DROP INDEX CONCURRENTLY syntax."""
atomic = False
category = OperationCategory.REMOVAL
def describe(self):
return "Concurrently remove index %s from %s" % (self.name, self.model_name)
def database_forwards(self, app_label, schema_editor, from_state, to_state):
self._ensure_not_in_transaction(schema_editor)
model = from_state.apps.get_model(app_label, self.model_name)
if self.allow_migrate_model(schema_editor.connection.alias, model):
from_model_state = from_state.models[app_label, self.model_name_lower]
index = from_model_state.get_index_by_name(self.name)
schema_editor.remove_index(model, index, concurrently=True)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
self._ensure_not_in_transaction(schema_editor)
model = to_state.apps.get_model(app_label, self.model_name)
if self.allow_migrate_model(schema_editor.connection.alias, model):
to_model_state = to_state.models[app_label, self.model_name_lower]
index = to_model_state.get_index_by_name(self.name)
schema_editor.add_index(model, index, concurrently=True)
class CollationOperation(Operation):
def __init__(self, name, locale, *, provider="libc", deterministic=True):
self.name = name
self.locale = locale
self.provider = provider
self.deterministic = deterministic
def state_forwards(self, app_label, state):
pass
def deconstruct(self):
kwargs = {"name": self.name, "locale": self.locale}
if self.provider and self.provider != "libc":
kwargs["provider"] = self.provider
if self.deterministic is False:
kwargs["deterministic"] = self.deterministic
return (
self.__class__.__qualname__,
[],
kwargs,
)
def create_collation(self, schema_editor):
args = {"locale": schema_editor.quote_name(self.locale)}
if self.provider != "libc":
args["provider"] = schema_editor.quote_name(self.provider)
if self.deterministic is False:
args["deterministic"] = "false"
schema_editor.execute(
"CREATE COLLATION %(name)s (%(args)s)"
% {
"name": schema_editor.quote_name(self.name),
"args": ", ".join(
f"{option}={value}" for option, value in args.items()
),
}
)
def remove_collation(self, schema_editor):
schema_editor.execute(
"DROP COLLATION %s" % schema_editor.quote_name(self.name),
)
class CreateCollation(CollationOperation):
"""Create a collation."""
category = OperationCategory.ADDITION
def database_forwards(self, app_label, schema_editor, from_state, to_state):
if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate(
schema_editor.connection.alias, app_label
):
return
self.create_collation(schema_editor)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
if not router.allow_migrate(schema_editor.connection.alias, app_label):
return
self.remove_collation(schema_editor)
def describe(self):
return f"Create collation {self.name}"
@property
def migration_name_fragment(self):
return "create_collation_%s" % self.name.lower()
def reduce(self, operation, app_label):
if isinstance(operation, RemoveCollation) and self.name == operation.name:
return []
return super().reduce(operation, app_label)
class RemoveCollation(CollationOperation):
"""Remove a collation."""
category = OperationCategory.REMOVAL
def database_forwards(self, app_label, schema_editor, from_state, to_state):
if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate(
schema_editor.connection.alias, app_label
):
return
self.remove_collation(schema_editor)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
if not router.allow_migrate(schema_editor.connection.alias, app_label):
return
self.create_collation(schema_editor)
def describe(self):
return f"Remove collation {self.name}"
@property
def migration_name_fragment(self):
return "remove_collation_%s" % self.name.lower()
class AddConstraintNotValid(AddConstraint):
"""
Add a table constraint without enforcing validation, using PostgreSQL's
NOT VALID syntax.
"""
category = OperationCategory.ADDITION
def __init__(self, model_name, constraint):
if not isinstance(constraint, CheckConstraint):
raise TypeError(
"AddConstraintNotValid.constraint must be a check constraint."
)
super().__init__(model_name, constraint)
def describe(self):
return "Create not valid constraint %s on model %s" % (
self.constraint.name,
self.model_name,
)
def database_forwards(self, app_label, schema_editor, from_state, to_state):
model = from_state.apps.get_model(app_label, self.model_name)
if self.allow_migrate_model(schema_editor.connection.alias, model):
constraint_sql = self.constraint.create_sql(model, schema_editor)
if constraint_sql:
# Constraint.create_sql returns interpolated SQL which makes
# params=None a necessity to avoid escaping attempts on
# execution.
schema_editor.execute(str(constraint_sql) + " NOT VALID", params=None)
@property
def migration_name_fragment(self):
return super().migration_name_fragment + "_not_valid"
class ValidateConstraint(Operation):
"""Validate a table NOT VALID constraint."""
category = OperationCategory.ALTERATION
def __init__(self, model_name, name):
self.model_name = model_name
self.name = name
def describe(self):
return "Validate constraint %s on model %s" % (self.name, self.model_name)
def database_forwards(self, app_label, schema_editor, from_state, to_state):
model = from_state.apps.get_model(app_label, self.model_name)
if self.allow_migrate_model(schema_editor.connection.alias, model):
schema_editor.execute(
"ALTER TABLE %s VALIDATE CONSTRAINT %s"
% (
schema_editor.quote_name(model._meta.db_table),
schema_editor.quote_name(self.name),
)
)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
# PostgreSQL does not provide a way to make a constraint invalid.
pass
def state_forwards(self, app_label, state):
pass
@property
def migration_name_fragment(self):
return "%s_validate_%s" % (self.model_name.lower(), self.name.lower())
def deconstruct(self):
return (
self.__class__.__name__,
[],
{
"model_name": self.model_name,
"name": self.name,
},
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/constraints.py | django/contrib/postgres/constraints.py | from types import NoneType
from django.core.exceptions import ValidationError
from django.db import DEFAULT_DB_ALIAS
from django.db.backends.ddl_references import Expressions, Statement, Table
from django.db.models import BaseConstraint, Deferrable, F, Q
from django.db.models.expressions import Exists, ExpressionList
from django.db.models.indexes import IndexExpression
from django.db.models.lookups import PostgresOperatorLookup
from django.db.models.sql import Query
from .utils import CheckPostgresInstalledMixin
__all__ = ["ExclusionConstraint"]
class ExclusionConstraintExpression(IndexExpression):
template = "%(expressions)s WITH %(operator)s"
class ExclusionConstraint(CheckPostgresInstalledMixin, BaseConstraint):
template = (
"CONSTRAINT %(name)s EXCLUDE USING %(index_type)s "
"(%(expressions)s)%(include)s%(where)s%(deferrable)s"
)
def __init__(
self,
*,
name,
expressions,
index_type=None,
condition=None,
deferrable=None,
include=None,
violation_error_code=None,
violation_error_message=None,
):
if index_type and index_type.lower() not in {"gist", "spgist"}:
raise ValueError(
"Exclusion constraints only support GiST or SP-GiST indexes."
)
if not expressions:
raise ValueError(
"At least one expression is required to define an exclusion "
"constraint."
)
if not all(
isinstance(expr, (list, tuple)) and len(expr) == 2 for expr in expressions
):
raise ValueError("The expressions must be a list of 2-tuples.")
if not isinstance(condition, (NoneType, Q)):
raise ValueError("ExclusionConstraint.condition must be a Q instance.")
if not isinstance(deferrable, (NoneType, Deferrable)):
raise ValueError(
"ExclusionConstraint.deferrable must be a Deferrable instance."
)
if not isinstance(include, (NoneType, list, tuple)):
raise ValueError("ExclusionConstraint.include must be a list or tuple.")
self.expressions = expressions
self.index_type = index_type or "GIST"
self.condition = condition
self.deferrable = deferrable
self.include = tuple(include) if include else ()
super().__init__(
name=name,
violation_error_code=violation_error_code,
violation_error_message=violation_error_message,
)
def _get_expressions(self, schema_editor, query):
expressions = []
for idx, (expression, operator) in enumerate(self.expressions):
if isinstance(expression, str):
expression = F(expression)
expression = ExclusionConstraintExpression(expression, operator=operator)
expression.set_wrapper_classes(schema_editor.connection)
expressions.append(expression)
return ExpressionList(*expressions).resolve_expression(query)
def check(self, model, connection):
errors = super().check(model, connection)
references = set()
for expr, _ in self.expressions:
if isinstance(expr, str):
expr = F(expr)
references.update(model._get_expr_references(expr))
errors.extend(self._check_references(model, references))
return errors
def _get_condition_sql(self, compiler, schema_editor, query):
if self.condition is None:
return None
where = query.build_where(self.condition)
sql, params = where.as_sql(compiler, schema_editor.connection)
return sql % tuple(schema_editor.quote_value(p) for p in params)
def constraint_sql(self, model, schema_editor):
query = Query(model, alias_cols=False)
compiler = query.get_compiler(connection=schema_editor.connection)
expressions = self._get_expressions(schema_editor, query)
table = model._meta.db_table
condition = self._get_condition_sql(compiler, schema_editor, query)
include = [
model._meta.get_field(field_name).column for field_name in self.include
]
return Statement(
self.template,
table=Table(table, schema_editor.quote_name),
name=schema_editor.quote_name(self.name),
index_type=self.index_type,
expressions=Expressions(
table, expressions, compiler, schema_editor.quote_value
),
where=" WHERE (%s)" % condition if condition else "",
include=schema_editor._index_include_sql(model, include),
deferrable=schema_editor._deferrable_constraint_sql(self.deferrable),
)
def create_sql(self, model, schema_editor):
return Statement(
"ALTER TABLE %(table)s ADD %(constraint)s",
table=Table(model._meta.db_table, schema_editor.quote_name),
constraint=self.constraint_sql(model, schema_editor),
)
def remove_sql(self, model, schema_editor):
return schema_editor._delete_constraint_sql(
schema_editor.sql_delete_check,
model,
schema_editor.quote_name(self.name),
)
def deconstruct(self):
path, args, kwargs = super().deconstruct()
kwargs["expressions"] = self.expressions
if self.condition is not None:
kwargs["condition"] = self.condition
if self.index_type.lower() != "gist":
kwargs["index_type"] = self.index_type
if self.deferrable:
kwargs["deferrable"] = self.deferrable
if self.include:
kwargs["include"] = self.include
return path, args, kwargs
def __eq__(self, other):
if isinstance(other, self.__class__):
return (
self.name == other.name
and self.index_type == other.index_type
and self.expressions == other.expressions
and self.condition == other.condition
and self.deferrable == other.deferrable
and self.include == other.include
and self.violation_error_code == other.violation_error_code
and self.violation_error_message == other.violation_error_message
)
return super().__eq__(other)
def __repr__(self):
return "<%s: index_type=%s expressions=%s name=%s%s%s%s%s%s>" % (
self.__class__.__qualname__,
repr(self.index_type),
repr(self.expressions),
repr(self.name),
"" if self.condition is None else " condition=%s" % self.condition,
"" if self.deferrable is None else " deferrable=%r" % self.deferrable,
"" if not self.include else " include=%s" % repr(self.include),
(
""
if self.violation_error_code is None
else " violation_error_code=%r" % self.violation_error_code
),
(
""
if self.violation_error_message is None
or self.violation_error_message == self.default_violation_error_message
else " violation_error_message=%r" % self.violation_error_message
),
)
def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS):
queryset = model._default_manager.using(using)
replacement_map = instance._get_field_expression_map(
meta=model._meta, exclude=exclude
)
replacements = {F(field): value for field, value in replacement_map.items()}
lookups = []
for expression, operator in self.expressions:
if isinstance(expression, str):
expression = F(expression)
if exclude and self._expression_refs_exclude(model, expression, exclude):
return
rhs_expression = expression.replace_expressions(replacements)
if hasattr(expression, "get_expression_for_validation"):
expression = expression.get_expression_for_validation()
if hasattr(rhs_expression, "get_expression_for_validation"):
rhs_expression = rhs_expression.get_expression_for_validation()
lookup = PostgresOperatorLookup(lhs=expression, rhs=rhs_expression)
lookup.postgres_operator = operator
lookups.append(lookup)
queryset = queryset.filter(*lookups)
model_class_pk = instance._get_pk_val(model._meta)
if not instance._state.adding and instance._is_pk_set(model._meta):
queryset = queryset.exclude(pk=model_class_pk)
if not self.condition:
if queryset.exists():
raise ValidationError(
self.get_violation_error_message(), code=self.violation_error_code
)
else:
# Ignore constraints with excluded fields in condition.
if exclude and self._expression_refs_exclude(
model, self.condition, exclude
):
return
if (self.condition & Exists(queryset.filter(self.condition))).check(
replacement_map, using=using
):
raise ValidationError(
self.get_violation_error_message(), code=self.violation_error_code
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/signals.py | django/contrib/postgres/signals.py | import functools
from django.db import connections
from django.db.backends.base.base import NO_DB_ALIAS
from django.db.backends.postgresql.psycopg_any import is_psycopg3
def get_type_oids(connection_alias, type_name):
with connections[connection_alias].cursor() as cursor:
cursor.execute(
"SELECT oid, typarray FROM pg_type WHERE typname = %s", (type_name,)
)
oids = []
array_oids = []
for row in cursor:
oids.append(row[0])
array_oids.append(row[1])
return tuple(oids), tuple(array_oids)
@functools.lru_cache
def get_hstore_oids(connection_alias):
"""Return hstore and hstore array OIDs."""
return get_type_oids(connection_alias, "hstore")
@functools.lru_cache
def get_citext_oids(connection_alias):
"""Return citext and citext array OIDs."""
return get_type_oids(connection_alias, "citext")
if is_psycopg3:
from psycopg.types import TypeInfo, hstore
def register_type_handlers(connection, **kwargs):
if connection.vendor != "postgresql" or connection.alias == NO_DB_ALIAS:
return
oids, array_oids = get_hstore_oids(connection.alias)
for oid, array_oid in zip(oids, array_oids):
ti = TypeInfo("hstore", oid, array_oid)
hstore.register_hstore(ti, connection.connection)
_, citext_oids = get_citext_oids(connection.alias)
for array_oid in citext_oids:
ti = TypeInfo("citext", 0, array_oid)
ti.register(connection.connection)
else:
import psycopg2
from psycopg2.extras import register_hstore
def register_type_handlers(connection, **kwargs):
if connection.vendor != "postgresql" or connection.alias == NO_DB_ALIAS:
return
oids, array_oids = get_hstore_oids(connection.alias)
# Don't register handlers when hstore is not available on the database.
#
# If someone tries to create an hstore field it will error there. This
# is necessary as someone may be using PSQL without extensions
# installed but be using other features of contrib.postgres.
#
# This is also needed in order to create the connection in order to
# install the hstore extension.
if oids:
register_hstore(
connection.connection, globally=True, oid=oids, array_oid=array_oids
)
oids, citext_oids = get_citext_oids(connection.alias)
# Don't register handlers when citext is not available on the database.
#
# The same comments in the above call to register_hstore() also apply
# here.
if oids:
array_type = psycopg2.extensions.new_array_type(
citext_oids, "citext[]", psycopg2.STRING
)
psycopg2.extensions.register_type(array_type, None)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/serializers.py | django/contrib/postgres/serializers.py | from django.db.migrations.serializer import BaseSerializer
class RangeSerializer(BaseSerializer):
def serialize(self):
module = self.value.__class__.__module__
# Ranges are implemented in psycopg2._range but the public import
# location is psycopg2.extras.
module = "psycopg2.extras" if module == "psycopg2._range" else module
return "%s.%r" % (module, self.value), {"import %s" % module}
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/validators.py | django/contrib/postgres/validators.py | from django.core.exceptions import ValidationError
from django.core.validators import (
MaxLengthValidator,
MaxValueValidator,
MinLengthValidator,
MinValueValidator,
)
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext_lazy
class ArrayMaxLengthValidator(MaxLengthValidator):
message = ngettext_lazy(
"List contains %(show_value)d item, it should contain no more than "
"%(limit_value)d.",
"List contains %(show_value)d items, it should contain no more than "
"%(limit_value)d.",
"show_value",
)
class ArrayMinLengthValidator(MinLengthValidator):
message = ngettext_lazy(
"List contains %(show_value)d item, it should contain no fewer than "
"%(limit_value)d.",
"List contains %(show_value)d items, it should contain no fewer than "
"%(limit_value)d.",
"show_value",
)
@deconstructible
class KeysValidator:
"""A validator designed for HStore to require/restrict keys."""
messages = {
"missing_keys": _("Some keys were missing: %(keys)s"),
"extra_keys": _("Some unknown keys were provided: %(keys)s"),
}
strict = False
def __init__(self, keys, strict=False, messages=None):
self.keys = set(keys)
self.strict = strict
if messages is not None:
self.messages = {**self.messages, **messages}
def __call__(self, value):
keys = set(value)
missing_keys = self.keys - keys
if missing_keys:
raise ValidationError(
self.messages["missing_keys"],
code="missing_keys",
params={"keys": ", ".join(missing_keys)},
)
if self.strict:
extra_keys = keys - self.keys
if extra_keys:
raise ValidationError(
self.messages["extra_keys"],
code="extra_keys",
params={"keys": ", ".join(extra_keys)},
)
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.keys == other.keys
and self.messages == other.messages
and self.strict == other.strict
)
class RangeMaxValueValidator(MaxValueValidator):
def compare(self, a, b):
return a.upper is None or a.upper > b
message = _(
"Ensure that the upper bound of the range is not greater than %(limit_value)s."
)
class RangeMinValueValidator(MinValueValidator):
def compare(self, a, b):
return a.lower is None or a.lower < b
message = _(
"Ensure that the lower bound of the range is not less than %(limit_value)s."
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/expressions.py | django/contrib/postgres/expressions.py | from django.contrib.postgres.fields import ArrayField
from django.db.models import Subquery
from django.utils.functional import cached_property
class ArraySubquery(Subquery):
template = "ARRAY(%(subquery)s)"
def __init__(self, queryset, **kwargs):
super().__init__(queryset, **kwargs)
@cached_property
def output_field(self):
return ArrayField(self.query.output_field)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/utils.py | django/contrib/postgres/utils.py | from django.apps import apps
from django.core import checks
from django.core.exceptions import ValidationError
from django.utils.functional import SimpleLazyObject
from django.utils.text import format_lazy
def prefix_validation_error(error, prefix, code, params):
"""
Prefix a validation error message while maintaining the existing
validation data structure.
"""
if error.error_list == [error]:
error_params = error.params or {}
return ValidationError(
# We can't simply concatenate messages since they might require
# their associated parameters to be expressed correctly which
# is not something `format_lazy` does. For example, proxied
# ngettext calls require a count parameter and are converted
# to an empty string if they are missing it.
message=format_lazy(
"{} {}",
SimpleLazyObject(lambda: prefix % params),
SimpleLazyObject(lambda: error.message % error_params),
),
code=code,
params={**error_params, **params},
)
return ValidationError(
[prefix_validation_error(e, prefix, code, params) for e in error.error_list]
)
class CheckPostgresInstalledMixin:
def _check_postgres_installed(self, *args):
# When subclassed by Index or BaseConstraint subclasses, args is
# (model, connection).
obj = args[0] if args else self
if not apps.is_installed("django.contrib.postgres"):
return [
checks.Error(
"'django.contrib.postgres' must be in INSTALLED_APPS in "
"order to use %s." % self.__class__.__name__,
obj=obj,
id="postgres.E005",
)
]
return []
def check(self, *args, **kwargs):
errors = super().check(*args, **kwargs)
errors.extend(self._check_postgres_installed(*args))
return errors
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/__init__.py | django/contrib/postgres/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/apps.py | django/contrib/postgres/apps.py | from django.apps import AppConfig
from django.core.signals import setting_changed
from django.db import connections
from django.db.backends.postgresql.psycopg_any import RANGE_TYPES
from django.db.backends.signals import connection_created
from django.db.migrations.writer import MigrationWriter
from django.db.models import CharField, OrderBy, TextField
from django.db.models.functions import Collate
from django.db.models.indexes import IndexExpression
from django.utils.translation import gettext_lazy as _
from .indexes import OpClass
from .lookups import (
SearchLookup,
TrigramSimilar,
TrigramStrictWordSimilar,
TrigramWordSimilar,
Unaccent,
)
from .serializers import RangeSerializer
from .signals import register_type_handlers
def uninstall_if_needed(setting, value, enter, **kwargs):
"""
Undo the effects of PostgresConfig.ready() when django.contrib.postgres
is "uninstalled" by override_settings().
"""
if (
not enter
and setting == "INSTALLED_APPS"
and "django.contrib.postgres" not in set(value)
):
connection_created.disconnect(register_type_handlers)
CharField._unregister_lookup(Unaccent)
TextField._unregister_lookup(Unaccent)
CharField._unregister_lookup(SearchLookup)
TextField._unregister_lookup(SearchLookup)
CharField._unregister_lookup(TrigramSimilar)
TextField._unregister_lookup(TrigramSimilar)
CharField._unregister_lookup(TrigramWordSimilar)
TextField._unregister_lookup(TrigramWordSimilar)
CharField._unregister_lookup(TrigramStrictWordSimilar)
TextField._unregister_lookup(TrigramStrictWordSimilar)
# Disconnect this receiver until the next time this app is installed
# and ready() connects it again to prevent unnecessary processing on
# each setting change.
setting_changed.disconnect(uninstall_if_needed)
MigrationWriter.unregister_serializer(RANGE_TYPES)
class PostgresConfig(AppConfig):
name = "django.contrib.postgres"
verbose_name = _("PostgreSQL extensions")
def ready(self):
setting_changed.connect(uninstall_if_needed)
# Connections may already exist before we are called.
for conn in connections.all(initialized_only=True):
if conn.vendor == "postgresql":
conn.introspection.data_types_reverse.update(
{
3904: "django.contrib.postgres.fields.IntegerRangeField",
3906: "django.contrib.postgres.fields.DecimalRangeField",
3910: "django.contrib.postgres.fields.DateTimeRangeField",
3912: "django.contrib.postgres.fields.DateRangeField",
3926: "django.contrib.postgres.fields.BigIntegerRangeField",
# PostgreSQL OIDs may vary depending on the
# installation, especially for datatypes from
# extensions, e.g. "hstore". In such cases, the
# type_display attribute (psycopg 3.2+) should be used.
"hstore": "django.contrib.postgres.fields.HStoreField",
}
)
if conn.connection is not None:
register_type_handlers(conn)
connection_created.connect(register_type_handlers)
CharField.register_lookup(Unaccent)
TextField.register_lookup(Unaccent)
CharField.register_lookup(SearchLookup)
TextField.register_lookup(SearchLookup)
CharField.register_lookup(TrigramSimilar)
TextField.register_lookup(TrigramSimilar)
CharField.register_lookup(TrigramWordSimilar)
TextField.register_lookup(TrigramWordSimilar)
CharField.register_lookup(TrigramStrictWordSimilar)
TextField.register_lookup(TrigramStrictWordSimilar)
MigrationWriter.register_serializer(RANGE_TYPES, RangeSerializer)
IndexExpression.register_wrappers(OrderBy, OpClass, Collate)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/functions.py | django/contrib/postgres/functions.py | from django.db.models import DateTimeField, Func, UUIDField
class RandomUUID(Func):
template = "GEN_RANDOM_UUID()"
output_field = UUIDField()
class TransactionNow(Func):
template = "CURRENT_TIMESTAMP"
output_field = DateTimeField()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/indexes.py | django/contrib/postgres/indexes.py | from django.db.models import Func, Index
from django.utils.functional import cached_property
from .utils import CheckPostgresInstalledMixin
__all__ = [
"BloomIndex",
"BrinIndex",
"BTreeIndex",
"GinIndex",
"GistIndex",
"HashIndex",
"SpGistIndex",
]
class PostgresIndex(CheckPostgresInstalledMixin, Index):
@cached_property
def max_name_length(self):
# Allow an index name longer than 30 characters when the suffix is
# longer than the usual 3 character limit. The 30 character limit for
# cross-database compatibility isn't applicable to PostgreSQL-specific
# indexes.
return Index.max_name_length - len(Index.suffix) + len(self.suffix)
def create_sql(self, model, schema_editor, using="", **kwargs):
self.check_supported(schema_editor)
statement = super().create_sql(
model, schema_editor, using=" USING %s" % (using or self.suffix), **kwargs
)
with_params = self.get_with_params()
if with_params:
statement.parts["extra"] = " WITH (%s)%s" % (
", ".join(with_params),
statement.parts["extra"],
)
return statement
def check_supported(self, schema_editor):
pass
def get_with_params(self):
return []
class BloomIndex(PostgresIndex):
suffix = "bloom"
def __init__(self, *expressions, length=None, columns=(), **kwargs):
super().__init__(*expressions, **kwargs)
if len(self.fields) > 32:
raise ValueError("Bloom indexes support a maximum of 32 fields.")
if not isinstance(columns, (list, tuple)):
raise ValueError("BloomIndex.columns must be a list or tuple.")
if len(columns) > len(self.fields):
raise ValueError("BloomIndex.columns cannot have more values than fields.")
if not all(0 < col <= 4095 for col in columns):
raise ValueError(
"BloomIndex.columns must contain integers from 1 to 4095.",
)
if length is not None and not 0 < length <= 4096:
raise ValueError(
"BloomIndex.length must be None or an integer from 1 to 4096.",
)
self.length = length
self.columns = columns
def deconstruct(self):
path, args, kwargs = super().deconstruct()
if self.length is not None:
kwargs["length"] = self.length
if self.columns:
kwargs["columns"] = self.columns
return path, args, kwargs
def get_with_params(self):
with_params = []
if self.length is not None:
with_params.append("length = %d" % self.length)
if self.columns:
with_params.extend(
"col%d = %d" % (i, v) for i, v in enumerate(self.columns, start=1)
)
return with_params
class BrinIndex(PostgresIndex):
suffix = "brin"
def __init__(
self, *expressions, autosummarize=None, pages_per_range=None, **kwargs
):
if pages_per_range is not None and pages_per_range <= 0:
raise ValueError("pages_per_range must be None or a positive integer")
self.autosummarize = autosummarize
self.pages_per_range = pages_per_range
super().__init__(*expressions, **kwargs)
def deconstruct(self):
path, args, kwargs = super().deconstruct()
if self.autosummarize is not None:
kwargs["autosummarize"] = self.autosummarize
if self.pages_per_range is not None:
kwargs["pages_per_range"] = self.pages_per_range
return path, args, kwargs
def get_with_params(self):
with_params = []
if self.autosummarize is not None:
with_params.append(
"autosummarize = %s" % ("on" if self.autosummarize else "off")
)
if self.pages_per_range is not None:
with_params.append("pages_per_range = %d" % self.pages_per_range)
return with_params
class BTreeIndex(PostgresIndex):
suffix = "btree"
def __init__(self, *expressions, fillfactor=None, deduplicate_items=None, **kwargs):
self.fillfactor = fillfactor
self.deduplicate_items = deduplicate_items
super().__init__(*expressions, **kwargs)
def deconstruct(self):
path, args, kwargs = super().deconstruct()
if self.fillfactor is not None:
kwargs["fillfactor"] = self.fillfactor
if self.deduplicate_items is not None:
kwargs["deduplicate_items"] = self.deduplicate_items
return path, args, kwargs
def get_with_params(self):
with_params = []
if self.fillfactor is not None:
with_params.append("fillfactor = %d" % self.fillfactor)
if self.deduplicate_items is not None:
with_params.append(
"deduplicate_items = %s" % ("on" if self.deduplicate_items else "off")
)
return with_params
class GinIndex(PostgresIndex):
suffix = "gin"
def __init__(
self, *expressions, fastupdate=None, gin_pending_list_limit=None, **kwargs
):
self.fastupdate = fastupdate
self.gin_pending_list_limit = gin_pending_list_limit
super().__init__(*expressions, **kwargs)
def deconstruct(self):
path, args, kwargs = super().deconstruct()
if self.fastupdate is not None:
kwargs["fastupdate"] = self.fastupdate
if self.gin_pending_list_limit is not None:
kwargs["gin_pending_list_limit"] = self.gin_pending_list_limit
return path, args, kwargs
def get_with_params(self):
with_params = []
if self.gin_pending_list_limit is not None:
with_params.append(
"gin_pending_list_limit = %d" % self.gin_pending_list_limit
)
if self.fastupdate is not None:
with_params.append("fastupdate = %s" % ("on" if self.fastupdate else "off"))
return with_params
class GistIndex(PostgresIndex):
suffix = "gist"
def __init__(self, *expressions, buffering=None, fillfactor=None, **kwargs):
self.buffering = buffering
self.fillfactor = fillfactor
super().__init__(*expressions, **kwargs)
def deconstruct(self):
path, args, kwargs = super().deconstruct()
if self.buffering is not None:
kwargs["buffering"] = self.buffering
if self.fillfactor is not None:
kwargs["fillfactor"] = self.fillfactor
return path, args, kwargs
def get_with_params(self):
with_params = []
if self.buffering is not None:
with_params.append("buffering = %s" % ("on" if self.buffering else "off"))
if self.fillfactor is not None:
with_params.append("fillfactor = %d" % self.fillfactor)
return with_params
class HashIndex(PostgresIndex):
suffix = "hash"
def __init__(self, *expressions, fillfactor=None, **kwargs):
self.fillfactor = fillfactor
super().__init__(*expressions, **kwargs)
def deconstruct(self):
path, args, kwargs = super().deconstruct()
if self.fillfactor is not None:
kwargs["fillfactor"] = self.fillfactor
return path, args, kwargs
def get_with_params(self):
with_params = []
if self.fillfactor is not None:
with_params.append("fillfactor = %d" % self.fillfactor)
return with_params
class SpGistIndex(PostgresIndex):
suffix = "spgist"
def __init__(self, *expressions, fillfactor=None, **kwargs):
self.fillfactor = fillfactor
super().__init__(*expressions, **kwargs)
def deconstruct(self):
path, args, kwargs = super().deconstruct()
if self.fillfactor is not None:
kwargs["fillfactor"] = self.fillfactor
return path, args, kwargs
def get_with_params(self):
with_params = []
if self.fillfactor is not None:
with_params.append("fillfactor = %d" % self.fillfactor)
return with_params
class OpClass(Func):
template = "%(expressions)s %(name)s"
constraint_validation_compatible = False
def __init__(self, expression, name):
super().__init__(expression, name=name)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/aggregates/mixins.py | django/contrib/postgres/aggregates/mixins.py | # RemovedInDjango70Warning: When the deprecation ends, remove completely.
import warnings
from django.utils.deprecation import RemovedInDjango70Warning
# RemovedInDjango70Warning.
class OrderableAggMixin:
allow_order_by = True
def __init_subclass__(cls, /, *args, **kwargs):
warnings.warn(
"OrderableAggMixin is deprecated. Use Aggregate and allow_order_by "
"instead.",
category=RemovedInDjango70Warning,
stacklevel=1,
)
super().__init_subclass__(*args, **kwargs)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/aggregates/general.py | django/contrib/postgres/aggregates/general.py | import warnings
from django.contrib.postgres.fields import ArrayField
from django.db.models import Aggregate, BooleanField, JSONField
from django.db.models import StringAgg as _StringAgg
from django.db.models import Value
from django.utils.deprecation import RemovedInDjango70Warning
__all__ = [
"ArrayAgg",
"BitAnd",
"BitOr",
"BitXor",
"BoolAnd",
"BoolOr",
"JSONBAgg",
"StringAgg", # RemovedInDjango70Warning.
]
class ArrayAgg(Aggregate):
function = "ARRAY_AGG"
allow_distinct = True
allow_order_by = True
@property
def output_field(self):
return ArrayField(self.source_expressions[0].output_field)
class BitAnd(Aggregate):
function = "BIT_AND"
class BitOr(Aggregate):
function = "BIT_OR"
class BitXor(Aggregate):
function = "BIT_XOR"
class BoolAnd(Aggregate):
function = "BOOL_AND"
output_field = BooleanField()
class BoolOr(Aggregate):
function = "BOOL_OR"
output_field = BooleanField()
class JSONBAgg(Aggregate):
function = "JSONB_AGG"
allow_distinct = True
allow_order_by = True
output_field = JSONField()
# RemovedInDjango70Warning: When the deprecation ends, remove completely.
class StringAgg(_StringAgg):
def __init__(self, expression, delimiter, **extra):
if isinstance(delimiter, str):
warnings.warn(
"delimiter: str will be resolved as a field reference instead "
"of a string literal on Django 7.0. Pass "
f"`delimiter=Value({delimiter!r})` to preserve the previous behavior.",
category=RemovedInDjango70Warning,
stacklevel=2,
)
delimiter = Value(delimiter)
warnings.warn(
"The PostgreSQL specific StringAgg function is deprecated. Use "
"django.db.models.aggregates.StringAgg instead.",
category=RemovedInDjango70Warning,
stacklevel=2,
)
super().__init__(expression, delimiter, **extra)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/aggregates/statistics.py | django/contrib/postgres/aggregates/statistics.py | from django.db.models import Aggregate, FloatField, IntegerField
__all__ = [
"CovarPop",
"Corr",
"RegrAvgX",
"RegrAvgY",
"RegrCount",
"RegrIntercept",
"RegrR2",
"RegrSlope",
"RegrSXX",
"RegrSXY",
"RegrSYY",
"StatAggregate",
]
class StatAggregate(Aggregate):
output_field = FloatField()
def __init__(self, y, x, output_field=None, filter=None, default=None):
if not x or not y:
raise ValueError("Both y and x must be provided.")
super().__init__(
y, x, output_field=output_field, filter=filter, default=default
)
class Corr(StatAggregate):
function = "CORR"
class CovarPop(StatAggregate):
def __init__(self, y, x, sample=False, filter=None, default=None):
self.function = "COVAR_SAMP" if sample else "COVAR_POP"
super().__init__(y, x, filter=filter, default=default)
class RegrAvgX(StatAggregate):
function = "REGR_AVGX"
class RegrAvgY(StatAggregate):
function = "REGR_AVGY"
class RegrCount(StatAggregate):
function = "REGR_COUNT"
output_field = IntegerField()
empty_result_set_value = 0
class RegrIntercept(StatAggregate):
function = "REGR_INTERCEPT"
class RegrR2(StatAggregate):
function = "REGR_R2"
class RegrSlope(StatAggregate):
function = "REGR_SLOPE"
class RegrSXX(StatAggregate):
function = "REGR_SXX"
class RegrSXY(StatAggregate):
function = "REGR_SXY"
class RegrSYY(StatAggregate):
function = "REGR_SYY"
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/aggregates/__init__.py | django/contrib/postgres/aggregates/__init__.py | from .general import * # NOQA
from .statistics import * # NOQA
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/forms/array.py | django/contrib/postgres/forms/array.py | import copy
from itertools import chain
from django import forms
from django.contrib.postgres.utils import prefix_validation_error
from django.contrib.postgres.validators import (
ArrayMaxLengthValidator,
ArrayMinLengthValidator,
)
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
class SimpleArrayField(forms.CharField):
default_error_messages = {
"item_invalid": _("Item %(nth)s in the array did not validate:"),
}
def __init__(
self, base_field, *, delimiter=",", max_length=None, min_length=None, **kwargs
):
self.base_field = base_field
self.delimiter = delimiter
super().__init__(**kwargs)
if min_length is not None:
self.min_length = min_length
self.validators.append(ArrayMinLengthValidator(int(min_length)))
if max_length is not None:
self.max_length = max_length
self.validators.append(ArrayMaxLengthValidator(int(max_length)))
def clean(self, value):
value = super().clean(value)
return [self.base_field.clean(val) for val in value]
def prepare_value(self, value):
if isinstance(value, list):
return self.delimiter.join(
str(self.base_field.prepare_value(v)) for v in value
)
return value
def to_python(self, value):
if isinstance(value, list):
items = value
elif value:
items = value.split(self.delimiter)
else:
items = []
errors = []
values = []
for index, item in enumerate(items):
try:
values.append(self.base_field.to_python(item))
except ValidationError as error:
errors.append(
prefix_validation_error(
error,
prefix=self.error_messages["item_invalid"],
code="item_invalid",
params={"nth": index + 1},
)
)
if errors:
raise ValidationError(errors)
return values
def validate(self, value):
super().validate(value)
errors = []
for index, item in enumerate(value):
try:
self.base_field.validate(item)
except ValidationError as error:
errors.append(
prefix_validation_error(
error,
prefix=self.error_messages["item_invalid"],
code="item_invalid",
params={"nth": index + 1},
)
)
if errors:
raise ValidationError(errors)
def run_validators(self, value):
super().run_validators(value)
errors = []
for index, item in enumerate(value):
try:
self.base_field.run_validators(item)
except ValidationError as error:
errors.append(
prefix_validation_error(
error,
prefix=self.error_messages["item_invalid"],
code="item_invalid",
params={"nth": index + 1},
)
)
if errors:
raise ValidationError(errors)
def has_changed(self, initial, data):
try:
value = self.to_python(data)
except ValidationError:
pass
else:
if initial in self.empty_values and value in self.empty_values:
return False
return super().has_changed(initial, data)
class SplitArrayWidget(forms.Widget):
template_name = "postgres/widgets/split_array.html"
def __init__(self, widget, size, **kwargs):
self.widget = widget() if isinstance(widget, type) else widget
self.size = size
super().__init__(**kwargs)
@property
def is_hidden(self):
return self.widget.is_hidden
def value_from_datadict(self, data, files, name):
return [
self.widget.value_from_datadict(data, files, "%s_%s" % (name, index))
for index in range(self.size)
]
def value_omitted_from_data(self, data, files, name):
return all(
self.widget.value_omitted_from_data(data, files, "%s_%s" % (name, index))
for index in range(self.size)
)
def id_for_label(self, id_):
# See the comment for RadioSelect.id_for_label()
if id_:
id_ += "_0"
return id_
def get_context(self, name, value, attrs=None):
attrs = {} if attrs is None else attrs
context = super().get_context(name, value, attrs)
if self.is_localized:
self.widget.is_localized = self.is_localized
value = value or []
context["widget"]["subwidgets"] = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get("id")
for i in range(max(len(value), self.size)):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = {**final_attrs, "id": "%s_%s" % (id_, i)}
context["widget"]["subwidgets"].append(
self.widget.get_context(name + "_%s" % i, widget_value, final_attrs)[
"widget"
]
)
return context
@property
def media(self):
return self.widget.media
def __deepcopy__(self, memo):
obj = super().__deepcopy__(memo)
obj.widget = copy.deepcopy(self.widget)
return obj
@property
def needs_multipart_form(self):
return self.widget.needs_multipart_form
class SplitArrayField(forms.Field):
default_error_messages = {
"item_invalid": _("Item %(nth)s in the array did not validate:"),
}
def __init__(self, base_field, size, *, remove_trailing_nulls=False, **kwargs):
self.base_field = base_field
self.size = size
self.remove_trailing_nulls = remove_trailing_nulls
widget = SplitArrayWidget(widget=base_field.widget, size=size)
kwargs.setdefault("widget", widget)
super().__init__(**kwargs)
def _remove_trailing_nulls(self, values):
index = None
if self.remove_trailing_nulls:
for i, value in reversed(list(enumerate(values))):
if value in self.base_field.empty_values:
index = i
else:
break
if index is not None:
values = values[:index]
return values, index
def to_python(self, value):
value = super().to_python(value)
return [self.base_field.to_python(item) for item in value]
def clean(self, value):
cleaned_data = []
errors = []
if not any(value) and self.required:
raise ValidationError(self.error_messages["required"])
max_size = max(self.size, len(value))
for index in range(max_size):
item = value[index]
try:
cleaned_data.append(self.base_field.clean(item))
except ValidationError as error:
errors.append(
prefix_validation_error(
error,
self.error_messages["item_invalid"],
code="item_invalid",
params={"nth": index + 1},
)
)
cleaned_data.append(item)
else:
errors.append(None)
cleaned_data, null_index = self._remove_trailing_nulls(cleaned_data)
if null_index is not None:
errors = errors[:null_index]
errors = list(filter(None, errors))
if errors:
raise ValidationError(list(chain.from_iterable(errors)))
return cleaned_data
def has_changed(self, initial, data):
try:
data = self.to_python(data)
except ValidationError:
pass
else:
data, _ = self._remove_trailing_nulls(data)
if initial in self.empty_values and data in self.empty_values:
return False
return super().has_changed(initial, data)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/forms/__init__.py | django/contrib/postgres/forms/__init__.py | from .array import * # NOQA
from .hstore import * # NOQA
from .ranges import * # NOQA
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/forms/hstore.py | django/contrib/postgres/forms/hstore.py | import json
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
__all__ = ["HStoreField"]
class HStoreField(forms.CharField):
"""
A field for HStore data which accepts dictionary JSON input.
"""
widget = forms.Textarea
default_error_messages = {
"invalid_json": _("Could not load JSON data."),
"invalid_format": _("Input must be a JSON dictionary."),
}
def prepare_value(self, value):
if isinstance(value, dict):
return json.dumps(value, ensure_ascii=False)
return value
def to_python(self, value):
if not value:
return {}
if not isinstance(value, dict):
try:
value = json.loads(value)
except json.JSONDecodeError:
raise ValidationError(
self.error_messages["invalid_json"],
code="invalid_json",
)
if not isinstance(value, dict):
raise ValidationError(
self.error_messages["invalid_format"],
code="invalid_format",
)
# Cast everything to strings for ease.
for key, val in value.items():
if val is not None:
val = str(val)
value[key] = val
return value
def has_changed(self, initial, data):
"""
Return True if data differs from initial.
"""
# For purposes of seeing whether something has changed, None is
# the same as an empty dict, if the data or initial value we get
# is None, replace it w/ {}.
initial_value = self.to_python(initial)
return super().has_changed(initial_value, data)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/forms/ranges.py | django/contrib/postgres/forms/ranges.py | from django import forms
from django.core import exceptions
from django.db.backends.postgresql.psycopg_any import (
DateRange,
DateTimeTZRange,
NumericRange,
)
from django.forms.widgets import HiddenInput, MultiWidget
from django.utils.translation import gettext_lazy as _
__all__ = [
"BaseRangeField",
"IntegerRangeField",
"DecimalRangeField",
"DateTimeRangeField",
"DateRangeField",
"HiddenRangeWidget",
"RangeWidget",
]
class RangeWidget(MultiWidget):
def __init__(self, base_widget, attrs=None):
widgets = (base_widget, base_widget)
super().__init__(widgets, attrs)
def decompress(self, value):
if value:
return (value.lower, value.upper)
return (None, None)
class HiddenRangeWidget(RangeWidget):
"""A widget that splits input into two <input type="hidden"> inputs."""
def __init__(self, attrs=None):
super().__init__(HiddenInput, attrs)
class BaseRangeField(forms.MultiValueField):
default_error_messages = {
"invalid": _("Enter two valid values."),
"bound_ordering": _(
"The start of the range must not exceed the end of the range."
),
}
hidden_widget = HiddenRangeWidget
def __init__(self, **kwargs):
if "widget" not in kwargs:
kwargs["widget"] = RangeWidget(self.base_field.widget)
if "fields" not in kwargs:
kwargs["fields"] = [
self.base_field(required=False),
self.base_field(required=False),
]
kwargs.setdefault("required", False)
kwargs.setdefault("require_all_fields", False)
self.range_kwargs = {}
if default_bounds := kwargs.pop("default_bounds", None):
self.range_kwargs = {"bounds": default_bounds}
super().__init__(**kwargs)
def prepare_value(self, value):
lower_base, upper_base = self.fields
if isinstance(value, self.range_type):
return [
lower_base.prepare_value(value.lower),
upper_base.prepare_value(value.upper),
]
if value is None:
return [
lower_base.prepare_value(None),
upper_base.prepare_value(None),
]
return value
def compress(self, values):
if not values:
return None
lower, upper = values
if lower is not None and upper is not None and lower > upper:
raise exceptions.ValidationError(
self.error_messages["bound_ordering"],
code="bound_ordering",
)
try:
range_value = self.range_type(lower, upper, **self.range_kwargs)
except TypeError:
raise exceptions.ValidationError(
self.error_messages["invalid"],
code="invalid",
)
else:
return range_value
class IntegerRangeField(BaseRangeField):
default_error_messages = {"invalid": _("Enter two whole numbers.")}
base_field = forms.IntegerField
range_type = NumericRange
class DecimalRangeField(BaseRangeField):
default_error_messages = {"invalid": _("Enter two numbers.")}
base_field = forms.DecimalField
range_type = NumericRange
class DateTimeRangeField(BaseRangeField):
default_error_messages = {"invalid": _("Enter two valid date/times.")}
base_field = forms.DateTimeField
range_type = DateTimeTZRange
class DateRangeField(BaseRangeField):
default_error_messages = {"invalid": _("Enter two valid dates.")}
base_field = forms.DateField
range_type = DateRange
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/fields/jsonb.py | django/contrib/postgres/fields/jsonb.py | from django.db.models import JSONField as BuiltinJSONField
__all__ = ["JSONField"]
class JSONField(BuiltinJSONField):
system_check_removed_details = {
"msg": (
"django.contrib.postgres.fields.JSONField is removed except for "
"support in historical migrations."
),
"hint": "Use django.db.models.JSONField instead.",
"id": "fields.E904",
}
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/fields/citext.py | django/contrib/postgres/fields/citext.py | from django.db.models import CharField, EmailField, TextField
__all__ = ["CICharField", "CIEmailField", "CITextField"]
class CICharField(CharField):
system_check_removed_details = {
"msg": (
"django.contrib.postgres.fields.CICharField is removed except for support "
"in historical migrations."
),
"hint": (
'Use CharField(db_collation="…") with a case-insensitive non-deterministic '
"collation instead."
),
"id": "fields.E905",
}
class CIEmailField(EmailField):
system_check_removed_details = {
"msg": (
"django.contrib.postgres.fields.CIEmailField is removed except for support "
"in historical migrations."
),
"hint": (
'Use EmailField(db_collation="…") with a case-insensitive '
"non-deterministic collation instead."
),
"id": "fields.E906",
}
class CITextField(TextField):
system_check_removed_details = {
"msg": (
"django.contrib.postgres.fields.CITextField is removed except for support "
"in historical migrations."
),
"hint": (
'Use TextField(db_collation="…") with a case-insensitive non-deterministic '
"collation instead."
),
"id": "fields.E907",
}
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/fields/utils.py | django/contrib/postgres/fields/utils.py | class AttributeSetter:
def __init__(self, name, value):
setattr(self, name, value)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/fields/array.py | django/contrib/postgres/fields/array.py | import json
from django.contrib.postgres import lookups
from django.contrib.postgres.forms import SimpleArrayField
from django.contrib.postgres.utils import (
CheckPostgresInstalledMixin,
prefix_validation_error,
)
from django.contrib.postgres.validators import ArrayMaxLengthValidator
from django.core import checks, exceptions
from django.db.models import Field, Func, IntegerField, Transform, Value
from django.db.models.fields.mixins import CheckFieldDefaultMixin
from django.db.models.lookups import Exact, In
from django.utils.translation import gettext_lazy as _
from .utils import AttributeSetter
__all__ = ["ArrayField"]
class ArrayField(CheckPostgresInstalledMixin, CheckFieldDefaultMixin, Field):
empty_strings_allowed = False
default_error_messages = {
"item_invalid": _("Item %(nth)s in the array did not validate:"),
"nested_array_mismatch": _("Nested arrays must have the same length."),
}
_default_hint = ("list", "[]")
def __init__(self, base_field, size=None, **kwargs):
self.base_field = base_field
self.db_collation = getattr(self.base_field, "db_collation", None)
self.size = size
if self.size:
self.default_validators = [
*self.default_validators,
ArrayMaxLengthValidator(self.size),
]
# For performance, only add a from_db_value() method if the base field
# implements it.
if hasattr(self.base_field, "from_db_value"):
self.from_db_value = self._from_db_value
super().__init__(**kwargs)
@property
def model(self):
try:
return self.__dict__["model"]
except KeyError:
raise AttributeError(
"'%s' object has no attribute 'model'" % self.__class__.__name__
)
@model.setter
def model(self, model):
self.__dict__["model"] = model
self.base_field.model = model
@classmethod
def _choices_is_value(cls, value):
return isinstance(value, (list, tuple)) or super()._choices_is_value(value)
def check(self, **kwargs):
errors = super().check(**kwargs)
if self.base_field.remote_field:
errors.append(
checks.Error(
"Base field for array cannot be a related field.",
obj=self,
id="postgres.E002",
)
)
else:
base_checks = self.base_field.check(**kwargs)
if base_checks:
error_messages = "\n ".join(
"%s (%s)" % (base_check.msg, base_check.id)
for base_check in base_checks
if isinstance(base_check, checks.Error)
# Prevent duplication of E005 in an E001 check.
and not base_check.id == "postgres.E005"
)
if error_messages:
errors.append(
checks.Error(
"Base field for array has errors:\n %s" % error_messages,
obj=self,
id="postgres.E001",
)
)
warning_messages = "\n ".join(
"%s (%s)" % (base_check.msg, base_check.id)
for base_check in base_checks
if isinstance(base_check, checks.Warning)
)
if warning_messages:
errors.append(
checks.Warning(
"Base field for array has warnings:\n %s"
% warning_messages,
obj=self,
id="postgres.W004",
)
)
return errors
def set_attributes_from_name(self, name):
super().set_attributes_from_name(name)
self.base_field.set_attributes_from_name(name)
@property
def description(self):
return "Array of %s" % self.base_field.description
def db_type(self, connection):
size = self.size or ""
return "%s[%s]" % (self.base_field.db_type(connection), size)
def cast_db_type(self, connection):
size = self.size or ""
return "%s[%s]" % (self.base_field.cast_db_type(connection), size)
def db_parameters(self, connection):
db_params = super().db_parameters(connection)
db_params["collation"] = self.db_collation
return db_params
def get_placeholder(self, value, compiler, connection):
return "%s::{}".format(self.db_type(connection))
def get_db_prep_value(self, value, connection, prepared=False):
if isinstance(value, (list, tuple)):
return [
self.base_field.get_db_prep_value(i, connection, prepared=False)
for i in value
]
return value
def get_db_prep_save(self, value, connection):
if isinstance(value, (list, tuple)):
return [self.base_field.get_db_prep_save(i, connection) for i in value]
return value
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if path == "django.contrib.postgres.fields.array.ArrayField":
path = "django.contrib.postgres.fields.ArrayField"
kwargs["base_field"] = self.base_field.clone()
if self.size is not None:
kwargs["size"] = self.size
return name, path, args, kwargs
def to_python(self, value):
if isinstance(value, str):
# Assume we're deserializing
vals = json.loads(value)
value = [self.base_field.to_python(val) for val in vals]
return value
def _from_db_value(self, value, expression, connection):
if value is None:
return value
return [
self.base_field.from_db_value(item, expression, connection)
for item in value
]
def value_to_string(self, obj):
values = []
vals = self.value_from_object(obj)
base_field = self.base_field
for val in vals:
if val is None:
values.append(None)
else:
obj = AttributeSetter(base_field.attname, val)
values.append(base_field.value_to_string(obj))
return json.dumps(values, ensure_ascii=False)
def get_transform(self, name):
transform = super().get_transform(name)
if transform:
return transform
if "_" not in name:
try:
index = int(name)
except ValueError:
pass
else:
index += 1 # postgres uses 1-indexing
return IndexTransformFactory(index, self.base_field)
try:
start, end = name.split("_")
start = int(start) + 1
end = int(end) # don't add one here because postgres slices are weird
except ValueError:
pass
else:
return SliceTransformFactory(start, end)
def validate(self, value, model_instance):
super().validate(value, model_instance)
for index, part in enumerate(value):
try:
self.base_field.validate(part, model_instance)
except exceptions.ValidationError as error:
raise prefix_validation_error(
error,
prefix=self.error_messages["item_invalid"],
code="item_invalid",
params={"nth": index + 1},
)
if isinstance(self.base_field, ArrayField):
if len({len(i) for i in value}) > 1:
raise exceptions.ValidationError(
self.error_messages["nested_array_mismatch"],
code="nested_array_mismatch",
)
def run_validators(self, value):
super().run_validators(value)
for index, part in enumerate(value):
try:
self.base_field.run_validators(part)
except exceptions.ValidationError as error:
raise prefix_validation_error(
error,
prefix=self.error_messages["item_invalid"],
code="item_invalid",
params={"nth": index + 1},
)
def formfield(self, **kwargs):
return super().formfield(
**{
"form_class": SimpleArrayField,
"base_field": self.base_field.formfield(),
"max_length": self.size,
**kwargs,
}
)
def slice_expression(self, expression, start, length):
# If length is not provided, don't specify an end to slice to the end
# of the array.
end = None if length is None else start + length - 1
return SliceTransform(start, end, expression)
class ArrayRHSMixin:
def __init__(self, lhs, rhs):
# Don't wrap arrays that contains only None values, psycopg doesn't
# allow this.
if isinstance(rhs, (tuple, list)) and any(self._rhs_not_none_values(rhs)):
expressions = []
for value in rhs:
if not hasattr(value, "resolve_expression"):
field = lhs.output_field
value = Value(field.base_field.get_prep_value(value))
expressions.append(value)
rhs = Func(
*expressions,
function="ARRAY",
template="%(function)s[%(expressions)s]",
)
super().__init__(lhs, rhs)
def process_rhs(self, compiler, connection):
rhs, rhs_params = super().process_rhs(compiler, connection)
cast_type = self.lhs.output_field.cast_db_type(connection)
return "%s::%s" % (rhs, cast_type), rhs_params
def _rhs_not_none_values(self, rhs):
for x in rhs:
if isinstance(x, (list, tuple)):
yield from self._rhs_not_none_values(x)
elif x is not None:
yield True
@ArrayField.register_lookup
class ArrayContains(ArrayRHSMixin, lookups.DataContains):
pass
@ArrayField.register_lookup
class ArrayContainedBy(ArrayRHSMixin, lookups.ContainedBy):
pass
@ArrayField.register_lookup
class ArrayExact(ArrayRHSMixin, Exact):
pass
@ArrayField.register_lookup
class ArrayOverlap(ArrayRHSMixin, lookups.Overlap):
pass
@ArrayField.register_lookup
class ArrayLenTransform(Transform):
lookup_name = "len"
output_field = IntegerField()
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
# Distinguish NULL and empty arrays
return (
"CASE WHEN %(lhs)s IS NULL THEN NULL ELSE "
"coalesce(array_length(%(lhs)s, 1), 0) END"
) % {"lhs": lhs}, params * 2
@ArrayField.register_lookup
class ArrayInLookup(In):
def get_prep_lookup(self):
values = super().get_prep_lookup()
if hasattr(values, "resolve_expression"):
return values
# In.process_rhs() expects values to be hashable, so convert lists
# to tuples.
prepared_values = []
for value in values:
if hasattr(value, "resolve_expression"):
prepared_values.append(value)
else:
prepared_values.append(tuple(value))
return prepared_values
class IndexTransform(Transform):
def __init__(self, index, base_field, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index = index
self.base_field = base_field
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
if not lhs.endswith("]"):
lhs = "(%s)" % lhs
return "%s[%%s]" % lhs, (*params, self.index)
@property
def output_field(self):
return self.base_field
class IndexTransformFactory:
def __init__(self, index, base_field):
self.index = index
self.base_field = base_field
def __call__(self, *args, **kwargs):
return IndexTransform(self.index, self.base_field, *args, **kwargs)
class SliceTransform(Transform):
def __init__(self, start, end, *args, **kwargs):
super().__init__(*args, **kwargs)
self.start = start
self.end = end
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
# self.start is set to 1 if slice start is not provided.
if self.end is None:
return f"({lhs})[%s:]", (*params, self.start)
else:
return f"({lhs})[%s:%s]", (*params, self.start, self.end)
class SliceTransformFactory:
def __init__(self, start, end):
self.start = start
self.end = end
def __call__(self, *args, **kwargs):
return SliceTransform(self.start, self.end, *args, **kwargs)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/fields/__init__.py | django/contrib/postgres/fields/__init__.py | from .array import * # NOQA
from .citext import * # NOQA
from .hstore import * # NOQA
from .jsonb import * # NOQA
from .ranges import * # NOQA
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/fields/hstore.py | django/contrib/postgres/fields/hstore.py | import json
from django.contrib.postgres import forms, lookups
from django.contrib.postgres.fields.array import ArrayField
from django.contrib.postgres.utils import CheckPostgresInstalledMixin
from django.core import exceptions
from django.db.models import Field, TextField, Transform
from django.db.models.fields.mixins import CheckFieldDefaultMixin
from django.utils.translation import gettext_lazy as _
__all__ = ["HStoreField"]
class HStoreField(CheckPostgresInstalledMixin, CheckFieldDefaultMixin, Field):
empty_strings_allowed = False
description = _("Map of strings to strings/nulls")
default_error_messages = {
"not_a_string": _("The value of “%(key)s” is not a string or null."),
}
_default_hint = ("dict", "{}")
def db_type(self, connection):
return "hstore"
def get_transform(self, name):
transform = super().get_transform(name)
if transform:
return transform
return KeyTransformFactory(name)
def validate(self, value, model_instance):
super().validate(value, model_instance)
for key, val in value.items():
if not isinstance(val, str) and val is not None:
raise exceptions.ValidationError(
self.error_messages["not_a_string"],
code="not_a_string",
params={"key": key},
)
def to_python(self, value):
if isinstance(value, str):
value = json.loads(value)
return value
def value_to_string(self, obj):
return json.dumps(self.value_from_object(obj), ensure_ascii=False)
def formfield(self, **kwargs):
return super().formfield(
**{
"form_class": forms.HStoreField,
**kwargs,
}
)
def get_prep_value(self, value):
value = super().get_prep_value(value)
if isinstance(value, dict):
prep_value = {}
for key, val in value.items():
key = str(key)
if val is not None:
val = str(val)
prep_value[key] = val
value = prep_value
if isinstance(value, list):
value = [str(item) for item in value]
return value
HStoreField.register_lookup(lookups.DataContains)
HStoreField.register_lookup(lookups.ContainedBy)
HStoreField.register_lookup(lookups.HasKey)
HStoreField.register_lookup(lookups.HasKeys)
HStoreField.register_lookup(lookups.HasAnyKeys)
class KeyTransform(Transform):
output_field = TextField()
def __init__(self, key_name, *args, **kwargs):
super().__init__(*args, **kwargs)
self.key_name = key_name
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return "(%s -> %%s)" % lhs, (*params, self.key_name)
class KeyTransformFactory:
def __init__(self, key_name):
self.key_name = key_name
def __call__(self, *args, **kwargs):
return KeyTransform(self.key_name, *args, **kwargs)
@HStoreField.register_lookup
class KeysTransform(Transform):
lookup_name = "keys"
function = "akeys"
output_field = ArrayField(TextField())
@HStoreField.register_lookup
class ValuesTransform(Transform):
lookup_name = "values"
function = "avals"
output_field = ArrayField(TextField())
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/postgres/fields/ranges.py | django/contrib/postgres/fields/ranges.py | import datetime
import json
from django.contrib.postgres import forms, lookups
from django.contrib.postgres.utils import CheckPostgresInstalledMixin
from django.db import models
from django.db.backends.postgresql.psycopg_any import (
DateRange,
DateTimeTZRange,
NumericRange,
Range,
)
from django.db.models.functions import Cast
from django.db.models.lookups import PostgresOperatorLookup
from .utils import AttributeSetter
__all__ = [
"RangeField",
"IntegerRangeField",
"BigIntegerRangeField",
"DecimalRangeField",
"DateTimeRangeField",
"DateRangeField",
"RangeBoundary",
"RangeOperators",
]
class RangeBoundary(models.Expression):
"""A class that represents range boundaries."""
def __init__(self, inclusive_lower=True, inclusive_upper=False):
self.lower = "[" if inclusive_lower else "("
self.upper = "]" if inclusive_upper else ")"
def as_sql(self, compiler, connection):
return "'%s%s'" % (self.lower, self.upper), []
class RangeOperators:
# https://www.postgresql.org/docs/current/functions-range.html#RANGE-OPERATORS-TABLE
EQUAL = "="
NOT_EQUAL = "<>"
CONTAINS = "@>"
CONTAINED_BY = "<@"
OVERLAPS = "&&"
FULLY_LT = "<<"
FULLY_GT = ">>"
NOT_LT = "&>"
NOT_GT = "&<"
ADJACENT_TO = "-|-"
class RangeField(CheckPostgresInstalledMixin, models.Field):
empty_strings_allowed = False
def __init__(self, *args, **kwargs):
if "default_bounds" in kwargs:
raise TypeError(
f"Cannot use 'default_bounds' with {self.__class__.__name__}."
)
# Initializing base_field here ensures that its model matches the model
# for self.
if hasattr(self, "base_field"):
self.base_field = self.base_field()
super().__init__(*args, **kwargs)
@property
def model(self):
try:
return self.__dict__["model"]
except KeyError:
raise AttributeError(
"'%s' object has no attribute 'model'" % self.__class__.__name__
)
@model.setter
def model(self, model):
self.__dict__["model"] = model
self.base_field.model = model
@classmethod
def _choices_is_value(cls, value):
return isinstance(value, (list, tuple)) or super()._choices_is_value(value)
def get_placeholder(self, value, compiler, connection):
return "%s::{}".format(self.db_type(connection))
def get_prep_value(self, value):
if value is None:
return None
elif isinstance(value, Range):
return value
elif isinstance(value, (list, tuple)):
return self.range_type(value[0], value[1])
return value
def to_python(self, value):
if isinstance(value, str):
# Assume we're deserializing
vals = json.loads(value)
for end in ("lower", "upper"):
if end in vals:
vals[end] = self.base_field.to_python(vals[end])
value = self.range_type(**vals)
elif isinstance(value, (list, tuple)):
value = self.range_type(value[0], value[1])
return value
def set_attributes_from_name(self, name):
super().set_attributes_from_name(name)
self.base_field.set_attributes_from_name(name)
def value_to_string(self, obj):
value = self.value_from_object(obj)
if value is None:
return None
if value.isempty:
return json.dumps({"empty": True})
base_field = self.base_field
result = {"bounds": value._bounds}
for end in ("lower", "upper"):
val = getattr(value, end)
if val is None:
result[end] = None
else:
obj = AttributeSetter(base_field.attname, val)
result[end] = base_field.value_to_string(obj)
return json.dumps(result)
def formfield(self, **kwargs):
kwargs.setdefault("form_class", self.form_field)
return super().formfield(**kwargs)
CANONICAL_RANGE_BOUNDS = "[)"
class ContinuousRangeField(RangeField):
"""
Continuous range field. It allows specifying default bounds for list and
tuple inputs.
"""
def __init__(self, *args, default_bounds=CANONICAL_RANGE_BOUNDS, **kwargs):
if default_bounds not in ("[)", "(]", "()", "[]"):
raise ValueError("default_bounds must be one of '[)', '(]', '()', or '[]'.")
self.default_bounds = default_bounds
super().__init__(*args, **kwargs)
def get_prep_value(self, value):
if isinstance(value, (list, tuple)):
return self.range_type(value[0], value[1], self.default_bounds)
return super().get_prep_value(value)
def formfield(self, **kwargs):
kwargs.setdefault("default_bounds", self.default_bounds)
return super().formfield(**kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if self.default_bounds and self.default_bounds != CANONICAL_RANGE_BOUNDS:
kwargs["default_bounds"] = self.default_bounds
return name, path, args, kwargs
class IntegerRangeField(RangeField):
base_field = models.IntegerField
range_type = NumericRange
form_field = forms.IntegerRangeField
def db_type(self, connection):
return "int4range"
class BigIntegerRangeField(RangeField):
base_field = models.BigIntegerField
range_type = NumericRange
form_field = forms.IntegerRangeField
def db_type(self, connection):
return "int8range"
class DecimalRangeField(ContinuousRangeField):
base_field = models.DecimalField
range_type = NumericRange
form_field = forms.DecimalRangeField
def db_type(self, connection):
return "numrange"
class DateTimeRangeField(ContinuousRangeField):
base_field = models.DateTimeField
range_type = DateTimeTZRange
form_field = forms.DateTimeRangeField
def db_type(self, connection):
return "tstzrange"
class DateRangeField(RangeField):
base_field = models.DateField
range_type = DateRange
form_field = forms.DateRangeField
def db_type(self, connection):
return "daterange"
class RangeContains(lookups.DataContains):
def get_prep_lookup(self):
if not isinstance(self.rhs, (list, tuple, Range)):
return Cast(self.rhs, self.lhs.field.base_field)
return super().get_prep_lookup()
RangeField.register_lookup(RangeContains)
RangeField.register_lookup(lookups.ContainedBy)
RangeField.register_lookup(lookups.Overlap)
class DateTimeRangeContains(PostgresOperatorLookup):
"""
Lookup for Date/DateTimeRange containment to cast the rhs to the correct
type.
"""
lookup_name = "contains"
postgres_operator = RangeOperators.CONTAINS
def process_rhs(self, compiler, connection):
# Transform rhs value for db lookup.
if isinstance(self.rhs, datetime.date):
value = models.Value(self.rhs)
self.rhs = value.resolve_expression(compiler.query)
return super().process_rhs(compiler, connection)
def as_postgresql(self, compiler, connection):
sql, params = super().as_postgresql(compiler, connection)
# Cast the rhs if needed.
cast_sql = ""
if (
isinstance(self.rhs, models.Expression)
and self.rhs._output_field_or_none
and
# Skip cast if rhs has a matching range type.
not isinstance(
self.rhs._output_field_or_none, self.lhs.output_field.__class__
)
):
cast_internal_type = self.lhs.output_field.base_field.get_internal_type()
cast_sql = "::{}".format(connection.data_types.get(cast_internal_type))
return "%s%s" % (sql, cast_sql), params
DateRangeField.register_lookup(DateTimeRangeContains)
DateTimeRangeField.register_lookup(DateTimeRangeContains)
class RangeContainedBy(PostgresOperatorLookup):
lookup_name = "contained_by"
type_mapping = {
"smallint": "int4range",
"integer": "int4range",
"bigint": "int8range",
"double precision": "numrange",
"numeric": "numrange",
"date": "daterange",
"timestamp with time zone": "tstzrange",
}
postgres_operator = RangeOperators.CONTAINED_BY
def process_rhs(self, compiler, connection):
rhs, rhs_params = super().process_rhs(compiler, connection)
# Ignore precision for DecimalFields.
db_type = self.lhs.output_field.cast_db_type(connection).split("(")[0]
cast_type = self.type_mapping[db_type]
return "%s::%s" % (rhs, cast_type), rhs_params
def process_lhs(self, compiler, connection):
lhs, lhs_params = super().process_lhs(compiler, connection)
if isinstance(self.lhs.output_field, models.FloatField):
lhs = "%s::numeric" % lhs
elif isinstance(self.lhs.output_field, models.SmallIntegerField):
lhs = "%s::integer" % lhs
return lhs, lhs_params
def get_prep_lookup(self):
return RangeField().get_prep_value(self.rhs)
models.DateField.register_lookup(RangeContainedBy)
models.DateTimeField.register_lookup(RangeContainedBy)
models.IntegerField.register_lookup(RangeContainedBy)
models.FloatField.register_lookup(RangeContainedBy)
models.DecimalField.register_lookup(RangeContainedBy)
@RangeField.register_lookup
class FullyLessThan(PostgresOperatorLookup):
lookup_name = "fully_lt"
postgres_operator = RangeOperators.FULLY_LT
@RangeField.register_lookup
class FullGreaterThan(PostgresOperatorLookup):
lookup_name = "fully_gt"
postgres_operator = RangeOperators.FULLY_GT
@RangeField.register_lookup
class NotLessThan(PostgresOperatorLookup):
lookup_name = "not_lt"
postgres_operator = RangeOperators.NOT_LT
@RangeField.register_lookup
class NotGreaterThan(PostgresOperatorLookup):
lookup_name = "not_gt"
postgres_operator = RangeOperators.NOT_GT
@RangeField.register_lookup
class AdjacentToLookup(PostgresOperatorLookup):
lookup_name = "adjacent_to"
postgres_operator = RangeOperators.ADJACENT_TO
@RangeField.register_lookup
class RangeStartsWith(models.Transform):
lookup_name = "startswith"
function = "lower"
@property
def output_field(self):
return self.lhs.output_field.base_field
@RangeField.register_lookup
class RangeEndsWith(models.Transform):
lookup_name = "endswith"
function = "upper"
@property
def output_field(self):
return self.lhs.output_field.base_field
@RangeField.register_lookup
class IsEmpty(models.Transform):
lookup_name = "isempty"
function = "isempty"
output_field = models.BooleanField()
@RangeField.register_lookup
class LowerInclusive(models.Transform):
lookup_name = "lower_inc"
function = "LOWER_INC"
output_field = models.BooleanField()
@RangeField.register_lookup
class LowerInfinite(models.Transform):
lookup_name = "lower_inf"
function = "LOWER_INF"
output_field = models.BooleanField()
@RangeField.register_lookup
class UpperInclusive(models.Transform):
lookup_name = "upper_inc"
function = "UPPER_INC"
output_field = models.BooleanField()
@RangeField.register_lookup
class UpperInfinite(models.Transform):
lookup_name = "upper_inf"
function = "UPPER_INF"
output_field = models.BooleanField()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/backends.py | django/contrib/auth/backends.py | from asgiref.sync import sync_to_async
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.db.models import Exists, OuterRef, Q
UserModel = get_user_model()
class BaseBackend:
def authenticate(self, request, **kwargs):
return None
async def aauthenticate(self, request, **kwargs):
return await sync_to_async(self.authenticate)(request, **kwargs)
def get_user(self, user_id):
return None
async def aget_user(self, user_id):
return await sync_to_async(self.get_user)(user_id)
def get_user_permissions(self, user_obj, obj=None):
return set()
async def aget_user_permissions(self, user_obj, obj=None):
return await sync_to_async(self.get_user_permissions)(user_obj, obj)
def get_group_permissions(self, user_obj, obj=None):
return set()
async def aget_group_permissions(self, user_obj, obj=None):
return await sync_to_async(self.get_group_permissions)(user_obj, obj)
def get_all_permissions(self, user_obj, obj=None):
return {
*self.get_user_permissions(user_obj, obj=obj),
*self.get_group_permissions(user_obj, obj=obj),
}
async def aget_all_permissions(self, user_obj, obj=None):
return {
*await self.aget_user_permissions(user_obj, obj=obj),
*await self.aget_group_permissions(user_obj, obj=obj),
}
def has_perm(self, user_obj, perm, obj=None):
return perm in self.get_all_permissions(user_obj, obj=obj)
async def ahas_perm(self, user_obj, perm, obj=None):
return perm in await self.aget_all_permissions(user_obj, obj)
class ModelBackend(BaseBackend):
"""
Authenticates against settings.AUTH_USER_MODEL.
"""
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if username is None or password is None:
return
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
async def aauthenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if username is None or password is None:
return
try:
user = await UserModel._default_manager.aget_by_natural_key(username)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if await user.acheck_password(password) and self.user_can_authenticate(
user
):
return user
def user_can_authenticate(self, user):
"""
Reject users with is_active=False. Custom user models that don't have
that attribute are allowed.
"""
return getattr(user, "is_active", True)
def _get_user_permissions(self, user_obj):
return user_obj.user_permissions.all()
def _get_group_permissions(self, user_obj):
return Permission.objects.filter(group__in=user_obj.groups.all())
def _get_permissions(self, user_obj, obj, from_name):
"""
Return the permissions of `user_obj` from `from_name`. `from_name` can
be either "group" or "user" to return permissions from
`_get_group_permissions` or `_get_user_permissions` respectively.
"""
if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
return set()
perm_cache_name = "_%s_perm_cache" % from_name
if not hasattr(user_obj, perm_cache_name):
if user_obj.is_superuser:
perms = Permission.objects.all()
else:
perms = getattr(self, "_get_%s_permissions" % from_name)(user_obj)
perms = perms.values_list("content_type__app_label", "codename").order_by()
setattr(
user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms}
)
return getattr(user_obj, perm_cache_name)
async def _aget_permissions(self, user_obj, obj, from_name):
"""See _get_permissions()."""
if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
return set()
perm_cache_name = "_%s_perm_cache" % from_name
if not hasattr(user_obj, perm_cache_name):
if user_obj.is_superuser:
perms = Permission.objects.all()
else:
perms = getattr(self, "_get_%s_permissions" % from_name)(user_obj)
perms = perms.values_list("content_type__app_label", "codename").order_by()
setattr(
user_obj,
perm_cache_name,
{"%s.%s" % (ct, name) async for ct, name in perms},
)
return getattr(user_obj, perm_cache_name)
def get_user_permissions(self, user_obj, obj=None):
"""
Return a set of permission strings the user `user_obj` has from their
`user_permissions`.
"""
return self._get_permissions(user_obj, obj, "user")
async def aget_user_permissions(self, user_obj, obj=None):
"""See get_user_permissions()."""
return await self._aget_permissions(user_obj, obj, "user")
def get_group_permissions(self, user_obj, obj=None):
"""
Return a set of permission strings the user `user_obj` has from the
groups they belong.
"""
return self._get_permissions(user_obj, obj, "group")
async def aget_group_permissions(self, user_obj, obj=None):
"""See get_group_permissions()."""
return await self._aget_permissions(user_obj, obj, "group")
def get_all_permissions(self, user_obj, obj=None):
if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
return set()
if not hasattr(user_obj, "_perm_cache"):
user_obj._perm_cache = super().get_all_permissions(user_obj)
return user_obj._perm_cache
def has_perm(self, user_obj, perm, obj=None):
return user_obj.is_active and super().has_perm(user_obj, perm, obj=obj)
async def ahas_perm(self, user_obj, perm, obj=None):
return user_obj.is_active and await super().ahas_perm(user_obj, perm, obj=obj)
def has_module_perms(self, user_obj, app_label):
"""
Return True if user_obj has any permissions in the given app_label.
"""
return user_obj.is_active and any(
perm[: perm.index(".")] == app_label
for perm in self.get_all_permissions(user_obj)
)
async def ahas_module_perms(self, user_obj, app_label):
"""See has_module_perms()"""
return user_obj.is_active and any(
perm[: perm.index(".")] == app_label
for perm in await self.aget_all_permissions(user_obj)
)
def with_perm(self, perm, is_active=True, include_superusers=True, obj=None):
"""
Return users that have permission "perm". By default, filter out
inactive users and include superusers.
"""
if isinstance(perm, str):
try:
app_label, codename = perm.split(".")
except ValueError:
raise ValueError(
"Permission name should be in the form "
"app_label.permission_codename."
)
elif not isinstance(perm, Permission):
raise TypeError(
"The `perm` argument must be a string or a permission instance."
)
if obj is not None:
return UserModel._default_manager.none()
permission_q = Q(group__user=OuterRef("pk")) | Q(user=OuterRef("pk"))
if isinstance(perm, Permission):
permission_q &= Q(pk=perm.pk)
else:
permission_q &= Q(codename=codename, content_type__app_label=app_label)
user_q = Exists(Permission.objects.filter(permission_q))
if include_superusers:
user_q |= Q(is_superuser=True)
if is_active is not None:
user_q &= Q(is_active=is_active)
return UserModel._default_manager.filter(user_q)
def get_user(self, user_id):
try:
user = UserModel._default_manager.get(pk=user_id)
except UserModel.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None
async def aget_user(self, user_id):
try:
user = await UserModel._default_manager.aget(pk=user_id)
except UserModel.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None
class AllowAllUsersModelBackend(ModelBackend):
def user_can_authenticate(self, user):
return True
class RemoteUserBackend(ModelBackend):
"""
This backend is to be used in conjunction with the ``RemoteUserMiddleware``
found in the middleware module of this package, and is used when the server
is handling authentication outside of Django.
By default, the ``authenticate`` method creates ``User`` objects for
usernames that don't already exist in the database. Subclasses can disable
this behavior by setting the ``create_unknown_user`` attribute to
``False``.
"""
# Create a User object if not already in the database?
create_unknown_user = True
def authenticate(self, request, remote_user):
"""
The username passed as ``remote_user`` is considered trusted. Return
the ``User`` object with the given username. Create a new ``User``
object if ``create_unknown_user`` is ``True``.
Return None if ``create_unknown_user`` is ``False`` and a ``User``
object with the given username is not found in the database.
"""
if not remote_user:
return
created = False
user = None
username = self.clean_username(remote_user)
# Note that this could be accomplished in one try-except clause, but
# instead we use get_or_create when creating unknown users since it has
# built-in safeguards for multiple threads.
if self.create_unknown_user:
user, created = UserModel._default_manager.get_or_create(
**{UserModel.USERNAME_FIELD: username}
)
else:
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
pass
user = self.configure_user(request, user, created=created)
return user if self.user_can_authenticate(user) else None
async def aauthenticate(self, request, remote_user):
"""See authenticate()."""
if not remote_user:
return
created = False
user = None
username = self.clean_username(remote_user)
# Note that this could be accomplished in one try-except clause, but
# instead we use get_or_create when creating unknown users since it has
# built-in safeguards for multiple threads.
if self.create_unknown_user:
user, created = await UserModel._default_manager.aget_or_create(
**{UserModel.USERNAME_FIELD: username}
)
else:
try:
user = await UserModel._default_manager.aget_by_natural_key(username)
except UserModel.DoesNotExist:
pass
user = await self.aconfigure_user(request, user, created=created)
return user if self.user_can_authenticate(user) else None
def clean_username(self, username):
"""
Perform any cleaning on the "username" prior to using it to get or
create the user object. Return the cleaned username.
By default, return the username unchanged.
"""
return username
def configure_user(self, request, user, created=True):
"""
Configure a user and return the updated user.
By default, return the user unmodified.
"""
return user
async def aconfigure_user(self, request, user, created=True):
"""See configure_user()"""
return await sync_to_async(self.configure_user)(request, user, created)
class AllowAllUsersRemoteUserBackend(RemoteUserBackend):
def user_can_authenticate(self, user):
return True
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/views.py | django/contrib/auth/views.py | from urllib.parse import urlsplit, urlunsplit
from django.conf import settings
# Avoid shadowing the login() and logout() views below.
from django.contrib.auth import REDIRECT_FIELD_NAME, get_user_model
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_not_required, login_required
from django.contrib.auth.forms import (
AuthenticationForm,
PasswordChangeForm,
PasswordResetForm,
SetPasswordForm,
)
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.http import HttpResponseRedirect, QueryDict
from django.shortcuts import resolve_url
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.utils.http import url_has_allowed_host_and_scheme, urlsafe_base64_decode
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
UserModel = get_user_model()
class RedirectURLMixin:
next_page = None
redirect_field_name = REDIRECT_FIELD_NAME
success_url_allowed_hosts = set()
def get_success_url(self):
return self.get_redirect_url() or self.get_default_redirect_url()
def get_redirect_url(self, request=None):
"""Return the user-originating redirect URL if it's safe.
Optionally takes a request argument, allowing use outside class-based
views.
"""
if request is None:
request = self.request
redirect_to = request.POST.get(
self.redirect_field_name, request.GET.get(self.redirect_field_name)
)
url_is_safe = url_has_allowed_host_and_scheme(
url=redirect_to,
allowed_hosts=self.get_success_url_allowed_hosts(request),
require_https=request.is_secure(),
)
return redirect_to if url_is_safe else ""
def get_success_url_allowed_hosts(self, request=None):
if request is None:
request = self.request
return {request.get_host(), *self.success_url_allowed_hosts}
def get_default_redirect_url(self):
"""Return the default redirect URL."""
if self.next_page:
return resolve_url(self.next_page)
raise ImproperlyConfigured("No URL to redirect to. Provide a next_page.")
@method_decorator(
[login_not_required, sensitive_post_parameters(), csrf_protect, never_cache],
name="dispatch",
)
class LoginView(RedirectURLMixin, FormView):
"""
Display the login form and handle the login action.
"""
form_class = AuthenticationForm
authentication_form = None
template_name = "registration/login.html"
redirect_authenticated_user = False
extra_context = None
def dispatch(self, request, *args, **kwargs):
if self.redirect_authenticated_user and self.request.user.is_authenticated:
redirect_to = self.get_success_url()
if redirect_to == self.request.path:
raise ValueError(
"Redirection loop for authenticated user detected. Check that "
"your LOGIN_REDIRECT_URL doesn't point to a login page."
)
return HttpResponseRedirect(redirect_to)
return super().dispatch(request, *args, **kwargs)
def get_default_redirect_url(self):
"""Return the default redirect URL."""
if self.next_page:
return resolve_url(self.next_page)
else:
return resolve_url(settings.LOGIN_REDIRECT_URL)
def get_form_class(self):
return self.authentication_form or self.form_class
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs["request"] = self.request
return kwargs
def form_valid(self, form):
"""Security check complete. Log the user in."""
auth_login(self.request, form.get_user())
return HttpResponseRedirect(self.get_success_url())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
current_site = get_current_site(self.request)
context.update(
{
self.redirect_field_name: self.get_redirect_url(),
"site": current_site,
"site_name": current_site.name,
**(self.extra_context or {}),
}
)
return context
@method_decorator([csrf_protect, never_cache], name="dispatch")
class LogoutView(RedirectURLMixin, TemplateView):
"""
Log out the user and display the 'You are logged out' message.
"""
http_method_names = ["post", "options"]
template_name = "registration/logged_out.html"
extra_context = None
def post(self, request, *args, **kwargs):
"""Logout may be done via POST."""
auth_logout(request)
redirect_to = self.get_success_url()
if redirect_to != request.get_full_path():
# Redirect to target page once the session has been cleared.
return HttpResponseRedirect(redirect_to)
return super().get(request, *args, **kwargs)
def get_default_redirect_url(self):
"""Return the default redirect URL."""
if self.next_page:
return resolve_url(self.next_page)
elif settings.LOGOUT_REDIRECT_URL:
return resolve_url(settings.LOGOUT_REDIRECT_URL)
else:
return self.request.path
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
current_site = get_current_site(self.request)
context.update(
{
"site": current_site,
"site_name": current_site.name,
"title": _("Logged out"),
"subtitle": None,
**(self.extra_context or {}),
}
)
return context
def logout_then_login(request, login_url=None):
"""
Log out the user if they are logged in. Then redirect to the login page.
"""
login_url = resolve_url(login_url or settings.LOGIN_URL)
return LogoutView.as_view(next_page=login_url)(request)
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirect the user to the login page, passing the given 'next' page.
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlsplit(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[3], mutable=True)
querystring[redirect_field_name] = next
login_url_parts[3] = querystring.urlencode(safe="/")
return HttpResponseRedirect(urlunsplit(login_url_parts))
# Class-based password reset views
# - PasswordResetView sends the mail
# - PasswordResetDoneView shows a success message for the above
# - PasswordResetConfirmView checks the link the user clicked and
# prompts for a new password
# - PasswordResetCompleteView shows a success message for the above
class PasswordContextMixin:
extra_context = None
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update(
{"title": self.title, "subtitle": None, **(self.extra_context or {})}
)
return context
@method_decorator([login_not_required, csrf_protect], name="dispatch")
class PasswordResetView(PasswordContextMixin, FormView):
email_template_name = "registration/password_reset_email.html"
extra_email_context = None
form_class = PasswordResetForm
from_email = None
html_email_template_name = None
subject_template_name = "registration/password_reset_subject.txt"
success_url = reverse_lazy("password_reset_done")
template_name = "registration/password_reset_form.html"
title = _("Password reset")
token_generator = default_token_generator
def form_valid(self, form):
opts = {
"use_https": self.request.is_secure(),
"token_generator": self.token_generator,
"from_email": self.from_email,
"email_template_name": self.email_template_name,
"subject_template_name": self.subject_template_name,
"request": self.request,
"html_email_template_name": self.html_email_template_name,
"extra_email_context": self.extra_email_context,
}
form.save(**opts)
return super().form_valid(form)
INTERNAL_RESET_SESSION_TOKEN = "_password_reset_token"
@method_decorator(login_not_required, name="dispatch")
class PasswordResetDoneView(PasswordContextMixin, TemplateView):
template_name = "registration/password_reset_done.html"
title = _("Password reset sent")
@method_decorator(
[login_not_required, sensitive_post_parameters(), never_cache], name="dispatch"
)
class PasswordResetConfirmView(PasswordContextMixin, FormView):
form_class = SetPasswordForm
post_reset_login = False
post_reset_login_backend = None
reset_url_token = "set-password"
success_url = reverse_lazy("password_reset_complete")
template_name = "registration/password_reset_confirm.html"
title = _("Enter new password")
token_generator = default_token_generator
def dispatch(self, *args, **kwargs):
if "uidb64" not in kwargs or "token" not in kwargs:
raise ImproperlyConfigured(
"The URL path must contain 'uidb64' and 'token' parameters."
)
self.validlink = False
self.user = self.get_user(kwargs["uidb64"])
if self.user is not None:
token = kwargs["token"]
if token == self.reset_url_token:
session_token = self.request.session.get(INTERNAL_RESET_SESSION_TOKEN)
if self.token_generator.check_token(self.user, session_token):
# If the token is valid, display the password reset form.
self.validlink = True
return super().dispatch(*args, **kwargs)
else:
if self.token_generator.check_token(self.user, token):
# Store the token in the session and redirect to the
# password reset form at a URL without the token. That
# avoids the possibility of leaking the token in the
# HTTP Referer header.
self.request.session[INTERNAL_RESET_SESSION_TOKEN] = token
redirect_url = self.request.path.replace(
token, self.reset_url_token
)
return HttpResponseRedirect(redirect_url)
# Display the "Password reset unsuccessful" page.
return self.render_to_response(self.get_context_data())
def get_user(self, uidb64):
try:
# urlsafe_base64_decode() decodes to bytestring
uid = urlsafe_base64_decode(uidb64).decode()
pk = UserModel._meta.pk.to_python(uid)
user = UserModel._default_manager.get(pk=pk)
except (
TypeError,
ValueError,
OverflowError,
UserModel.DoesNotExist,
ValidationError,
):
user = None
return user
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs["user"] = self.user
return kwargs
def form_valid(self, form):
user = form.save()
del self.request.session[INTERNAL_RESET_SESSION_TOKEN]
if self.post_reset_login:
auth_login(self.request, user, self.post_reset_login_backend)
return super().form_valid(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.validlink:
context["validlink"] = True
else:
context.update(
{
"form": None,
"title": _("Password reset unsuccessful"),
"validlink": False,
}
)
return context
@method_decorator(login_not_required, name="dispatch")
class PasswordResetCompleteView(PasswordContextMixin, TemplateView):
template_name = "registration/password_reset_complete.html"
title = _("Password reset complete")
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["login_url"] = resolve_url(settings.LOGIN_URL)
return context
@method_decorator(
[sensitive_post_parameters(), csrf_protect, login_required], name="dispatch"
)
class PasswordChangeView(PasswordContextMixin, FormView):
form_class = PasswordChangeForm
success_url = reverse_lazy("password_change_done")
template_name = "registration/password_change_form.html"
title = _("Password change")
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs["user"] = self.request.user
return kwargs
def form_valid(self, form):
form.save()
# Updating the password logs out all other sessions for the user
# except the current one.
update_session_auth_hash(self.request, form.user)
return super().form_valid(form)
@method_decorator(login_required, name="dispatch")
class PasswordChangeDoneView(PasswordContextMixin, TemplateView):
template_name = "registration/password_change_done.html"
title = _("Password change successful")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/admin.py | django/contrib/auth/admin.py | from django.conf import settings
from django.contrib import admin, messages
from django.contrib.admin.options import IS_POPUP_VAR
from django.contrib.admin.utils import unquote
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import (
AdminPasswordChangeForm,
AdminUserCreationForm,
UserChangeForm,
)
from django.contrib.auth.models import Group, User
from django.core.exceptions import PermissionDenied
from django.db import router, transaction
from django.http import Http404, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.urls import path, reverse
from django.utils.decorators import method_decorator
from django.utils.html import escape
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
@admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
search_fields = ("name",)
ordering = ("name",)
filter_horizontal = ("permissions",)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if db_field.name == "permissions":
qs = kwargs.get("queryset", db_field.remote_field.model.objects)
# Avoid a major performance hit resolving permission names which
# triggers a content_type load:
kwargs["queryset"] = qs.select_related("content_type")
return super().formfield_for_manytomany(db_field, request=request, **kwargs)
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
add_form_template = "admin/auth/user/add_form.html"
change_user_password_template = None
fieldsets = (
(None, {"fields": ("username", "password")}),
(_("Personal info"), {"fields": ("first_name", "last_name", "email")}),
(
_("Permissions"),
{
"fields": (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
),
},
),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
)
add_fieldsets = (
(
None,
{
"classes": ("wide",),
"fields": ("username", "usable_password", "password1", "password2"),
},
),
)
form = UserChangeForm
add_form = AdminUserCreationForm
change_password_form = AdminPasswordChangeForm
list_display = ("username", "email", "first_name", "last_name", "is_staff")
list_filter = ("is_staff", "is_superuser", "is_active", "groups")
search_fields = ("username", "first_name", "last_name", "email")
ordering = ("username",)
filter_horizontal = (
"groups",
"user_permissions",
)
def get_fieldsets(self, request, obj=None):
if not obj:
return self.add_fieldsets
return super().get_fieldsets(request, obj)
def get_form(self, request, obj=None, **kwargs):
"""
Use special form during user creation
"""
defaults = {}
if obj is None:
defaults["form"] = self.add_form
defaults.update(kwargs)
return super().get_form(request, obj, **defaults)
def get_urls(self):
return [
path(
"<id>/password/",
self.admin_site.admin_view(self.user_change_password),
name="auth_user_password_change",
),
*super().get_urls(),
]
def lookup_allowed(self, lookup, value, request):
# Don't allow lookups involving passwords.
return not lookup.startswith("password") and super().lookup_allowed(
lookup, value, request
)
@method_decorator([sensitive_post_parameters(), csrf_protect])
def add_view(self, request, form_url="", extra_context=None):
if request.method in ("GET", "HEAD", "OPTIONS", "TRACE"):
return self._add_view(request, form_url, extra_context)
with transaction.atomic(using=router.db_for_write(self.model)):
return self._add_view(request, form_url, extra_context)
def _add_view(self, request, form_url="", extra_context=None):
# It's an error for a user to have add permission but NOT change
# permission for users. If we allowed such users to add users, they
# could create superusers, which would mean they would essentially have
# the permission to change users. To avoid the problem entirely, we
# disallow users from adding users if they don't have change
# permission.
if not self.has_change_permission(request):
if self.has_add_permission(request) and settings.DEBUG:
# Raise Http404 in debug mode so that the user gets a helpful
# error message.
raise Http404(
'Your user does not have the "Change user" permission. In '
"order to add users, Django requires that your user "
'account have both the "Add user" and "Change user" '
"permissions set."
)
raise PermissionDenied
if extra_context is None:
extra_context = {}
username_field = self.opts.get_field(self.model.USERNAME_FIELD)
defaults = {
"auto_populated_fields": (),
"username_help_text": username_field.help_text,
}
extra_context.update(defaults)
return super().add_view(request, form_url, extra_context)
@method_decorator(sensitive_post_parameters())
def user_change_password(self, request, id, form_url=""):
user = self.get_object(request, unquote(id))
if not self.has_change_permission(request, user):
raise PermissionDenied
if user is None:
raise Http404(
_("%(name)s object with primary key %(key)r does not exist.")
% {
"name": self.opts.verbose_name,
"key": escape(id),
}
)
if request.method == "POST":
form = self.change_password_form(user, request.POST)
if form.is_valid():
# If disabling password-based authentication was requested
# (via the form field `usable_password`), the submit action
# must be "unset-password". This check is most relevant when
# the admin user has two submit buttons available (for example
# when Javascript is disabled).
valid_submission = (
form.cleaned_data["set_usable_password"]
or "unset-password" in request.POST
)
if not valid_submission:
msg = gettext("Conflicting form data submitted. Please try again.")
messages.error(request, msg)
return HttpResponseRedirect(request.get_full_path())
user = form.save()
change_message = self.construct_change_message(request, form, None)
self.log_change(request, user, change_message)
if user.has_usable_password():
msg = gettext("Password changed successfully.")
else:
msg = gettext("Password-based authentication was disabled.")
messages.success(request, msg)
update_session_auth_hash(request, form.user)
return HttpResponseRedirect(
reverse(
"%s:%s_%s_change"
% (
self.admin_site.name,
user._meta.app_label,
user._meta.model_name,
),
args=(user.pk,),
)
)
else:
form = self.change_password_form(user)
fieldsets = [(None, {"fields": list(form.base_fields)})]
admin_form = admin.helpers.AdminForm(form, fieldsets, {})
if user.has_usable_password():
title = _("Change password: %s")
else:
title = _("Set password: %s")
context = {
"title": title % escape(user.get_username()),
"adminForm": admin_form,
"form_url": form_url,
"form": form,
"is_popup": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET),
"is_popup_var": IS_POPUP_VAR,
"add": True,
"change": False,
"has_delete_permission": False,
"has_change_permission": True,
"has_absolute_url": False,
"opts": self.opts,
"original": user,
"save_as": False,
"show_save": True,
**self.admin_site.each_context(request),
}
request.current_app = self.admin_site.name
return TemplateResponse(
request,
self.change_user_password_template
or "admin/auth/user/change_password.html",
context,
)
def response_add(self, request, obj, post_url_continue=None):
"""
Determine the HttpResponse for the add_view stage. It mostly defers to
its superclass implementation but is customized because the User model
has a slightly different workflow.
"""
# We should allow further modification of the user just added i.e. the
# 'Save' button should behave like the 'Save and continue editing'
# button except in two scenarios:
# * The user has pressed the 'Save and add another' button
# * We are adding a user in a popup
if "_addanother" not in request.POST and IS_POPUP_VAR not in request.POST:
request.POST = request.POST.copy()
request.POST["_continue"] = 1
return super().response_add(request, obj, post_url_continue)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/middleware.py | django/contrib/auth/middleware.py | from functools import partial
from urllib.parse import urlsplit
from asgiref.sync import iscoroutinefunction, markcoroutinefunction
from django.conf import settings
from django.contrib import auth
from django.contrib.auth import REDIRECT_FIELD_NAME, load_backend
from django.contrib.auth.backends import RemoteUserBackend
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import resolve_url
from django.utils.deprecation import MiddlewareMixin
from django.utils.functional import SimpleLazyObject
def get_user(request):
if not hasattr(request, "_cached_user"):
request._cached_user = auth.get_user(request)
return request._cached_user
async def auser(request):
if not hasattr(request, "_acached_user"):
request._acached_user = await auth.aget_user(request)
return request._acached_user
class AuthenticationMiddleware(MiddlewareMixin):
def process_request(self, request):
if not hasattr(request, "session"):
raise ImproperlyConfigured(
"The Django authentication middleware requires session "
"middleware to be installed. Edit your MIDDLEWARE setting to "
"insert "
"'django.contrib.sessions.middleware.SessionMiddleware' before "
"'django.contrib.auth.middleware.AuthenticationMiddleware'."
)
request.user = SimpleLazyObject(lambda: get_user(request))
request.auser = partial(auser, request)
class LoginRequiredMiddleware(MiddlewareMixin):
"""
Middleware that redirects all unauthenticated requests to a login page.
Views using the login_not_required decorator will not be redirected.
"""
redirect_field_name = REDIRECT_FIELD_NAME
def process_view(self, request, view_func, view_args, view_kwargs):
if not getattr(view_func, "login_required", True):
return None
if request.user.is_authenticated:
return None
return self.handle_no_permission(request, view_func)
def get_login_url(self, view_func):
login_url = getattr(view_func, "login_url", None) or settings.LOGIN_URL
if not login_url:
raise ImproperlyConfigured(
"No login URL to redirect to. Define settings.LOGIN_URL or "
"provide a login_url via the 'django.contrib.auth.decorators."
"login_required' decorator."
)
return str(login_url)
def get_redirect_field_name(self, view_func):
return getattr(view_func, "redirect_field_name", self.redirect_field_name)
def handle_no_permission(self, request, view_func):
path = request.build_absolute_uri()
resolved_login_url = resolve_url(self.get_login_url(view_func))
# If the login url is the same scheme and net location then use the
# path as the "next" url.
login_scheme, login_netloc = urlsplit(resolved_login_url)[:2]
current_scheme, current_netloc = urlsplit(path)[:2]
if (not login_scheme or login_scheme == current_scheme) and (
not login_netloc or login_netloc == current_netloc
):
path = request.get_full_path()
return redirect_to_login(
path,
resolved_login_url,
self.get_redirect_field_name(view_func),
)
class RemoteUserMiddleware:
"""
Middleware for utilizing web-server-provided authentication.
If request.user is not authenticated, then this middleware attempts to
authenticate the username from the ``REMOTE_USER`` key in ``request.META``,
an environment variable commonly set by the webserver.
If authentication is successful, the user is automatically logged in to
persist the user in the session.
The ``request.META`` key is configurable and defaults to ``REMOTE_USER``.
Subclass this class and change the ``header`` attribute if you need to
use a different key from ``request.META``, for example a HTTP request
header.
"""
sync_capable = True
async_capable = True
def __init__(self, get_response):
if get_response is None:
raise ValueError("get_response must be provided.")
self.get_response = get_response
self.is_async = iscoroutinefunction(get_response)
if self.is_async:
markcoroutinefunction(self)
super().__init__()
# Name of request.META key to grab username from. Note that for
# request headers, normalization to all uppercase and the addition
# of a "HTTP_" prefix apply.
header = "REMOTE_USER"
force_logout_if_no_header = True
def __call__(self, request):
if self.is_async:
return self.__acall__(request)
self.process_request(request)
return self.get_response(request)
def process_request(self, request):
# AuthenticationMiddleware is required so that request.user exists.
if not hasattr(request, "user"):
raise ImproperlyConfigured(
"The Django remote user auth middleware requires the"
" authentication middleware to be installed. Edit your"
" MIDDLEWARE setting to insert"
" 'django.contrib.auth.middleware.AuthenticationMiddleware'"
" before the RemoteUserMiddleware class."
)
try:
username = request.META[self.header]
except KeyError:
# If specified header doesn't exist then remove any existing
# authenticated remote-user, or return (leaving request.user set to
# AnonymousUser by the AuthenticationMiddleware).
if self.force_logout_if_no_header and request.user.is_authenticated:
self._remove_invalid_user(request)
return
# If the user is already authenticated and that user is the user we are
# getting passed in the headers, then the correct user is already
# persisted in the session and we don't need to continue.
if request.user.is_authenticated:
if request.user.get_username() == self.clean_username(username, request):
return
else:
# An authenticated user is associated with the request, but
# it does not match the authorized user in the header.
self._remove_invalid_user(request)
# We are seeing this user for the first time in this session, attempt
# to authenticate the user.
user = auth.authenticate(request, remote_user=username)
if user:
# User is valid. Set request.user and persist user in the session
# by logging the user in.
request.user = user
auth.login(request, user)
async def __acall__(self, request):
await self.aprocess_request(request)
return await self.get_response(request)
async def aprocess_request(self, request):
# AuthenticationMiddleware is required so that request.user exists.
if not hasattr(request, "user"):
raise ImproperlyConfigured(
"The Django remote user auth middleware requires the"
" authentication middleware to be installed. Edit your"
" MIDDLEWARE setting to insert"
" 'django.contrib.auth.middleware.AuthenticationMiddleware'"
" before the RemoteUserMiddleware class."
)
try:
username = request.META["HTTP_" + self.header]
except KeyError:
# If specified header doesn't exist then remove any existing
# authenticated remote-user, or return (leaving request.user set to
# AnonymousUser by the AuthenticationMiddleware).
if self.force_logout_if_no_header:
user = await request.auser()
if user.is_authenticated:
await self._aremove_invalid_user(request)
return
user = await request.auser()
# If the user is already authenticated and that user is the user we are
# getting passed in the headers, then the correct user is already
# persisted in the session and we don't need to continue.
if user.is_authenticated:
if user.get_username() == self.clean_username(username, request):
return
else:
# An authenticated user is associated with the request, but
# it does not match the authorized user in the header.
await self._aremove_invalid_user(request)
# We are seeing this user for the first time in this session, attempt
# to authenticate the user.
user = await auth.aauthenticate(request, remote_user=username)
if user:
# User is valid. Set request.user and persist user in the session
# by logging the user in.
request.user = user
await auth.alogin(request, user)
def clean_username(self, username, request):
"""
Allow the backend to clean the username, if the backend defines a
clean_username method.
"""
backend_str = request.session[auth.BACKEND_SESSION_KEY]
backend = auth.load_backend(backend_str)
try:
username = backend.clean_username(username)
except AttributeError: # Backend has no clean_username method.
pass
return username
def _remove_invalid_user(self, request):
"""
Remove the current authenticated user in the request which is invalid
but only if the user is authenticated via the RemoteUserBackend.
"""
try:
stored_backend = load_backend(
request.session.get(auth.BACKEND_SESSION_KEY, "")
)
except ImportError:
# backend failed to load
auth.logout(request)
else:
if isinstance(stored_backend, RemoteUserBackend):
auth.logout(request)
async def _aremove_invalid_user(self, request):
"""
Remove the current authenticated user in the request which is invalid
but only if the user is authenticated via the RemoteUserBackend.
"""
try:
stored_backend = load_backend(
await request.session.aget(auth.BACKEND_SESSION_KEY, "")
)
except ImportError:
# Backend failed to load.
await auth.alogout(request)
else:
if isinstance(stored_backend, RemoteUserBackend):
await auth.alogout(request)
class PersistentRemoteUserMiddleware(RemoteUserMiddleware):
"""
Middleware for web-server provided authentication on logon pages.
Like RemoteUserMiddleware but keeps the user authenticated even if
the ``request.META`` key is not found in the request. Useful for
setups when the external authentication is only expected to happen
on some "logon" URL and the rest of the application wants to use
Django's authentication mechanism.
"""
force_logout_if_no_header = False
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/mixins.py | django/contrib/auth/mixins.py | from urllib.parse import urlsplit
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.shortcuts import resolve_url
class AccessMixin:
"""
Abstract CBV mixin that gives access mixins the same customizable
functionality.
"""
login_url = None
permission_denied_message = ""
raise_exception = False
redirect_field_name = REDIRECT_FIELD_NAME
def get_login_url(self):
"""
Override this method to override the login_url attribute.
"""
login_url = self.login_url or settings.LOGIN_URL
if not login_url:
raise ImproperlyConfigured(
f"{self.__class__.__name__} is missing the login_url attribute. Define "
f"{self.__class__.__name__}.login_url, settings.LOGIN_URL, or override "
f"{self.__class__.__name__}.get_login_url()."
)
return str(login_url)
def get_permission_denied_message(self):
"""
Override this method to override the permission_denied_message
attribute.
"""
return self.permission_denied_message
def get_redirect_field_name(self):
"""
Override this method to override the redirect_field_name attribute.
"""
return self.redirect_field_name
def handle_no_permission(self):
if self.raise_exception or self.request.user.is_authenticated:
raise PermissionDenied(self.get_permission_denied_message())
path = self.request.build_absolute_uri()
resolved_login_url = resolve_url(self.get_login_url())
# If the login url is the same scheme and net location then use the
# path as the "next" url.
login_scheme, login_netloc = urlsplit(resolved_login_url)[:2]
current_scheme, current_netloc = urlsplit(path)[:2]
if (not login_scheme or login_scheme == current_scheme) and (
not login_netloc or login_netloc == current_netloc
):
path = self.request.get_full_path()
return redirect_to_login(
path,
resolved_login_url,
self.get_redirect_field_name(),
)
class LoginRequiredMixin(AccessMixin):
"""Verify that the current user is authenticated."""
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs)
class PermissionRequiredMixin(AccessMixin):
"""Verify that the current user has all specified permissions."""
permission_required = None
def get_permission_required(self):
"""
Override this method to override the permission_required attribute.
Must return an iterable.
"""
if self.permission_required is None:
raise ImproperlyConfigured(
f"{self.__class__.__name__} is missing the "
f"permission_required attribute. Define "
f"{self.__class__.__name__}.permission_required, or override "
f"{self.__class__.__name__}.get_permission_required()."
)
if isinstance(self.permission_required, str):
perms = (self.permission_required,)
else:
perms = self.permission_required
return perms
def has_permission(self):
"""
Override this method to customize the way permissions are checked.
"""
perms = self.get_permission_required()
return self.request.user.has_perms(perms)
def dispatch(self, request, *args, **kwargs):
if not self.has_permission():
return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs)
class UserPassesTestMixin(AccessMixin):
"""
Deny a request with a permission error if the test_func() method returns
False.
"""
def test_func(self):
raise NotImplementedError(
"{} is missing the implementation of the test_func() method.".format(
self.__class__.__name__
)
)
def get_test_func(self):
"""
Override this method to use a different test_func method.
"""
return self.test_func
def dispatch(self, request, *args, **kwargs):
user_test_result = self.get_test_func()()
if not user_test_result:
return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/checks.py | django/contrib/auth/checks.py | from itertools import chain
from django.apps import apps
from django.conf import settings
from django.core import checks
from django.utils.module_loading import import_string
from .management import _get_builtin_permissions
def _subclass_index(class_path, candidate_paths):
"""
Return the index of dotted class path (or a subclass of that class) in a
list of candidate paths. If it does not exist, return -1.
"""
cls = import_string(class_path)
for index, path in enumerate(candidate_paths):
try:
candidate_cls = import_string(path)
if issubclass(candidate_cls, cls):
return index
except (ImportError, TypeError):
continue
return -1
def check_user_model(app_configs, **kwargs):
if app_configs is None:
cls = apps.get_model(settings.AUTH_USER_MODEL)
else:
app_label, model_name = settings.AUTH_USER_MODEL.split(".")
for app_config in app_configs:
if app_config.label == app_label:
cls = app_config.get_model(model_name)
break
else:
# Checks might be run against a set of app configs that don't
# include the specified user model. In this case we simply don't
# perform the checks defined below.
return []
errors = []
# Check that REQUIRED_FIELDS is a list
if not isinstance(cls.REQUIRED_FIELDS, (list, tuple)):
errors.append(
checks.Error(
"'REQUIRED_FIELDS' must be a list or tuple.",
obj=cls,
id="auth.E001",
)
)
# Check that the USERNAME FIELD isn't included in REQUIRED_FIELDS.
if cls.USERNAME_FIELD in cls.REQUIRED_FIELDS:
errors.append(
checks.Error(
"The field named as the 'USERNAME_FIELD' "
"for a custom user model must not be included in 'REQUIRED_FIELDS'.",
hint=(
"The 'USERNAME_FIELD' is currently set to '%s', you "
"should remove '%s' from the 'REQUIRED_FIELDS'."
% (cls.USERNAME_FIELD, cls.USERNAME_FIELD)
),
obj=cls,
id="auth.E002",
)
)
# Check that the username field is unique
if not cls._meta.get_field(cls.USERNAME_FIELD).unique and not any(
constraint.fields == (cls.USERNAME_FIELD,)
for constraint in cls._meta.total_unique_constraints
):
if settings.AUTHENTICATION_BACKENDS == [
"django.contrib.auth.backends.ModelBackend"
]:
errors.append(
checks.Error(
"'%s.%s' must be unique because it is named as the "
"'USERNAME_FIELD'." % (cls._meta.object_name, cls.USERNAME_FIELD),
obj=cls,
id="auth.E003",
)
)
else:
errors.append(
checks.Warning(
"'%s.%s' is named as the 'USERNAME_FIELD', but it is not unique."
% (cls._meta.object_name, cls.USERNAME_FIELD),
hint=(
"Ensure that your authentication backend(s) can handle "
"non-unique usernames."
),
obj=cls,
id="auth.W004",
)
)
if callable(cls().is_anonymous):
errors.append(
checks.Critical(
"%s.is_anonymous must be an attribute or property rather than "
"a method. Ignoring this is a security issue as anonymous "
"users will be treated as authenticated!" % cls,
obj=cls,
id="auth.C009",
)
)
if callable(cls().is_authenticated):
errors.append(
checks.Critical(
"%s.is_authenticated must be an attribute or property rather "
"than a method. Ignoring this is a security issue as anonymous "
"users will be treated as authenticated!" % cls,
obj=cls,
id="auth.C010",
)
)
return errors
def check_models_permissions(app_configs, **kwargs):
if app_configs is None:
models = apps.get_models()
else:
models = chain.from_iterable(
app_config.get_models() for app_config in app_configs
)
Permission = apps.get_model("auth", "Permission")
permission_name_max_length = Permission._meta.get_field("name").max_length
permission_codename_max_length = Permission._meta.get_field("codename").max_length
errors = []
for model in models:
opts = model._meta
builtin_permissions = dict(_get_builtin_permissions(opts))
# Check builtin permission name length.
max_builtin_permission_name_length = (
max(len(name) for name in builtin_permissions.values())
if builtin_permissions
else 0
)
if max_builtin_permission_name_length > permission_name_max_length:
verbose_name_max_length = permission_name_max_length - (
max_builtin_permission_name_length - len(opts.verbose_name_raw)
)
errors.append(
checks.Error(
"The verbose_name of model '%s' must be at most %d "
"characters for its builtin permission names to be at "
"most %d characters."
% (opts.label, verbose_name_max_length, permission_name_max_length),
obj=model,
id="auth.E007",
)
)
# Check builtin permission codename length.
max_builtin_permission_codename_length = (
max(len(codename) for codename in builtin_permissions.keys())
if builtin_permissions
else 0
)
if max_builtin_permission_codename_length > permission_codename_max_length:
model_name_max_length = permission_codename_max_length - (
max_builtin_permission_codename_length - len(opts.model_name)
)
errors.append(
checks.Error(
"The name of model '%s' must be at most %d characters "
"for its builtin permission codenames to be at most %d "
"characters."
% (
opts.label,
model_name_max_length,
permission_codename_max_length,
),
obj=model,
id="auth.E011",
)
)
codenames = set()
for codename, name in opts.permissions:
# Check custom permission name length.
if len(name) > permission_name_max_length:
errors.append(
checks.Error(
"The permission named '%s' of model '%s' is longer "
"than %d characters."
% (
name,
opts.label,
permission_name_max_length,
),
obj=model,
id="auth.E008",
)
)
# Check custom permission codename length.
if len(codename) > permission_codename_max_length:
errors.append(
checks.Error(
"The permission codenamed '%s' of model '%s' is "
"longer than %d characters."
% (
codename,
opts.label,
permission_codename_max_length,
),
obj=model,
id="auth.E012",
)
)
# Check custom permissions codename clashing.
if codename in builtin_permissions:
errors.append(
checks.Error(
"The permission codenamed '%s' clashes with a builtin "
"permission for model '%s'." % (codename, opts.label),
obj=model,
id="auth.E005",
)
)
elif codename in codenames:
errors.append(
checks.Error(
"The permission codenamed '%s' is duplicated for "
"model '%s'." % (codename, opts.label),
obj=model,
id="auth.E006",
)
)
codenames.add(codename)
return errors
def check_middleware(app_configs, **kwargs):
errors = []
login_required_index = _subclass_index(
"django.contrib.auth.middleware.LoginRequiredMiddleware",
settings.MIDDLEWARE,
)
if login_required_index != -1:
auth_index = _subclass_index(
"django.contrib.auth.middleware.AuthenticationMiddleware",
settings.MIDDLEWARE,
)
if auth_index == -1 or auth_index > login_required_index:
errors.append(
checks.Error(
"In order to use django.contrib.auth.middleware."
"LoginRequiredMiddleware, django.contrib.auth.middleware."
"AuthenticationMiddleware must be defined before it in MIDDLEWARE.",
id="auth.E013",
)
)
return errors
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/models.py | django/contrib/auth/models.py | from collections.abc import Iterable
from django.apps import apps
from django.contrib import auth
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.hashers import make_password
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.core.mail import send_mail
from django.db import models
from django.db.models.manager import EmptyManager
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from .validators import UnicodeUsernameValidator
def update_last_login(sender, user, **kwargs):
"""
A signal receiver which updates the last_login date for
the user logging in.
"""
user.last_login = timezone.now()
user.save(update_fields=["last_login"])
class PermissionManager(models.Manager):
use_in_migrations = True
def get_by_natural_key(self, codename, app_label, model):
return self.get(
codename=codename,
content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(
app_label, model
),
)
class Permission(models.Model):
"""
The permissions system provides a way to assign permissions to specific
users and groups of users.
The permission system is used by the Django admin site, but may also be
useful in your own code. The Django admin site uses permissions as follows:
- The "add" permission limits the user's ability to view the "add" form
and add an object.
- The "change" permission limits a user's ability to view the change
list, view the "change" form and change an object.
- The "delete" permission limits the ability to delete an object.
- The "view" permission limits the ability to view an object.
Permissions are set globally per type of object, not per specific object
instance. It is possible to say "Mary may change news stories," but it's
not currently possible to say "Mary may change news stories, but only the
ones she created herself" or "Mary may only change news stories that have a
certain status or publication date."
The permissions listed above are automatically created for each model.
"""
name = models.CharField(_("name"), max_length=255)
content_type = models.ForeignKey(
ContentType,
models.CASCADE,
verbose_name=_("content type"),
)
codename = models.CharField(_("codename"), max_length=100)
objects = PermissionManager()
class Meta:
verbose_name = _("permission")
verbose_name_plural = _("permissions")
unique_together = [["content_type", "codename"]]
ordering = ["content_type__app_label", "content_type__model", "codename"]
def __str__(self):
return "%s | %s" % (self.content_type, self.name)
def natural_key(self):
return (self.codename, *self.content_type.natural_key())
natural_key.dependencies = ["contenttypes.contenttype"]
class GroupManager(models.Manager):
"""
The manager for the auth's Group model.
"""
use_in_migrations = True
def get_by_natural_key(self, name):
return self.get(name=name)
async def aget_by_natural_key(self, name):
return await self.aget(name=name)
class Group(models.Model):
"""
Groups are a generic way of categorizing users to apply permissions, or
some other label, to those users. A user can belong to any number of
groups.
A user in a group automatically has all the permissions granted to that
group. For example, if the group 'Site editors' has the permission
can_edit_home_page, any user in that group will have that permission.
Beyond permissions, groups are a convenient way to categorize users to
apply some label, or extended functionality, to them. For example, you
could create a group 'Special users', and you could write code that would
do special things to those users -- such as giving them access to a
members-only portion of your site, or sending them members-only email
messages.
"""
name = models.CharField(_("name"), max_length=150, unique=True)
permissions = models.ManyToManyField(
Permission,
verbose_name=_("permissions"),
blank=True,
)
objects = GroupManager()
class Meta:
verbose_name = _("group")
verbose_name_plural = _("groups")
def __str__(self):
return self.name
def natural_key(self):
return (self.name,)
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user_object(self, username, email, password, **extra_fields):
if not username:
raise ValueError("The given username must be set")
email = self.normalize_email(email)
# Lookup the real model class from the global app registry so this
# manager method can be used in migrations. This is fine because
# managers are by definition working on the real model.
GlobalUserModel = apps.get_model(
self.model._meta.app_label, self.model._meta.object_name
)
username = GlobalUserModel.normalize_username(username)
user = self.model(username=username, email=email, **extra_fields)
user.password = make_password(password)
return user
def _create_user(self, username, email, password, **extra_fields):
"""
Create and save a user with the given username, email, and password.
"""
user = self._create_user_object(username, email, password, **extra_fields)
user.save(using=self._db)
return user
async def _acreate_user(self, username, email, password, **extra_fields):
"""See _create_user()"""
user = self._create_user_object(username, email, password, **extra_fields)
await user.asave(using=self._db)
return user
def create_user(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False)
return self._create_user(username, email, password, **extra_fields)
create_user.alters_data = True
async def acreate_user(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False)
return await self._acreate_user(username, email, password, **extra_fields)
acreate_user.alters_data = True
def create_superuser(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return self._create_user(username, email, password, **extra_fields)
create_superuser.alters_data = True
async def acreate_superuser(
self, username, email=None, password=None, **extra_fields
):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return await self._acreate_user(username, email, password, **extra_fields)
acreate_superuser.alters_data = True
def with_perm(
self, perm, is_active=True, include_superusers=True, backend=None, obj=None
):
if backend is None:
backends = auth.get_backends()
if len(backends) == 1:
backend = backends[0]
else:
raise ValueError(
"You have multiple authentication backends configured and "
"therefore must provide the `backend` argument."
)
elif not isinstance(backend, str):
raise TypeError(
"backend must be a dotted import path string (got %r)." % backend
)
else:
backend = auth.load_backend(backend)
if hasattr(backend, "with_perm"):
return backend.with_perm(
perm,
is_active=is_active,
include_superusers=include_superusers,
obj=obj,
)
return self.none()
# A few helper functions for common logic between User and AnonymousUser.
def _user_get_permissions(user, obj, from_name):
permissions = set()
name = "get_%s_permissions" % from_name
for backend in auth.get_backends():
if hasattr(backend, name):
permissions.update(getattr(backend, name)(user, obj))
return permissions
async def _auser_get_permissions(user, obj, from_name):
permissions = set()
name = "aget_%s_permissions" % from_name
for backend in auth.get_backends():
if hasattr(backend, name):
permissions.update(await getattr(backend, name)(user, obj))
return permissions
def _user_has_perm(user, perm, obj):
"""
A backend can raise `PermissionDenied` to short-circuit permission checks.
"""
for backend in auth.get_backends():
if not hasattr(backend, "has_perm"):
continue
try:
if backend.has_perm(user, perm, obj):
return True
except PermissionDenied:
return False
return False
async def _auser_has_perm(user, perm, obj):
"""See _user_has_perm()"""
for backend in auth.get_backends():
if not hasattr(backend, "ahas_perm"):
continue
try:
if await backend.ahas_perm(user, perm, obj):
return True
except PermissionDenied:
return False
return False
def _user_has_module_perms(user, app_label):
"""
A backend can raise `PermissionDenied` to short-circuit permission checks.
"""
for backend in auth.get_backends():
if not hasattr(backend, "has_module_perms"):
continue
try:
if backend.has_module_perms(user, app_label):
return True
except PermissionDenied:
return False
return False
async def _auser_has_module_perms(user, app_label):
"""See _user_has_module_perms()"""
for backend in auth.get_backends():
if not hasattr(backend, "ahas_module_perms"):
continue
try:
if await backend.ahas_module_perms(user, app_label):
return True
except PermissionDenied:
return False
return False
class PermissionsMixin(models.Model):
"""
Add the fields and methods necessary to support the Group and Permission
models using the ModelBackend.
"""
is_superuser = models.BooleanField(
_("superuser status"),
default=False,
help_text=_(
"Designates that this user has all permissions without "
"explicitly assigning them."
),
)
groups = models.ManyToManyField(
Group,
verbose_name=_("groups"),
blank=True,
help_text=_(
"The groups this user belongs to. A user will get all permissions "
"granted to each of their groups."
),
related_name="user_set",
related_query_name="user",
)
user_permissions = models.ManyToManyField(
Permission,
verbose_name=_("user permissions"),
blank=True,
help_text=_("Specific permissions for this user."),
related_name="user_set",
related_query_name="user",
)
class Meta:
abstract = True
def get_user_permissions(self, obj=None):
"""
Return a list of permission strings that this user has directly.
Query all available auth backends. If an object is passed in,
return only permissions matching this object.
"""
return _user_get_permissions(self, obj, "user")
async def aget_user_permissions(self, obj=None):
"""See get_user_permissions()"""
return await _auser_get_permissions(self, obj, "user")
def get_group_permissions(self, obj=None):
"""
Return a list of permission strings that this user has through their
groups. Query all available auth backends. If an object is passed in,
return only permissions matching this object.
"""
return _user_get_permissions(self, obj, "group")
async def aget_group_permissions(self, obj=None):
"""See get_group_permissions()"""
return await _auser_get_permissions(self, obj, "group")
def get_all_permissions(self, obj=None):
return _user_get_permissions(self, obj, "all")
async def aget_all_permissions(self, obj=None):
return await _auser_get_permissions(self, obj, "all")
def has_perm(self, perm, obj=None):
"""
Return True if the user has the specified permission. Query all
available auth backends, but return immediately if any backend returns
True. Thus, a user who has permission from a single auth backend is
assumed to have permission in general. If an object is provided, check
permissions for that object.
"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
# Otherwise we need to check the backends.
return _user_has_perm(self, perm, obj)
async def ahas_perm(self, perm, obj=None):
"""See has_perm()"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
# Otherwise we need to check the backends.
return await _auser_has_perm(self, perm, obj)
def has_perms(self, perm_list, obj=None):
"""
Return True if the user has each of the specified permissions. If
object is passed, check if the user has all required perms for it.
"""
if not isinstance(perm_list, Iterable) or isinstance(perm_list, str):
raise ValueError("perm_list must be an iterable of permissions.")
return all(self.has_perm(perm, obj) for perm in perm_list)
async def ahas_perms(self, perm_list, obj=None):
"""See has_perms()"""
if not isinstance(perm_list, Iterable) or isinstance(perm_list, str):
raise ValueError("perm_list must be an iterable of permissions.")
for perm in perm_list:
if not await self.ahas_perm(perm, obj):
return False
return True
def has_module_perms(self, app_label):
"""
Return True if the user has any permissions in the given app label.
Use similar logic as has_perm(), above.
"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
return _user_has_module_perms(self, app_label)
async def ahas_module_perms(self, app_label):
"""See has_module_perms()"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
return await _auser_has_module_perms(self, app_label)
class AbstractUser(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
Username and password are required. Other fields are optional.
"""
username_validator = UnicodeUsernameValidator()
username = models.CharField(
_("username"),
max_length=150,
unique=True,
help_text=_(
"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
),
validators=[username_validator],
error_messages={
"unique": _("A user with that username already exists."),
},
)
first_name = models.CharField(_("first name"), max_length=150, blank=True)
last_name = models.CharField(_("last name"), max_length=150, blank=True)
email = models.EmailField(_("email address"), blank=True)
is_staff = models.BooleanField(
_("staff status"),
default=False,
help_text=_("Designates whether the user can log into this admin site."),
)
is_active = models.BooleanField(
_("active"),
default=True,
help_text=_(
"Designates whether this user should be treated as active. "
"Unselect this instead of deleting accounts."
),
)
date_joined = models.DateTimeField(_("date joined"), default=timezone.now)
objects = UserManager()
EMAIL_FIELD = "email"
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ["email"]
class Meta:
verbose_name = _("user")
verbose_name_plural = _("users")
abstract = True
def clean(self):
super().clean()
self.email = self.__class__.objects.normalize_email(self.email)
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.
"""
full_name = "%s %s" % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"""Return the short name for the user."""
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""Send an email to this user."""
send_mail(subject, message, from_email, [self.email], **kwargs)
class User(AbstractUser):
"""
Users within the Django authentication system are represented by this
model.
Username and password are required. Other fields are optional.
"""
class Meta(AbstractUser.Meta):
swappable = "AUTH_USER_MODEL"
class AnonymousUser:
id = None
pk = None
username = ""
is_staff = False
is_active = False
is_superuser = False
_groups = EmptyManager(Group)
_user_permissions = EmptyManager(Permission)
def __str__(self):
return "AnonymousUser"
def __eq__(self, other):
return isinstance(other, self.__class__)
def __hash__(self):
return 1 # instances always return the same hash value
def __int__(self):
raise TypeError(
"Cannot cast AnonymousUser to int. Are you trying to use it in place of "
"User?"
)
def save(self):
raise NotImplementedError(
"Django doesn't provide a DB representation for AnonymousUser."
)
def delete(self):
raise NotImplementedError(
"Django doesn't provide a DB representation for AnonymousUser."
)
def set_password(self, raw_password):
raise NotImplementedError(
"Django doesn't provide a DB representation for AnonymousUser."
)
def check_password(self, raw_password):
raise NotImplementedError(
"Django doesn't provide a DB representation for AnonymousUser."
)
@property
def groups(self):
return self._groups
@property
def user_permissions(self):
return self._user_permissions
def get_user_permissions(self, obj=None):
return _user_get_permissions(self, obj, "user")
async def aget_user_permissions(self, obj=None):
return await _auser_get_permissions(self, obj, "user")
def get_group_permissions(self, obj=None):
return set()
async def aget_group_permissions(self, obj=None):
return self.get_group_permissions(obj)
def get_all_permissions(self, obj=None):
return _user_get_permissions(self, obj, "all")
async def aget_all_permissions(self, obj=None):
return await _auser_get_permissions(self, obj, "all")
def has_perm(self, perm, obj=None):
return _user_has_perm(self, perm, obj=obj)
async def ahas_perm(self, perm, obj=None):
return await _auser_has_perm(self, perm, obj=obj)
def has_perms(self, perm_list, obj=None):
if not isinstance(perm_list, Iterable) or isinstance(perm_list, str):
raise ValueError("perm_list must be an iterable of permissions.")
return all(self.has_perm(perm, obj) for perm in perm_list)
async def ahas_perms(self, perm_list, obj=None):
if not isinstance(perm_list, Iterable) or isinstance(perm_list, str):
raise ValueError("perm_list must be an iterable of permissions.")
for perm in perm_list:
if not await self.ahas_perm(perm, obj):
return False
return True
def has_module_perms(self, module):
return _user_has_module_perms(self, module)
async def ahas_module_perms(self, module):
return await _auser_has_module_perms(self, module)
@property
def is_anonymous(self):
return True
@property
def is_authenticated(self):
return False
def get_username(self):
return self.username
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/signals.py | django/contrib/auth/signals.py | from django.dispatch import Signal
user_logged_in = Signal()
user_login_failed = Signal()
user_logged_out = Signal()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/decorators.py | django/contrib/auth/decorators.py | from functools import wraps
from urllib.parse import urlsplit
from asgiref.sync import async_to_sync, iscoroutinefunction, sync_to_async
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.exceptions import PermissionDenied
from django.shortcuts import resolve_url
def user_passes_test(
test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME
):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _redirect_to_login(request):
path = request.build_absolute_uri()
resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
# If the login url is the same scheme and net location then just
# use the path as the "next" url.
login_scheme, login_netloc = urlsplit(resolved_login_url)[:2]
current_scheme, current_netloc = urlsplit(path)[:2]
if (not login_scheme or login_scheme == current_scheme) and (
not login_netloc or login_netloc == current_netloc
):
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(path, resolved_login_url, redirect_field_name)
if iscoroutinefunction(view_func):
async def _view_wrapper(request, *args, **kwargs):
auser = await request.auser()
if iscoroutinefunction(test_func):
test_pass = await test_func(auser)
else:
test_pass = await sync_to_async(test_func)(auser)
if test_pass:
return await view_func(request, *args, **kwargs)
return _redirect_to_login(request)
else:
def _view_wrapper(request, *args, **kwargs):
if iscoroutinefunction(test_func):
test_pass = async_to_sync(test_func)(request.user)
else:
test_pass = test_func(request.user)
if test_pass:
return view_func(request, *args, **kwargs)
return _redirect_to_login(request)
# Attributes used by LoginRequiredMiddleware.
_view_wrapper.login_url = login_url
_view_wrapper.redirect_field_name = redirect_field_name
return wraps(view_func)(_view_wrapper)
return decorator
def login_required(
function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None
):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_authenticated,
login_url=login_url,
redirect_field_name=redirect_field_name,
)
if function:
return actual_decorator(function)
return actual_decorator
def login_not_required(view_func):
"""
Decorator for views that allows access to unauthenticated requests.
"""
view_func.login_required = False
return view_func
def permission_required(perm, login_url=None, raise_exception=False):
"""
Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if necessary.
If the raise_exception parameter is given the PermissionDenied exception
is raised.
"""
if isinstance(perm, str):
perms = (perm,)
else:
perms = perm
def decorator(view_func):
if iscoroutinefunction(view_func):
async def check_perms(user):
# First check if the user has the permission (even anon users).
if await user.ahas_perms(perms):
return True
# In case the 403 handler should be called raise the exception.
if raise_exception:
raise PermissionDenied
# As the last resort, show the login form.
return False
else:
def check_perms(user):
# First check if the user has the permission (even anon users).
if user.has_perms(perms):
return True
# In case the 403 handler should be called raise the exception.
if raise_exception:
raise PermissionDenied
# As the last resort, show the login form.
return False
return user_passes_test(check_perms, login_url=login_url)(view_func)
return decorator
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/validators.py | django/contrib/auth/validators.py | import re
from django.core import validators
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
@deconstructible
class ASCIIUsernameValidator(validators.RegexValidator):
regex = r"^[\w.@+-]+\Z"
message = _(
"Enter a valid username. This value may contain only unaccented lowercase a-z "
"and uppercase A-Z letters, numbers, and @/./+/-/_ characters."
)
flags = re.ASCII
@deconstructible
class UnicodeUsernameValidator(validators.RegexValidator):
regex = r"^[\w.@+-]+\Z"
message = _(
"Enter a valid username. This value may contain only letters, "
"numbers, and @/./+/-/_ characters."
)
flags = 0
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/context_processors.py | django/contrib/auth/context_processors.py | # PermWrapper and PermLookupDict proxy the permissions system into objects that
# the template system can understand.
class PermLookupDict:
def __init__(self, user, app_label):
self.user, self.app_label = user, app_label
def __repr__(self):
return str(self.user.get_all_permissions())
def __getitem__(self, perm_name):
return self.user.has_perm("%s.%s" % (self.app_label, perm_name))
def __iter__(self):
# To fix 'item in perms.someapp' and __getitem__ interaction we need to
# define __iter__. See #18979 for details.
raise TypeError("PermLookupDict is not iterable.")
def __bool__(self):
return self.user.has_module_perms(self.app_label)
class PermWrapper:
def __init__(self, user):
self.user = user
def __repr__(self):
return f"{self.__class__.__qualname__}({self.user!r})"
def __getitem__(self, app_label):
return PermLookupDict(self.user, app_label)
def __iter__(self):
# I am large, I contain multitudes.
raise TypeError("PermWrapper is not iterable.")
def __contains__(self, perm_name):
"""
Lookup by "someapp" or "someapp.someperm" in perms.
"""
if "." not in perm_name:
# The name refers to module.
return bool(self[perm_name])
app_label, perm_name = perm_name.split(".", 1)
return self[app_label][perm_name]
def auth(request):
"""
Return context variables required by apps that use Django's authentication
system.
If there is no 'user' attribute in the request, use AnonymousUser (from
django.contrib.auth).
"""
if hasattr(request, "user"):
user = request.user
else:
from django.contrib.auth.models import AnonymousUser
user = AnonymousUser()
return {
"user": user,
"perms": PermWrapper(user),
}
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/__init__.py | django/contrib/auth/__init__.py | import inspect
import re
from django.apps import apps as django_apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.middleware.csrf import rotate_token
from django.utils.crypto import constant_time_compare
from django.utils.module_loading import import_string
from django.views.decorators.debug import sensitive_variables
from .signals import user_logged_in, user_logged_out, user_login_failed
SESSION_KEY = "_auth_user_id"
BACKEND_SESSION_KEY = "_auth_user_backend"
HASH_SESSION_KEY = "_auth_user_hash"
REDIRECT_FIELD_NAME = "next"
def load_backend(path):
return import_string(path)()
def _get_backends(return_tuples=False):
backends = []
for backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
backends.append((backend, backend_path) if return_tuples else backend)
if not backends:
raise ImproperlyConfigured(
"No authentication backends have been defined. Does "
"AUTHENTICATION_BACKENDS contain anything?"
)
return backends
def get_backends():
return _get_backends(return_tuples=False)
def _get_compatible_backends(request, **credentials):
for backend, backend_path in _get_backends(return_tuples=True):
backend_signature = inspect.signature(backend.authenticate)
try:
backend_signature.bind(request, **credentials)
except TypeError:
# This backend doesn't accept these credentials as arguments. Try
# the next one.
continue
yield backend, backend_path
def _get_backend_from_user(user, backend=None):
try:
backend = backend or user.backend
except AttributeError:
backends = _get_backends(return_tuples=True)
if len(backends) == 1:
_, backend = backends[0]
else:
raise ValueError(
"You have multiple authentication backends configured and "
"therefore must provide the `backend` argument or set the "
"`backend` attribute on the user."
)
else:
if not isinstance(backend, str):
raise TypeError(
"backend must be a dotted import path string (got %r)." % backend
)
return backend
@sensitive_variables("credentials")
def _clean_credentials(credentials):
"""
Clean a dictionary of credentials of potentially sensitive info before
sending to less secure functions.
Not comprehensive - intended for user_login_failed signal
"""
SENSITIVE_CREDENTIALS = re.compile("api|token|key|secret|password|signature", re.I)
CLEANSED_SUBSTITUTE = "********************"
for key in credentials:
if SENSITIVE_CREDENTIALS.search(key):
credentials[key] = CLEANSED_SUBSTITUTE
return credentials
def _get_user_session_key(request):
# This value in the session is always serialized to a string, so we need
# to convert it back to Python whenever we access it.
return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
async def _aget_user_session_key(request):
# This value in the session is always serialized to a string, so we need
# to convert it back to Python whenever we access it.
session_key = await request.session.aget(SESSION_KEY)
if session_key is None:
raise KeyError()
return get_user_model()._meta.pk.to_python(session_key)
@sensitive_variables("credentials")
def authenticate(request=None, **credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend, backend_path in _get_compatible_backends(request, **credentials):
try:
user = backend.authenticate(request, **credentials)
except PermissionDenied:
# This backend says to stop in our tracks - this user should not be
# allowed in at all.
break
if user is None:
continue
# Annotate the user object with the path of the backend.
user.backend = backend_path
return user
# The credentials supplied are invalid to all backends, fire signal
user_login_failed.send(
sender=__name__, credentials=_clean_credentials(credentials), request=request
)
@sensitive_variables("credentials")
async def aauthenticate(request=None, **credentials):
"""See authenticate()."""
for backend, backend_path in _get_compatible_backends(request, **credentials):
try:
user = await backend.aauthenticate(request, **credentials)
except PermissionDenied:
# This backend says to stop in our tracks - this user should not be
# allowed in at all.
break
if user is None:
continue
# Annotate the user object with the path of the backend.
user.backend = backend_path
return user
# The credentials supplied are invalid to all backends, fire signal.
await user_login_failed.asend(
sender=__name__, credentials=_clean_credentials(credentials), request=request
)
def login(request, user, backend=None):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = user.get_session_auth_hash()
if SESSION_KEY in request.session:
if _get_user_session_key(request) != user.pk or (
session_auth_hash
and not constant_time_compare(
request.session.get(HASH_SESSION_KEY, ""), session_auth_hash
)
):
# To avoid reusing another user's session, create a new, empty
# session if the existing session corresponds to a different
# authenticated user.
request.session.flush()
else:
request.session.cycle_key()
backend = _get_backend_from_user(user=user, backend=backend)
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
request.session[BACKEND_SESSION_KEY] = backend
request.session[HASH_SESSION_KEY] = session_auth_hash
if hasattr(request, "user"):
request.user = user
rotate_token(request)
user_logged_in.send(sender=user.__class__, request=request, user=user)
async def alogin(request, user, backend=None):
"""See login()."""
session_auth_hash = user.get_session_auth_hash()
if await request.session.ahas_key(SESSION_KEY):
if await _aget_user_session_key(request) != user.pk or (
session_auth_hash
and not constant_time_compare(
await request.session.aget(HASH_SESSION_KEY, ""),
session_auth_hash,
)
):
# To avoid reusing another user's session, create a new, empty
# session if the existing session corresponds to a different
# authenticated user.
await request.session.aflush()
else:
await request.session.acycle_key()
backend = _get_backend_from_user(user=user, backend=backend)
await request.session.aset(SESSION_KEY, user._meta.pk.value_to_string(user))
await request.session.aset(BACKEND_SESSION_KEY, backend)
await request.session.aset(HASH_SESSION_KEY, session_auth_hash)
if hasattr(request, "auser"):
async def auser():
return user
request.auser = auser
rotate_token(request)
await user_logged_in.asend(sender=user.__class__, request=request, user=user)
def logout(request):
"""
Remove the authenticated user's ID from the request and flush their session
data.
"""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, "user", None)
if not getattr(user, "is_authenticated", True):
user = None
user_logged_out.send(sender=user.__class__, request=request, user=user)
request.session.flush()
if hasattr(request, "user"):
from django.contrib.auth.models import AnonymousUser
request.user = AnonymousUser()
async def alogout(request):
"""See logout()."""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, "auser", None)
if user is not None:
user = await user()
if not getattr(user, "is_authenticated", True):
user = None
await user_logged_out.asend(sender=user.__class__, request=request, user=user)
await request.session.aflush()
if hasattr(request, "auser"):
from django.contrib.auth.models import AnonymousUser
async def auser():
return AnonymousUser()
request.auser = auser
def get_user_model():
"""
Return the User model that is active in this project.
"""
try:
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured(
"AUTH_USER_MODEL must be of the form 'app_label.model_name'"
)
except LookupError:
raise ImproperlyConfigured(
"AUTH_USER_MODEL refers to model '%s' that has not been installed"
% settings.AUTH_USER_MODEL
)
def get_user(request):
"""
Return the user model instance associated with the given request session.
If no user is retrieved, return an instance of `AnonymousUser`.
"""
from .models import AnonymousUser
user = None
try:
user_id = _get_user_session_key(request)
backend_path = request.session[BACKEND_SESSION_KEY]
except KeyError:
pass
else:
if backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
user = backend.get_user(user_id)
# Verify the session
if hasattr(user, "get_session_auth_hash"):
session_hash = request.session.get(HASH_SESSION_KEY)
if not session_hash:
session_hash_verified = False
else:
session_auth_hash = user.get_session_auth_hash()
session_hash_verified = constant_time_compare(
session_hash, session_auth_hash
)
if not session_hash_verified:
# If the current secret does not verify the session, try
# with the fallback secrets and stop when a matching one is
# found.
if session_hash and any(
constant_time_compare(session_hash, fallback_auth_hash)
for fallback_auth_hash in user.get_session_auth_fallback_hash()
):
request.session.cycle_key()
request.session[HASH_SESSION_KEY] = session_auth_hash
else:
request.session.flush()
user = None
return user or AnonymousUser()
async def aget_user(request):
"""See get_user()."""
from .models import AnonymousUser
user = None
try:
user_id = await _aget_user_session_key(request)
backend_path = await request.session.aget(BACKEND_SESSION_KEY)
except KeyError:
pass
else:
if backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
user = await backend.aget_user(user_id)
# Verify the session
if hasattr(user, "get_session_auth_hash"):
session_hash = await request.session.aget(HASH_SESSION_KEY)
if not session_hash:
session_hash_verified = False
else:
session_auth_hash = user.get_session_auth_hash()
session_hash_verified = constant_time_compare(
session_hash, session_auth_hash
)
if not session_hash_verified:
# If the current secret does not verify the session, try
# with the fallback secrets and stop when a matching one is
# found.
if session_hash and any(
constant_time_compare(session_hash, fallback_auth_hash)
for fallback_auth_hash in user.get_session_auth_fallback_hash()
):
await request.session.acycle_key()
await request.session.aset(HASH_SESSION_KEY, session_auth_hash)
else:
await request.session.aflush()
user = None
return user or AnonymousUser()
def get_permission_codename(action, opts):
"""
Return the codename of the permission for the specified action.
"""
return "%s_%s" % (action, opts.model_name)
def update_session_auth_hash(request, user):
"""
Updating a user's password logs out all sessions for the user.
Take the current request and the updated user object from which the new
session hash will be derived and update the session hash appropriately to
prevent a password change from logging out the session from which the
password was changed.
"""
request.session.cycle_key()
if hasattr(user, "get_session_auth_hash") and request.user == user:
request.session[HASH_SESSION_KEY] = user.get_session_auth_hash()
async def aupdate_session_auth_hash(request, user):
"""See update_session_auth_hash()."""
await request.session.acycle_key()
if hasattr(user, "get_session_auth_hash") and await request.auser() == user:
await request.session.aset(HASH_SESSION_KEY, user.get_session_auth_hash())
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/password_validation.py | django/contrib/auth/password_validation.py | import functools
import gzip
import re
from difflib import SequenceMatcher
from pathlib import Path
from django.conf import settings
from django.core.exceptions import (
FieldDoesNotExist,
ImproperlyConfigured,
ValidationError,
)
from django.utils.functional import cached_property, lazy
from django.utils.html import format_html, format_html_join
from django.utils.module_loading import import_string
from django.utils.translation import gettext as _
from django.utils.translation import ngettext
@functools.cache
def get_default_password_validators():
return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS)
def get_password_validators(validator_config):
validators = []
for validator in validator_config:
try:
klass = import_string(validator["NAME"])
except ImportError:
msg = (
"The module in NAME could not be imported: %s. Check your "
"AUTH_PASSWORD_VALIDATORS setting."
)
raise ImproperlyConfigured(msg % validator["NAME"])
validators.append(klass(**validator.get("OPTIONS", {})))
return validators
def validate_password(password, user=None, password_validators=None):
"""
Validate that the password meets all validator requirements.
If the password is valid, return ``None``.
If the password is invalid, raise ValidationError with all error messages.
"""
errors = []
if password_validators is None:
password_validators = get_default_password_validators()
for validator in password_validators:
try:
validator.validate(password, user)
except ValidationError as error:
errors.append(error)
if errors:
raise ValidationError(errors)
def password_changed(password, user=None, password_validators=None):
"""
Inform all validators that have implemented a password_changed() method
that the password has been changed.
"""
if password_validators is None:
password_validators = get_default_password_validators()
for validator in password_validators:
password_changed = getattr(validator, "password_changed", lambda *a: None)
password_changed(password, user)
def password_validators_help_texts(password_validators=None):
"""
Return a list of all help texts of all configured validators.
"""
help_texts = []
if password_validators is None:
password_validators = get_default_password_validators()
for validator in password_validators:
help_texts.append(validator.get_help_text())
return help_texts
def _password_validators_help_text_html(password_validators=None):
"""
Return an HTML string with all help texts of all configured validators
in an <ul>.
"""
help_texts = password_validators_help_texts(password_validators)
help_items = format_html_join(
"", "<li>{}</li>", ((help_text,) for help_text in help_texts)
)
return format_html("<ul>{}</ul>", help_items) if help_items else ""
password_validators_help_text_html = lazy(_password_validators_help_text_html, str)
class MinimumLengthValidator:
"""
Validate that the password is of a minimum length.
"""
def __init__(self, min_length=8):
self.min_length = min_length
def validate(self, password, user=None):
if len(password) < self.min_length:
raise ValidationError(
self.get_error_message(),
code="password_too_short",
params={"min_length": self.min_length},
)
def get_error_message(self):
return (
ngettext(
"This password is too short. It must contain at least %d character.",
"This password is too short. It must contain at least %d characters.",
self.min_length,
)
% self.min_length
)
def get_help_text(self):
return ngettext(
"Your password must contain at least %(min_length)d character.",
"Your password must contain at least %(min_length)d characters.",
self.min_length,
) % {"min_length": self.min_length}
def exceeds_maximum_length_ratio(password, max_similarity, value):
"""
Test that value is within a reasonable range of password.
The following ratio calculations are based on testing SequenceMatcher like
this:
for i in range(0,6):
print(10**i, SequenceMatcher(a='A', b='A'*(10**i)).quick_ratio())
which yields:
1 1.0
10 0.18181818181818182
100 0.019801980198019802
1000 0.001998001998001998
10000 0.00019998000199980003
100000 1.999980000199998e-05
This means a length_ratio of 10 should never yield a similarity higher than
0.2, for 100 this is down to 0.02 and for 1000 it is 0.002. This can be
calculated via 2 / length_ratio. As a result we avoid the potentially
expensive sequence matching.
"""
pwd_len = len(password)
length_bound_similarity = max_similarity / 2 * pwd_len
value_len = len(value)
return pwd_len >= 10 * value_len and value_len < length_bound_similarity
class UserAttributeSimilarityValidator:
"""
Validate that the password is sufficiently different from the user's
attributes.
If no specific attributes are provided, look at a sensible list of
defaults. Attributes that don't exist are ignored. Comparison is made to
not only the full attribute value, but also its components, so that, for
example, a password is validated against either part of an email address,
as well as the full address.
"""
DEFAULT_USER_ATTRIBUTES = ("username", "first_name", "last_name", "email")
def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7):
self.user_attributes = user_attributes
if max_similarity < 0.1:
raise ValueError("max_similarity must be at least 0.1")
self.max_similarity = max_similarity
def validate(self, password, user=None):
if not user:
return
password = password.lower()
for attribute_name in self.user_attributes:
value = getattr(user, attribute_name, None)
if not value or not isinstance(value, str):
continue
value_lower = value.lower()
value_parts = [*re.split(r"\W+", value_lower), value_lower]
for value_part in value_parts:
if exceeds_maximum_length_ratio(
password, self.max_similarity, value_part
):
continue
if (
SequenceMatcher(a=password, b=value_part).quick_ratio()
>= self.max_similarity
):
try:
verbose_name = str(
user._meta.get_field(attribute_name).verbose_name
)
except FieldDoesNotExist:
verbose_name = attribute_name
raise ValidationError(
self.get_error_message(),
code="password_too_similar",
params={"verbose_name": verbose_name},
)
def get_error_message(self):
return _("The password is too similar to the %(verbose_name)s.")
def get_help_text(self):
return _(
"Your password can’t be too similar to your other personal information."
)
class CommonPasswordValidator:
"""
Validate that the password is not a common password.
The password is rejected if it occurs in a provided list of passwords,
which may be gzipped. The list Django ships with contains 20000 common
passwords (unhexed, lowercased and deduplicated), created by Royce
Williams:
https://gist.github.com/roycewilliams/226886fd01572964e1431ac8afc999ce
The password list must be lowercased to match the comparison in validate().
"""
@cached_property
def DEFAULT_PASSWORD_LIST_PATH(self):
return Path(__file__).resolve().parent / "common-passwords.txt.gz"
def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH):
if password_list_path is CommonPasswordValidator.DEFAULT_PASSWORD_LIST_PATH:
password_list_path = self.DEFAULT_PASSWORD_LIST_PATH
try:
with gzip.open(password_list_path, "rt", encoding="utf-8") as f:
self.passwords = {x.strip() for x in f}
except OSError:
with open(password_list_path) as f:
self.passwords = {x.strip() for x in f}
def validate(self, password, user=None):
if password.lower().strip() in self.passwords:
raise ValidationError(
self.get_error_message(),
code="password_too_common",
)
def get_error_message(self):
return _("This password is too common.")
def get_help_text(self):
return _("Your password can’t be a commonly used password.")
class NumericPasswordValidator:
"""
Validate that the password is not entirely numeric.
"""
def validate(self, password, user=None):
if password.isdigit():
raise ValidationError(
self.get_error_message(),
code="password_entirely_numeric",
)
def get_error_message(self):
return _("This password is entirely numeric.")
def get_help_text(self):
return _("Your password can’t be entirely numeric.")
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/apps.py | django/contrib/auth/apps.py | from django.apps import AppConfig
from django.core import checks
from django.db.models.query_utils import DeferredAttribute
from django.db.models.signals import post_migrate, pre_migrate
from django.utils.translation import gettext_lazy as _
from . import get_user_model
from .checks import check_middleware, check_models_permissions, check_user_model
from .management import create_permissions, rename_permissions
from .signals import user_logged_in
class AuthConfig(AppConfig):
default_auto_field = "django.db.models.AutoField"
name = "django.contrib.auth"
verbose_name = _("Authentication and Authorization")
def ready(self):
post_migrate.connect(
create_permissions,
dispatch_uid="django.contrib.auth.management.create_permissions",
)
pre_migrate.connect(
rename_permissions,
dispatch_uid="django.contrib.auth.management.rename_permissions",
)
last_login_field = getattr(get_user_model(), "last_login", None)
# Register the handler only if UserModel.last_login is a field.
if isinstance(last_login_field, DeferredAttribute):
from .models import update_last_login
user_logged_in.connect(update_last_login, dispatch_uid="update_last_login")
checks.register(check_user_model, checks.Tags.models)
checks.register(check_models_permissions, checks.Tags.models)
checks.register(check_middleware)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/hashers.py | django/contrib/auth/hashers.py | import base64
import binascii
import functools
import hashlib
import importlib
import math
import warnings
from asgiref.sync import sync_to_async
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.signals import setting_changed
from django.dispatch import receiver
from django.utils.crypto import (
RANDOM_STRING_CHARS,
constant_time_compare,
get_random_string,
pbkdf2,
)
from django.utils.encoding import force_bytes, force_str
from django.utils.module_loading import import_string
from django.utils.translation import gettext_noop as _
UNUSABLE_PASSWORD_PREFIX = "!" # This will never be a valid encoded hash
UNUSABLE_PASSWORD_SUFFIX_LENGTH = (
40 # number of random chars to add after UNUSABLE_PASSWORD_PREFIX
)
def is_password_usable(encoded):
"""
Return True if this password wasn't generated by
User.set_unusable_password(), i.e. make_password(None).
"""
return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX)
def verify_password(password, encoded, preferred="default"):
"""
Return two booleans. The first is whether the raw password matches the
three part encoded digest, and the second whether to regenerate the
password.
"""
fake_runtime = password is None or not is_password_usable(encoded)
preferred = get_hasher(preferred)
try:
hasher = identify_hasher(encoded)
except ValueError:
# encoded is gibberish or uses a hasher that's no longer installed.
fake_runtime = True
if fake_runtime:
# Run the default password hasher once to reduce the timing difference
# between an existing user with an unusable password and a nonexistent
# user or missing hasher (similar to #20760).
make_password(get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH))
return False, False
hasher_changed = hasher.algorithm != preferred.algorithm
must_update = hasher_changed or preferred.must_update(encoded)
is_correct = hasher.verify(password, encoded)
# If the hasher didn't change (we don't protect against enumeration if it
# does) and the password should get updated, try to close the timing gap
# between the work factor of the current encoded password and the default
# work factor.
if not is_correct and not hasher_changed and must_update:
hasher.harden_runtime(password, encoded)
return is_correct, must_update
def check_password(password, encoded, setter=None, preferred="default"):
"""
Return a boolean of whether the raw password matches the three part encoded
digest.
If setter is specified, it'll be called when you need to regenerate the
password.
"""
is_correct, must_update = verify_password(password, encoded, preferred=preferred)
if setter and is_correct and must_update:
setter(password)
return is_correct
async def acheck_password(password, encoded, setter=None, preferred="default"):
"""See check_password()."""
is_correct, must_update = await sync_to_async(
verify_password,
thread_sensitive=False,
)(password, encoded, preferred=preferred)
if setter and is_correct and must_update:
await setter(password)
return is_correct
def make_password(password, salt=None, hasher="default"):
"""
Turn a plain-text password into a hash for database storage
Same as encode() but generate a new random salt. If password is None then
return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
which disallows logins. Additional random string reduces chances of gaining
access to staff or superuser accounts. See ticket #20079 for more info.
"""
if password is None:
return UNUSABLE_PASSWORD_PREFIX + get_random_string(
UNUSABLE_PASSWORD_SUFFIX_LENGTH
)
if not isinstance(password, (bytes, str)):
raise TypeError(
"Password must be a string or bytes, got %s." % type(password).__qualname__
)
hasher = get_hasher(hasher)
salt = salt or hasher.salt()
return hasher.encode(password, salt)
@functools.lru_cache
def get_hashers():
hashers = []
for hasher_path in settings.PASSWORD_HASHERS:
hasher_cls = import_string(hasher_path)
hasher = hasher_cls()
if not getattr(hasher, "algorithm"):
raise ImproperlyConfigured(
"hasher doesn't specify an algorithm name: %s" % hasher_path
)
hashers.append(hasher)
return hashers
@functools.lru_cache
def get_hashers_by_algorithm():
return {hasher.algorithm: hasher for hasher in get_hashers()}
@receiver(setting_changed)
def reset_hashers(*, setting, **kwargs):
if setting == "PASSWORD_HASHERS":
get_hashers.cache_clear()
get_hashers_by_algorithm.cache_clear()
def get_hasher(algorithm="default"):
"""
Return an instance of a loaded password hasher.
If algorithm is 'default', return the default hasher. Lazily import hashers
specified in the project's settings file if needed.
"""
if hasattr(algorithm, "algorithm"):
return algorithm
elif algorithm == "default":
return get_hashers()[0]
else:
hashers = get_hashers_by_algorithm()
try:
return hashers[algorithm]
except KeyError:
raise ValueError(
"Unknown password hashing algorithm '%s'. "
"Did you specify it in the PASSWORD_HASHERS "
"setting?" % algorithm
)
def identify_hasher(encoded):
"""
Return an instance of a loaded password hasher.
Identify hasher algorithm by examining encoded hash, and call
get_hasher() to return hasher. Raise ValueError if
algorithm cannot be identified, or if hasher is not loaded.
"""
# Ancient versions of Django created plain MD5 passwords and accepted
# MD5 passwords with an empty salt.
if (len(encoded) == 32 and "$" not in encoded) or (
len(encoded) == 37 and encoded.startswith("md5$$")
):
algorithm = "unsalted_md5"
# Ancient versions of Django accepted SHA1 passwords with an empty salt.
elif len(encoded) == 46 and encoded.startswith("sha1$$"):
algorithm = "unsalted_sha1"
else:
algorithm = encoded.split("$", 1)[0]
return get_hasher(algorithm)
def mask_hash(hash, show=6, char="*"):
"""
Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons.
"""
masked = hash[:show]
masked += char * len(hash[show:])
return masked
def must_update_salt(salt, expected_entropy):
# Each character in the salt provides log_2(len(alphabet)) bits of entropy.
return len(salt) * math.log2(len(RANDOM_STRING_CHARS)) < expected_entropy
class BasePasswordHasher:
"""
Abstract base class for password hashers
When creating your own hasher, you need to override algorithm,
verify(), encode() and safe_summary().
PasswordHasher objects are immutable.
"""
algorithm = None
library = None
salt_entropy = 128
def _load_library(self):
if self.library is not None:
if isinstance(self.library, (tuple, list)):
name, mod_path = self.library
else:
mod_path = self.library
try:
module = importlib.import_module(mod_path)
except ImportError as e:
raise ValueError(
"Couldn't load %r algorithm library: %s"
% (self.__class__.__name__, e)
)
return module
raise ValueError(
"Hasher %r doesn't specify a library attribute" % self.__class__.__name__
)
def salt(self):
"""
Generate a cryptographically secure nonce salt in ASCII with an entropy
of at least `salt_entropy` bits.
"""
# Each character in the salt provides
# log_2(len(alphabet)) bits of entropy.
char_count = math.ceil(self.salt_entropy / math.log2(len(RANDOM_STRING_CHARS)))
return get_random_string(char_count, allowed_chars=RANDOM_STRING_CHARS)
def verify(self, password, encoded):
"""Check if the given password is correct."""
raise NotImplementedError(
"subclasses of BasePasswordHasher must provide a verify() method"
)
def _check_encode_args(self, password, salt):
if password is None:
raise TypeError("password must be provided.")
if not salt or "$" in force_str(salt): # salt can be str or bytes.
raise ValueError("salt must be provided and cannot contain $.")
def encode(self, password, salt):
"""
Create an encoded database value.
The result is normally formatted as "algorithm$salt$hash" and
must be fewer than 128 characters.
"""
raise NotImplementedError(
"subclasses of BasePasswordHasher must provide an encode() method"
)
def decode(self, encoded):
"""
Return a decoded database value.
The result is a dictionary and should contain `algorithm`, `hash`, and
`salt`. Extra keys can be algorithm specific like `iterations` or
`work_factor`.
"""
raise NotImplementedError(
"subclasses of BasePasswordHasher must provide a decode() method."
)
def safe_summary(self, encoded):
"""
Return a summary of safe values.
The result is a dictionary and will be used where the password field
must be displayed to construct a safe representation of the password.
"""
raise NotImplementedError(
"subclasses of BasePasswordHasher must provide a safe_summary() method"
)
def must_update(self, encoded):
return False
def harden_runtime(self, password, encoded):
"""
Bridge the runtime gap between the work factor supplied in `encoded`
and the work factor suggested by this hasher.
Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and
`self.iterations` is 30000, this method should run password through
another 10000 iterations of PBKDF2. Similar approaches should exist
for any hasher that has a work factor. If not, this method should be
defined as a no-op to silence the warning.
"""
warnings.warn(
"subclasses of BasePasswordHasher should provide a harden_runtime() method"
)
class PBKDF2PasswordHasher(BasePasswordHasher):
"""
Secure password hashing using the PBKDF2 algorithm (recommended)
Configured to use PBKDF2 + HMAC + SHA256.
The result is a 64 byte binary string. Iterations may be changed
safely but you must rename the algorithm if you change SHA256.
"""
algorithm = "pbkdf2_sha256"
iterations = 1_500_000
digest = hashlib.sha256
def encode(self, password, salt, iterations=None):
self._check_encode_args(password, salt)
iterations = iterations or self.iterations
password = force_str(password)
salt = force_str(salt)
hash = pbkdf2(password, salt, iterations, digest=self.digest)
hash = base64.b64encode(hash).decode("ascii").strip()
return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)
def decode(self, encoded):
algorithm, iterations, salt, hash = encoded.split("$", 3)
assert algorithm == self.algorithm
return {
"algorithm": algorithm,
"hash": hash,
"iterations": int(iterations),
"salt": salt,
}
def verify(self, password, encoded):
decoded = self.decode(encoded)
encoded_2 = self.encode(password, decoded["salt"], decoded["iterations"])
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
decoded = self.decode(encoded)
return {
_("algorithm"): decoded["algorithm"],
_("iterations"): decoded["iterations"],
_("salt"): mask_hash(decoded["salt"]),
_("hash"): mask_hash(decoded["hash"]),
}
def must_update(self, encoded):
decoded = self.decode(encoded)
update_salt = must_update_salt(decoded["salt"], self.salt_entropy)
return (decoded["iterations"] != self.iterations) or update_salt
def harden_runtime(self, password, encoded):
decoded = self.decode(encoded)
extra_iterations = self.iterations - decoded["iterations"]
if extra_iterations > 0:
self.encode(password, decoded["salt"], extra_iterations)
class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher):
"""
Alternate PBKDF2 hasher which uses SHA1, the default PRF
recommended by PKCS #5. This is compatible with other
implementations of PBKDF2, such as openssl's
PKCS5_PBKDF2_HMAC_SHA1().
"""
algorithm = "pbkdf2_sha1"
digest = hashlib.sha1
class Argon2PasswordHasher(BasePasswordHasher):
"""
Secure password hashing using the argon2 algorithm.
This is the winner of the Password Hashing Competition 2013-2015
(https://password-hashing.net). It requires the argon2-cffi library which
depends on native C code and might cause portability issues.
"""
algorithm = "argon2"
library = "argon2"
time_cost = 2
memory_cost = 102400
parallelism = 8
def encode(self, password, salt):
argon2 = self._load_library()
params = self.params()
data = argon2.low_level.hash_secret(
force_bytes(password),
force_bytes(salt),
time_cost=params.time_cost,
memory_cost=params.memory_cost,
parallelism=params.parallelism,
hash_len=params.hash_len,
type=params.type,
)
return self.algorithm + data.decode("ascii")
def decode(self, encoded):
argon2 = self._load_library()
algorithm, rest = encoded.split("$", 1)
assert algorithm == self.algorithm
params = argon2.extract_parameters("$" + rest)
variety, *_, b64salt, hash = rest.split("$")
# Add padding.
b64salt += "=" * (-len(b64salt) % 4)
salt = base64.b64decode(b64salt).decode("latin1")
return {
"algorithm": algorithm,
"hash": hash,
"memory_cost": params.memory_cost,
"parallelism": params.parallelism,
"salt": salt,
"time_cost": params.time_cost,
"variety": variety,
"version": params.version,
"params": params,
}
def verify(self, password, encoded):
argon2 = self._load_library()
algorithm, rest = encoded.split("$", 1)
assert algorithm == self.algorithm
try:
return argon2.PasswordHasher().verify("$" + rest, password)
except argon2.exceptions.VerificationError:
return False
def safe_summary(self, encoded):
decoded = self.decode(encoded)
return {
_("algorithm"): decoded["algorithm"],
_("variety"): decoded["variety"],
_("version"): decoded["version"],
_("memory cost"): decoded["memory_cost"],
_("time cost"): decoded["time_cost"],
_("parallelism"): decoded["parallelism"],
_("salt"): mask_hash(decoded["salt"]),
_("hash"): mask_hash(decoded["hash"]),
}
def must_update(self, encoded):
decoded = self.decode(encoded)
current_params = decoded["params"]
new_params = self.params()
# Set salt_len to the salt_len of the current parameters because salt
# is explicitly passed to argon2.
new_params.salt_len = current_params.salt_len
update_salt = must_update_salt(decoded["salt"], self.salt_entropy)
return (current_params != new_params) or update_salt
def harden_runtime(self, password, encoded):
# The runtime for Argon2 is too complicated to implement a sensible
# hardening algorithm.
pass
def params(self):
argon2 = self._load_library()
# salt_len is a noop, because we provide our own salt.
return argon2.Parameters(
type=argon2.low_level.Type.ID,
version=argon2.low_level.ARGON2_VERSION,
salt_len=argon2.DEFAULT_RANDOM_SALT_LENGTH,
hash_len=argon2.DEFAULT_HASH_LENGTH,
time_cost=self.time_cost,
memory_cost=self.memory_cost,
parallelism=self.parallelism,
)
class BCryptSHA256PasswordHasher(BasePasswordHasher):
"""
Secure password hashing using the bcrypt algorithm (recommended)
This is considered by many to be the most secure algorithm but you
must first install the bcrypt library. Please be warned that
this library depends on native C code and might cause portability
issues.
"""
algorithm = "bcrypt_sha256"
digest = hashlib.sha256
library = ("bcrypt", "bcrypt")
rounds = 12
def salt(self):
bcrypt = self._load_library()
return bcrypt.gensalt(self.rounds)
def encode(self, password, salt):
bcrypt = self._load_library()
password = force_bytes(password)
salt = force_bytes(salt)
# Hash the password prior to using bcrypt to prevent password
# truncation as described in #20138.
if self.digest is not None:
# Use binascii.hexlify() because a hex encoded bytestring is str.
password = binascii.hexlify(self.digest(password).digest())
data = bcrypt.hashpw(password, salt)
return "%s$%s" % (self.algorithm, data.decode("ascii"))
def decode(self, encoded):
algorithm, empty, algostr, work_factor, data = encoded.split("$", 4)
assert algorithm == self.algorithm
return {
"algorithm": algorithm,
"algostr": algostr,
"checksum": data[22:],
"salt": data[:22],
"work_factor": int(work_factor),
}
def verify(self, password, encoded):
algorithm, data = encoded.split("$", 1)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, data.encode("ascii"))
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
decoded = self.decode(encoded)
return {
_("algorithm"): decoded["algorithm"],
_("work factor"): decoded["work_factor"],
_("salt"): mask_hash(decoded["salt"]),
_("checksum"): mask_hash(decoded["checksum"]),
}
def must_update(self, encoded):
decoded = self.decode(encoded)
return decoded["work_factor"] != self.rounds
def harden_runtime(self, password, encoded):
_, data = encoded.split("$", 1)
salt = data[:29] # Length of the salt in bcrypt.
rounds = data.split("$")[2]
# work factor is logarithmic, adding one doubles the load.
diff = 2 ** (self.rounds - int(rounds)) - 1
while diff > 0:
self.encode(password, salt.encode("ascii"))
diff -= 1
class BCryptPasswordHasher(BCryptSHA256PasswordHasher):
"""
Secure password hashing using the bcrypt algorithm
This is considered by many to be the most secure algorithm but you
must first install the bcrypt library. Please be warned that
this library depends on native C code and might cause portability
issues.
This hasher does not first hash the password which means it is subject to
bcrypt's 72 bytes password truncation. Most use cases should prefer the
BCryptSHA256PasswordHasher.
"""
algorithm = "bcrypt"
digest = None
class ScryptPasswordHasher(BasePasswordHasher):
"""
Secure password hashing using the Scrypt algorithm.
"""
algorithm = "scrypt"
block_size = 8
maxmem = 0
parallelism = 5
work_factor = 2**14
def encode(self, password, salt, n=None, r=None, p=None):
self._check_encode_args(password, salt)
n = n or self.work_factor
r = r or self.block_size
p = p or self.parallelism
hash_ = hashlib.scrypt(
password=force_bytes(password),
salt=force_bytes(salt),
n=n,
r=r,
p=p,
maxmem=self.maxmem,
dklen=64,
)
hash_ = base64.b64encode(hash_).decode("ascii").strip()
return "%s$%d$%s$%d$%d$%s" % (self.algorithm, n, force_str(salt), r, p, hash_)
def decode(self, encoded):
algorithm, work_factor, salt, block_size, parallelism, hash_ = encoded.split(
"$", 6
)
assert algorithm == self.algorithm
return {
"algorithm": algorithm,
"work_factor": int(work_factor),
"salt": salt,
"block_size": int(block_size),
"parallelism": int(parallelism),
"hash": hash_,
}
def verify(self, password, encoded):
decoded = self.decode(encoded)
encoded_2 = self.encode(
password,
decoded["salt"],
decoded["work_factor"],
decoded["block_size"],
decoded["parallelism"],
)
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
decoded = self.decode(encoded)
return {
_("algorithm"): decoded["algorithm"],
_("work factor"): decoded["work_factor"],
_("block size"): decoded["block_size"],
_("parallelism"): decoded["parallelism"],
_("salt"): mask_hash(decoded["salt"]),
_("hash"): mask_hash(decoded["hash"]),
}
def must_update(self, encoded):
decoded = self.decode(encoded)
return (
decoded["work_factor"] != self.work_factor
or decoded["block_size"] != self.block_size
or decoded["parallelism"] != self.parallelism
)
def harden_runtime(self, password, encoded):
# The runtime for Scrypt is too complicated to implement a sensible
# hardening algorithm.
pass
class MD5PasswordHasher(BasePasswordHasher):
"""
The Salted MD5 password hashing algorithm (not recommended)
"""
algorithm = "md5"
def encode(self, password, salt):
self._check_encode_args(password, salt)
password = force_str(password)
salt = force_str(salt)
hash = hashlib.md5((salt + password).encode()).hexdigest()
return "%s$%s$%s" % (self.algorithm, salt, hash)
def decode(self, encoded):
algorithm, salt, hash = encoded.split("$", 2)
assert algorithm == self.algorithm
return {
"algorithm": algorithm,
"hash": hash,
"salt": salt,
}
def verify(self, password, encoded):
decoded = self.decode(encoded)
encoded_2 = self.encode(password, decoded["salt"])
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
decoded = self.decode(encoded)
return {
_("algorithm"): decoded["algorithm"],
_("salt"): mask_hash(decoded["salt"], show=2),
_("hash"): mask_hash(decoded["hash"]),
}
def must_update(self, encoded):
decoded = self.decode(encoded)
return must_update_salt(decoded["salt"], self.salt_entropy)
def harden_runtime(self, password, encoded):
pass
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/base_user.py | django/contrib/auth/base_user.py | """
This module allows importing AbstractBaseUser even when django.contrib.auth is
not in INSTALLED_APPS.
"""
import unicodedata
from django.conf import settings
from django.contrib.auth import password_validation
from django.contrib.auth.hashers import (
acheck_password,
check_password,
is_password_usable,
make_password,
)
from django.db import models
from django.utils.crypto import salted_hmac
from django.utils.translation import gettext_lazy as _
class BaseUserManager(models.Manager):
@classmethod
def normalize_email(cls, email):
"""
Normalize the email address by lowercasing the domain part of it.
"""
email = email or ""
try:
email_name, domain_part = email.strip().rsplit("@", 1)
except ValueError:
pass
else:
email = email_name + "@" + domain_part.lower()
return email
def get_by_natural_key(self, username):
return self.get(**{self.model.USERNAME_FIELD: username})
async def aget_by_natural_key(self, username):
return await self.aget(**{self.model.USERNAME_FIELD: username})
class AbstractBaseUser(models.Model):
password = models.CharField(_("password"), max_length=128)
last_login = models.DateTimeField(_("last login"), blank=True, null=True)
is_active = True
REQUIRED_FIELDS = []
# Stores the raw password if set_password() is called so that it can
# be passed to password_changed() after the model is saved.
_password = None
class Meta:
abstract = True
def __str__(self):
return self.get_username()
def save(self, **kwargs):
super().save(**kwargs)
if self._password is not None:
password_validation.password_changed(self._password, self)
self._password = None
def get_username(self):
"""Return the username for this User."""
return getattr(self, self.USERNAME_FIELD)
def clean(self):
setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username()))
def natural_key(self):
return (self.get_username(),)
@property
def is_anonymous(self):
"""
Always return False. This is a way of comparing User objects to
anonymous users.
"""
return False
@property
def is_authenticated(self):
"""
Always return True. This is a way to tell if the user has been
authenticated in templates.
"""
return True
def set_password(self, raw_password):
self.password = make_password(raw_password)
self._password = raw_password
def check_password(self, raw_password):
"""
Return a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes.
"""
def setter(raw_password):
self.set_password(raw_password)
# Password hash upgrades shouldn't be considered password changes.
self._password = None
self.save(update_fields=["password"])
return check_password(raw_password, self.password, setter)
async def acheck_password(self, raw_password):
"""See check_password()."""
async def setter(raw_password):
self.set_password(raw_password)
# Password hash upgrades shouldn't be considered password changes.
self._password = None
await self.asave(update_fields=["password"])
return await acheck_password(raw_password, self.password, setter)
def set_unusable_password(self):
# Set a value that will never be a valid hash
self.password = make_password(None)
def has_usable_password(self):
"""
Return False if set_unusable_password() has been called for this user.
"""
return is_password_usable(self.password)
def get_session_auth_hash(self):
"""
Return an HMAC of the password field.
"""
return self._get_session_auth_hash()
def get_session_auth_fallback_hash(self):
for fallback_secret in settings.SECRET_KEY_FALLBACKS:
yield self._get_session_auth_hash(secret=fallback_secret)
def _get_session_auth_hash(self, secret=None):
key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
return salted_hmac(
key_salt,
self.password,
secret=secret,
algorithm="sha256",
).hexdigest()
@classmethod
def get_email_field_name(cls):
try:
return cls.EMAIL_FIELD
except AttributeError:
return "email"
@classmethod
def normalize_username(cls, username):
return (
unicodedata.normalize("NFKC", username)
if isinstance(username, str)
else username
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/forms.py | django/contrib/auth/forms.py | import logging
import unicodedata
from django import forms
from django.contrib.auth import authenticate, get_user_model, password_validation
from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ValidationError
from django.core.mail import EmailMultiAlternatives
from django.template import loader
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.utils.text import capfirst
from django.utils.translation import gettext_lazy as _
from django.views.decorators.debug import sensitive_variables
UserModel = get_user_model()
logger = logging.getLogger("django.contrib.auth")
def _unicode_ci_compare(s1, s2):
"""
Perform case-insensitive comparison of two identifiers, using the
recommended algorithm from Unicode Technical Report 36, section
2.11.2(B)(2).
"""
return (
unicodedata.normalize("NFKC", s1).casefold()
== unicodedata.normalize("NFKC", s2).casefold()
)
class ReadOnlyPasswordHashWidget(forms.Widget):
template_name = "auth/widgets/read_only_password_hash.html"
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
usable_password = value and not value.startswith(UNUSABLE_PASSWORD_PREFIX)
context["button_label"] = (
_("Reset password") if usable_password else _("Set password")
)
return context
def id_for_label(self, id_):
return None
class ReadOnlyPasswordHashField(forms.Field):
widget = ReadOnlyPasswordHashWidget
def __init__(self, *args, **kwargs):
kwargs.setdefault("required", False)
kwargs.setdefault("disabled", True)
super().__init__(*args, **kwargs)
class UsernameField(forms.CharField):
def to_python(self, value):
value = super().to_python(value)
if self.max_length is not None and len(value) > self.max_length:
# Normalization can increase the string length (e.g.
# "ff" -> "ff", "½" -> "1⁄2") but cannot reduce it, so there is no
# point in normalizing invalid data. Moreover, Unicode
# normalization is very slow on Windows and can be a DoS attack
# vector.
return value
return unicodedata.normalize("NFKC", value)
def widget_attrs(self, widget):
return {
**super().widget_attrs(widget),
"autocapitalize": "none",
"autocomplete": "username",
}
class SetPasswordMixin:
"""
Form mixin that validates and sets a password for a user.
"""
error_messages = {
"password_mismatch": _("The two password fields didn’t match."),
}
@staticmethod
def create_password_fields(label1=_("Password"), label2=_("Password confirmation")):
password1 = forms.CharField(
label=label1,
required=True,
strip=False,
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
help_text=password_validation.password_validators_help_text_html(),
)
password2 = forms.CharField(
label=label2,
required=True,
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
strip=False,
help_text=_("Enter the same password as before, for verification."),
)
return password1, password2
@sensitive_variables("password1", "password2")
def validate_passwords(
self,
password1_field_name="password1",
password2_field_name="password2",
):
password1 = self.cleaned_data.get(password1_field_name)
password2 = self.cleaned_data.get(password2_field_name)
if password1 and password2 and password1 != password2:
error = ValidationError(
self.error_messages["password_mismatch"],
code="password_mismatch",
)
self.add_error(password2_field_name, error)
@sensitive_variables("password")
def validate_password_for_user(self, user, password_field_name="password2"):
password = self.cleaned_data.get(password_field_name)
if password:
try:
password_validation.validate_password(password, user)
except ValidationError as error:
self.add_error(password_field_name, error)
def set_password_and_save(self, user, password_field_name="password1", commit=True):
user.set_password(self.cleaned_data[password_field_name])
if commit:
user.save()
return user
def __class_getitem__(cls, *args, **kwargs):
return cls
class SetUnusablePasswordMixin:
"""
Form mixin that allows setting an unusable password for a user.
This mixin should be used in combination with `SetPasswordMixin`.
"""
usable_password_help_text = _(
"Whether the user will be able to authenticate using a password or not. "
"If disabled, they may still be able to authenticate using other backends, "
"such as Single Sign-On or LDAP."
)
@staticmethod
def create_usable_password_field(help_text=usable_password_help_text):
return forms.ChoiceField(
label=_("Password-based authentication"),
required=False,
initial="true",
choices={"true": _("Enabled"), "false": _("Disabled")},
widget=forms.RadioSelect(attrs={"class": "radiolist inline"}),
help_text=help_text,
)
@sensitive_variables("password1", "password2")
def validate_passwords(
self,
password1_field_name="password1",
password2_field_name="password2",
usable_password_field_name="usable_password",
):
usable_password = (
self.cleaned_data.pop(usable_password_field_name, None) != "false"
)
self.cleaned_data["set_usable_password"] = usable_password
if not usable_password:
return
password1 = self.cleaned_data.get(password1_field_name)
password2 = self.cleaned_data.get(password2_field_name)
if not password1 and password1_field_name not in self.errors:
error = ValidationError(
self.fields[password1_field_name].error_messages["required"],
code="required",
)
self.add_error(password1_field_name, error)
if not password2 and password2_field_name not in self.errors:
error = ValidationError(
self.fields[password2_field_name].error_messages["required"],
code="required",
)
self.add_error(password2_field_name, error)
super().validate_passwords(password1_field_name, password2_field_name)
def validate_password_for_user(self, user, **kwargs):
if self.cleaned_data["set_usable_password"]:
super().validate_password_for_user(user, **kwargs)
def set_password_and_save(self, user, commit=True, **kwargs):
if self.cleaned_data["set_usable_password"]:
user = super().set_password_and_save(user, **kwargs, commit=commit)
else:
user.set_unusable_password()
if commit:
user.save()
return user
class BaseUserCreationForm(SetPasswordMixin, forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
This is the documented base class for customizing the user creation form.
It should be kept mostly unchanged to ensure consistency and compatibility.
"""
password1, password2 = SetPasswordMixin.create_password_fields()
class Meta:
model = User
fields = ("username",)
field_classes = {"username": UsernameField}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self._meta.model.USERNAME_FIELD in self.fields:
self.fields[self._meta.model.USERNAME_FIELD].widget.attrs[
"autofocus"
] = True
def clean(self):
self.validate_passwords()
return super().clean()
def _post_clean(self):
super()._post_clean()
# Validate the password after self.instance is updated with form data
# by super().
self.validate_password_for_user(self.instance)
def save(self, commit=True):
user = super().save(commit=False)
user = self.set_password_and_save(user, commit=commit)
if commit and hasattr(self, "save_m2m"):
self.save_m2m()
return user
class UserCreationForm(BaseUserCreationForm):
def clean_username(self):
"""Reject usernames that differ only in case."""
username = self.cleaned_data.get("username")
if (
username
and self._meta.model.objects.filter(username__iexact=username).exists()
):
self._update_errors(
ValidationError(
{
"username": self.instance.unique_error_message(
self._meta.model, ["username"]
)
}
)
)
else:
return username
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField(
label=_("Password"),
help_text=_(
"Raw passwords are not stored, so there is no way to see "
"the user’s password."
),
)
class Meta:
model = User
fields = "__all__"
field_classes = {"username": UsernameField}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
password = self.fields.get("password")
if password:
if self.instance and not self.instance.has_usable_password():
password.help_text = _(
"Enable password-based authentication for this user by setting a "
"password."
)
user_permissions = self.fields.get("user_permissions")
if user_permissions:
user_permissions.queryset = user_permissions.queryset.select_related(
"content_type"
)
class AuthenticationForm(forms.Form):
"""
Base class for authenticating users. Extend this to get a form that accepts
username/password logins.
"""
username = UsernameField(widget=forms.TextInput(attrs={"autofocus": True}))
password = forms.CharField(
label=_("Password"),
strip=False,
widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
)
error_messages = {
"invalid_login": _(
"Please enter a correct %(username)s and password. Note that both "
"fields may be case-sensitive."
),
"inactive": _("This account is inactive."),
}
def __init__(self, request=None, *args, **kwargs):
"""
The 'request' parameter is set for custom auth use by subclasses.
The form data comes in via the standard 'data' kwarg.
"""
self.request = request
self.user_cache = None
super().__init__(*args, **kwargs)
# Set the max length and label for the "username" field.
self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
username_max_length = self.username_field.max_length or 254
self.fields["username"].max_length = username_max_length
self.fields["username"].widget.attrs["maxlength"] = username_max_length
if self.fields["username"].label is None:
self.fields["username"].label = capfirst(self.username_field.verbose_name)
@sensitive_variables()
def clean(self):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username is not None and password:
self.user_cache = authenticate(
self.request, username=username, password=password
)
if self.user_cache is None:
raise self.get_invalid_login_error()
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
def confirm_login_allowed(self, user):
"""
Controls whether the given User may log in. This is a policy setting,
independent of end-user authentication. This default behavior is to
allow login by active users, and reject login by inactive users.
If the given user cannot log in, this method should raise a
``ValidationError``.
If the given user may log in, this method should return None.
"""
if not user.is_active:
raise ValidationError(
self.error_messages["inactive"],
code="inactive",
)
def get_user(self):
return self.user_cache
def get_invalid_login_error(self):
return ValidationError(
self.error_messages["invalid_login"],
code="invalid_login",
params={"username": self.username_field.verbose_name},
)
class PasswordResetForm(forms.Form):
email = forms.EmailField(
label=_("Email"),
max_length=254,
widget=forms.EmailInput(attrs={"autocomplete": "email"}),
)
def send_mail(
self,
subject_template_name,
email_template_name,
context,
from_email,
to_email,
html_email_template_name=None,
):
"""
Send a django.core.mail.EmailMultiAlternatives to `to_email`.
"""
subject = loader.render_to_string(subject_template_name, context)
# Email subject *must not* contain newlines
subject = "".join(subject.splitlines())
body = loader.render_to_string(email_template_name, context)
email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
if html_email_template_name is not None:
html_email = loader.render_to_string(html_email_template_name, context)
email_message.attach_alternative(html_email, "text/html")
try:
email_message.send()
except Exception:
logger.exception(
"Failed to send password reset email to %s", context["user"].pk
)
def get_users(self, email):
"""Given an email, return matching user(s) who should receive a reset.
This allows subclasses to more easily customize the default policies
that prevent inactive users and users with unusable passwords from
resetting their password.
"""
email_field_name = UserModel.get_email_field_name()
active_users = UserModel._default_manager.filter(
**{
"%s__iexact" % email_field_name: email,
"is_active": True,
}
)
return (
u
for u in active_users
if u.has_usable_password()
and _unicode_ci_compare(email, getattr(u, email_field_name))
)
def save(
self,
domain_override=None,
subject_template_name="registration/password_reset_subject.txt",
email_template_name="registration/password_reset_email.html",
use_https=False,
token_generator=default_token_generator,
from_email=None,
request=None,
html_email_template_name=None,
extra_email_context=None,
):
"""
Generate a one-use only link for resetting password and send it to the
user.
"""
email = self.cleaned_data["email"]
if not domain_override:
current_site = get_current_site(request)
site_name = current_site.name
domain = current_site.domain
else:
site_name = domain = domain_override
email_field_name = UserModel.get_email_field_name()
for user in self.get_users(email):
user_email = getattr(user, email_field_name)
user_pk_bytes = force_bytes(UserModel._meta.pk.value_to_string(user))
context = {
"email": user_email,
"domain": domain,
"site_name": site_name,
"uid": urlsafe_base64_encode(user_pk_bytes),
"user": user,
"token": token_generator.make_token(user),
"protocol": "https" if use_https else "http",
**(extra_email_context or {}),
}
self.send_mail(
subject_template_name,
email_template_name,
context,
from_email,
user_email,
html_email_template_name=html_email_template_name,
)
class SetPasswordForm(SetPasswordMixin, forms.Form):
"""
A form that lets a user set their password without entering the old
password
"""
new_password1, new_password2 = SetPasswordMixin.create_password_fields(
label1=_("New password"), label2=_("New password confirmation")
)
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
def clean(self):
self.validate_passwords("new_password1", "new_password2")
self.validate_password_for_user(self.user, "new_password2")
return super().clean()
def save(self, commit=True):
return self.set_password_and_save(self.user, "new_password1", commit=commit)
class PasswordChangeForm(SetPasswordForm):
"""
A form that lets a user change their password by entering their old
password.
"""
error_messages = {
**SetPasswordForm.error_messages,
"password_incorrect": _(
"Your old password was entered incorrectly. Please enter it again."
),
}
old_password = forms.CharField(
label=_("Old password"),
strip=False,
widget=forms.PasswordInput(
attrs={"autocomplete": "current-password", "autofocus": True}
),
)
field_order = ["old_password", "new_password1", "new_password2"]
@sensitive_variables("old_password")
def clean_old_password(self):
"""
Validate that the old_password field is correct.
"""
old_password = self.cleaned_data["old_password"]
if not self.user.check_password(old_password):
raise ValidationError(
self.error_messages["password_incorrect"],
code="password_incorrect",
)
return old_password
class AdminPasswordChangeForm(SetUnusablePasswordMixin, SetPasswordMixin, forms.Form):
"""
A form used to change the password of a user in the admin interface.
"""
required_css_class = "required"
usable_password_help_text = SetUnusablePasswordMixin.usable_password_help_text + (
'<ul id="id_unusable_warning" class="messagelist"><li class="warning">'
"If disabled, the current password for this user will be lost.</li></ul>"
)
password1, password2 = SetPasswordMixin.create_password_fields()
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
self.fields["password1"].widget.attrs["autofocus"] = True
if self.user.has_usable_password():
self.fields["password1"].required = False
self.fields["password2"].required = False
self.fields["usable_password"] = (
SetUnusablePasswordMixin.create_usable_password_field(
self.usable_password_help_text
)
)
def clean(self):
self.validate_passwords()
self.validate_password_for_user(self.user)
return super().clean()
def save(self, commit=True):
"""Save the new password."""
return self.set_password_and_save(self.user, commit=commit)
@property
def changed_data(self):
data = super().changed_data
if "set_usable_password" in data or "password1" in data and "password2" in data:
return ["password"]
return []
class AdminUserCreationForm(SetUnusablePasswordMixin, UserCreationForm):
usable_password = SetUnusablePasswordMixin.create_usable_password_field()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["password1"].required = False
self.fields["password2"].required = False
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/tokens.py | django/contrib/auth/tokens.py | from datetime import datetime
from django.conf import settings
from django.utils.crypto import constant_time_compare, salted_hmac
from django.utils.http import base36_to_int, int_to_base36
class PasswordResetTokenGenerator:
"""
Strategy object used to generate and check tokens for the password
reset mechanism.
"""
key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
algorithm = None
_secret = None
_secret_fallbacks = None
def __init__(self):
self.algorithm = self.algorithm or "sha256"
def _get_secret(self):
return self._secret or settings.SECRET_KEY
def _set_secret(self, secret):
self._secret = secret
secret = property(_get_secret, _set_secret)
def _get_fallbacks(self):
if self._secret_fallbacks is None:
return settings.SECRET_KEY_FALLBACKS
return self._secret_fallbacks
def _set_fallbacks(self, fallbacks):
self._secret_fallbacks = fallbacks
secret_fallbacks = property(_get_fallbacks, _set_fallbacks)
def make_token(self, user):
"""
Return a token that can be used once to do a password reset
for the given user.
"""
return self._make_token_with_timestamp(
user,
self._num_seconds(self._now()),
self.secret,
)
def check_token(self, user, token):
"""
Check that a password reset token is correct for a given user.
"""
if not (user and token):
return False
# Parse the token
try:
ts_b36, _ = token.split("-")
except ValueError:
return False
try:
ts = base36_to_int(ts_b36)
except ValueError:
return False
# Check that the timestamp/uid has not been tampered with
for secret in [self.secret, *self.secret_fallbacks]:
if constant_time_compare(
self._make_token_with_timestamp(user, ts, secret),
token,
):
break
else:
return False
# Check the timestamp is within limit.
if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:
return False
return True
def _make_token_with_timestamp(self, user, timestamp, secret):
# timestamp is number of seconds since 2001-1-1. Converted to base 36,
# this gives us a 6 digit string until about 2069.
ts_b36 = int_to_base36(timestamp)
hash_string = salted_hmac(
self.key_salt,
self._make_hash_value(user, timestamp),
secret=secret,
algorithm=self.algorithm,
).hexdigest()[
::2
] # Limit to shorten the URL.
return "%s-%s" % (ts_b36, hash_string)
def _make_hash_value(self, user, timestamp):
"""
Hash the user's primary key, email (if available), and some user state
that's sure to change after a password reset to produce a token that is
invalidated when it's used:
1. The password field will change upon a password reset (even if the
same password is chosen, due to password salting).
2. The last_login field will usually be updated very shortly after
a password reset.
Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually
invalidates the token.
Running this data through salted_hmac() prevents password cracking
attempts using the reset token, provided the secret isn't compromised.
"""
# Truncate microseconds so that tokens are consistent even if the
# database doesn't support microseconds.
login_timestamp = (
""
if user.last_login is None
else user.last_login.replace(microsecond=0, tzinfo=None)
)
email_field = user.get_email_field_name()
email = getattr(user, email_field, "") or ""
return f"{user.pk}{user.password}{login_timestamp}{timestamp}{email}"
def _num_seconds(self, dt):
return int((dt - datetime(2001, 1, 1)).total_seconds())
def _now(self):
# Used for mocking in tests
return datetime.now()
default_token_generator = PasswordResetTokenGenerator()
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/urls.py | django/contrib/auth/urls.py | # The views used below are normally mapped in the AdminSite instance.
# This URLs file is used to provide a reliable view deployment for test
# purposes. It is also provided as a convenience to those who want to deploy
# these URLs elsewhere.
from django.contrib.auth import views
from django.urls import path
urlpatterns = [
path("login/", views.LoginView.as_view(), name="login"),
path("logout/", views.LogoutView.as_view(), name="logout"),
path(
"password_change/", views.PasswordChangeView.as_view(), name="password_change"
),
path(
"password_change/done/",
views.PasswordChangeDoneView.as_view(),
name="password_change_done",
),
path("password_reset/", views.PasswordResetView.as_view(), name="password_reset"),
path(
"password_reset/done/",
views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
path(
"reset/<uidb64>/<token>/",
views.PasswordResetConfirmView.as_view(),
name="password_reset_confirm",
),
path(
"reset/done/",
views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/templatetags/__init__.py | django/contrib/auth/templatetags/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/templatetags/auth.py | django/contrib/auth/templatetags/auth.py | from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX, identify_hasher
from django.template import Library
from django.utils.html import format_html, format_html_join
from django.utils.translation import gettext
register = Library()
@register.simple_tag
def render_password_as_hash(value):
if not value or value.startswith(UNUSABLE_PASSWORD_PREFIX):
return format_html("<p><strong>{}</strong></p>", gettext("No password set."))
try:
hasher = identify_hasher(value)
hashed_summary = hasher.safe_summary(value)
except ValueError:
return format_html(
"<p><strong>{}</strong></p>",
gettext("Invalid password format or unknown hashing algorithm."),
)
items = [(gettext(key), val) for key, val in hashed_summary.items()]
return format_html(
"<p>{}</p>",
format_html_join(" ", "<strong>{}</strong>: <bdi>{}</bdi>", items),
)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/management/__init__.py | django/contrib/auth/management/__init__.py | """
Creates permissions for all installed apps that need permissions.
"""
import getpass
import unicodedata
from django.apps import apps as global_apps
from django.contrib.auth import get_permission_codename
from django.contrib.contenttypes.management import create_contenttypes
from django.core import exceptions
from django.db import DEFAULT_DB_ALIAS, migrations, router, transaction
from django.db.utils import IntegrityError
from django.utils.text import camel_case_to_spaces
def _get_all_permissions(opts):
"""
Return (codename, name) for all permissions in the given opts.
"""
return [*_get_builtin_permissions(opts), *opts.permissions]
def _get_builtin_permissions(opts):
"""
Return (codename, name) for all autogenerated permissions.
By default, this is ('add', 'change', 'delete', 'view')
"""
perms = []
for action in opts.default_permissions:
perms.append(
(
get_permission_codename(action, opts),
"Can %s %s" % (action, opts.verbose_name_raw),
)
)
return perms
def create_permissions(
app_config,
verbosity=2,
interactive=True,
using=DEFAULT_DB_ALIAS,
apps=global_apps,
**kwargs,
):
if not app_config.models_module:
return
try:
Permission = apps.get_model("auth", "Permission")
except LookupError:
return
if not router.allow_migrate_model(using, Permission):
return
# Ensure that contenttypes are created for this app. Needed if
# 'django.contrib.auth' is in INSTALLED_APPS before
# 'django.contrib.contenttypes'.
create_contenttypes(
app_config,
verbosity=verbosity,
interactive=interactive,
using=using,
apps=apps,
**kwargs,
)
app_label = app_config.label
try:
app_config = apps.get_app_config(app_label)
ContentType = apps.get_model("contenttypes", "ContentType")
except LookupError:
return
models = list(app_config.get_models())
# Grab all the ContentTypes.
ctypes = ContentType.objects.db_manager(using).get_for_models(
*models, for_concrete_models=False
)
# Find all the Permissions that have a content_type for a model we're
# looking for. We don't need to check for codenames since we already have
# a list of the ones we're going to create.
all_perms = set(
Permission.objects.using(using)
.filter(
content_type__in=set(ctypes.values()),
)
.values_list("content_type", "codename")
)
perms = []
for model in models:
ctype = ctypes[model]
for codename, name in _get_all_permissions(model._meta):
if (ctype.pk, codename) not in all_perms:
permission = Permission()
permission._state.db = using
permission.codename = codename
permission.name = name
permission.content_type = ctype
perms.append(permission)
Permission.objects.using(using).bulk_create(perms)
if verbosity >= 2:
for perm in perms:
print("Adding permission '%s'" % perm)
class RenamePermission(migrations.RunPython):
def __init__(self, app_label, old_model, new_model):
self.app_label = app_label
self.old_model = old_model
self.new_model = new_model
super(RenamePermission, self).__init__(
self.rename_forward, self.rename_backward
)
def _rename(self, apps, schema_editor, old_model, new_model):
ContentType = apps.get_model("contenttypes", "ContentType")
# Use the live Permission model instead of the frozen one, since frozen
# models do not retain foreign key constraints.
from django.contrib.auth.models import Permission
db = schema_editor.connection.alias
ctypes = ContentType.objects.using(db).filter(
app_label=self.app_label, model__icontains=old_model.lower()
)
for permission in Permission.objects.using(db).filter(
content_type_id__in=ctypes.values("id")
):
prefix = permission.codename.split("_")[0]
default_verbose_name = camel_case_to_spaces(new_model)
new_codename = f"{prefix}_{new_model.lower()}"
new_name = f"Can {prefix} {default_verbose_name}"
if permission.codename != new_codename or permission.name != new_name:
permission.codename = new_codename
permission.name = new_name
try:
with transaction.atomic(using=db):
permission.save(update_fields={"name", "codename"})
except IntegrityError:
pass
def rename_forward(self, apps, schema_editor):
self._rename(apps, schema_editor, self.old_model, self.new_model)
def rename_backward(self, apps, schema_editor):
self._rename(apps, schema_editor, self.new_model, self.old_model)
def rename_permissions(
plan,
verbosity=2,
interactive=True,
using=DEFAULT_DB_ALIAS,
apps=global_apps,
**kwargs,
):
"""
Insert a `RenamePermissionType` operation after every planned `RenameModel`
operation.
"""
try:
Permission = apps.get_model("auth", "Permission")
except LookupError:
return
else:
if not router.allow_migrate_model(using, Permission):
return
for migration, backward in plan:
inserts = []
for index, operation in enumerate(migration.operations):
if isinstance(operation, migrations.RenameModel):
operation = RenamePermission(
migration.app_label,
operation.old_name,
operation.new_name,
)
inserts.append((index + 1, operation))
for inserted, (index, operation) in enumerate(inserts):
migration.operations.insert(inserted + index, operation)
def get_system_username():
"""
Return the current system user's username, or an empty string if the
username could not be determined.
"""
try:
result = getpass.getuser()
except (ImportError, KeyError, OSError):
# TODO: Drop ImportError and KeyError when dropping support for PY312.
# KeyError (Python <3.13) or OSError (Python 3.13+) will be raised by
# os.getpwuid() (called by getuser()) if there is no corresponding
# entry in the /etc/passwd file (for example, in a very restricted
# chroot environment).
return ""
return result
def get_default_username(check_db=True, database=DEFAULT_DB_ALIAS):
"""
Try to determine the current system user's username to use as a default.
:param check_db: If ``True``, requires that the username does not match an
existing ``auth.User`` (otherwise returns an empty string).
:param database: The database where the unique check will be performed.
:returns: The username, or an empty string if no username can be
determined or the suggested username is already taken.
"""
# This file is used in apps.py, it should not trigger models import.
from django.contrib.auth import models as auth_app
# If the User model has been swapped out, we can't make any assumptions
# about the default user name.
if auth_app.User._meta.swapped:
return ""
default_username = get_system_username()
try:
default_username = (
unicodedata.normalize("NFKD", default_username)
.encode("ascii", "ignore")
.decode("ascii")
.replace(" ", "")
.lower()
)
except UnicodeDecodeError:
return ""
# Run the username validator
try:
auth_app.User._meta.get_field("username").run_validators(default_username)
except exceptions.ValidationError:
return ""
# Don't return the default username if it is already taken.
if check_db and default_username:
try:
auth_app.User._default_manager.db_manager(database).get(
username=default_username,
)
except auth_app.User.DoesNotExist:
pass
else:
return ""
return default_username
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/management/commands/changepassword.py | django/contrib/auth/management/commands/changepassword.py | import getpass
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, connections
UserModel = get_user_model()
class Command(BaseCommand):
help = "Change a user's password for django.contrib.auth."
requires_migrations_checks = True
requires_system_checks = []
def _get_pass(self, prompt="Password: "):
p = getpass.getpass(prompt=prompt)
if not p:
raise CommandError("aborted")
return p
def add_arguments(self, parser):
parser.add_argument(
"username",
nargs="?",
help=(
"Username to change password for; by default, it's the current "
"username."
),
)
parser.add_argument(
"--database",
default=DEFAULT_DB_ALIAS,
choices=tuple(connections),
help='Specifies the database to use. Default is "default".',
)
def handle(self, *args, **options):
if options["username"]:
username = options["username"]
else:
username = getpass.getuser()
try:
u = UserModel._default_manager.using(options["database"]).get(
**{UserModel.USERNAME_FIELD: username}
)
except UserModel.DoesNotExist:
raise CommandError("user '%s' does not exist" % username)
self.stdout.write("Changing password for user '%s'" % u)
MAX_TRIES = 3
count = 0
p1, p2 = 1, 2 # To make them initially mismatch.
password_validated = False
while (p1 != p2 or not password_validated) and count < MAX_TRIES:
p1 = self._get_pass()
p2 = self._get_pass("Password (again): ")
if p1 != p2:
self.stdout.write("Passwords do not match. Please try again.")
count += 1
# Don't validate passwords that don't match.
continue
try:
validate_password(p2, u)
except ValidationError as err:
self.stderr.write("\n".join(err.messages))
count += 1
else:
password_validated = True
if count == MAX_TRIES:
raise CommandError(
"Aborting password change for user '%s' after %s attempts" % (u, count)
)
u.set_password(p1)
u.save()
return "Password changed successfully for user '%s'" % u
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/management/commands/createsuperuser.py | django/contrib/auth/management/commands/createsuperuser.py | """
Management utility to create superusers.
"""
import getpass
import os
import sys
from django.contrib.auth import get_user_model
from django.contrib.auth.management import get_default_username
from django.contrib.auth.password_validation import validate_password
from django.core import exceptions
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, connections
from django.utils.functional import cached_property
from django.utils.text import capfirst
class NotRunningInTTYException(Exception):
pass
PASSWORD_FIELD = "password"
class Command(BaseCommand):
help = "Used to create a superuser."
requires_migrations_checks = True
stealth_options = ("stdin",)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.UserModel = get_user_model()
self.username_field = self.UserModel._meta.get_field(
self.UserModel.USERNAME_FIELD
)
def add_arguments(self, parser):
parser.add_argument(
"--%s" % self.UserModel.USERNAME_FIELD,
help="Specifies the login for the superuser.",
)
parser.add_argument(
"--noinput",
"--no-input",
action="store_false",
dest="interactive",
help=(
"Tells Django to NOT prompt the user for input of any kind. "
"You must use --%s with --noinput, along with an option for "
"any other required field. Superusers created with --noinput will "
"not be able to log in until they're given a valid password."
% self.UserModel.USERNAME_FIELD
),
)
parser.add_argument(
"--database",
default=DEFAULT_DB_ALIAS,
choices=tuple(connections),
help='Specifies the database to use. Default is "default".',
)
for field_name in self.UserModel.REQUIRED_FIELDS:
field = self.UserModel._meta.get_field(field_name)
if field.many_to_many:
if (
field.remote_field.through
and not field.remote_field.through._meta.auto_created
):
raise CommandError(
"Required field '%s' specifies a many-to-many "
"relation through model, which is not supported." % field_name
)
else:
parser.add_argument(
"--%s" % field_name,
action="append",
help=(
"Specifies the %s for the superuser. Can be used "
"multiple times." % field_name,
),
)
else:
parser.add_argument(
"--%s" % field_name,
help="Specifies the %s for the superuser." % field_name,
)
def execute(self, *args, **options):
self.stdin = options.get("stdin", sys.stdin) # Used for testing
return super().execute(*args, **options)
def handle(self, *args, **options):
username = options[self.UserModel.USERNAME_FIELD]
database = options["database"]
user_data = {}
verbose_field_name = self.username_field.verbose_name
try:
self.UserModel._meta.get_field(PASSWORD_FIELD)
except exceptions.FieldDoesNotExist:
pass
else:
# If not provided, create the user with an unusable password.
user_data[PASSWORD_FIELD] = None
try:
if options["interactive"]:
# Same as user_data but without many to many fields and with
# foreign keys as fake model instances instead of raw IDs.
fake_user_data = {}
if hasattr(self.stdin, "isatty") and not self.stdin.isatty():
raise NotRunningInTTYException
default_username = get_default_username(database=database)
if username:
error_msg = self._validate_username(
username, verbose_field_name, database
)
if error_msg:
self.stderr.write(error_msg)
username = None
elif username == "":
raise CommandError(
"%s cannot be blank." % capfirst(verbose_field_name)
)
# Prompt for username.
while username is None:
message = self._get_input_message(
self.username_field, default_username
)
username = self.get_input_data(
self.username_field, message, default_username
)
if username:
error_msg = self._validate_username(
username, verbose_field_name, database
)
if error_msg:
self.stderr.write(error_msg)
username = None
continue
user_data[self.UserModel.USERNAME_FIELD] = username
fake_user_data[self.UserModel.USERNAME_FIELD] = (
self.username_field.remote_field.model(username)
if self.username_field.remote_field
else username
)
# Prompt for required fields.
for field_name in self.UserModel.REQUIRED_FIELDS:
field = self.UserModel._meta.get_field(field_name)
user_data[field_name] = options[field_name]
if user_data[field_name] is not None:
user_data[field_name] = field.clean(user_data[field_name], None)
while user_data[field_name] is None:
message = self._get_input_message(field)
input_value = self.get_input_data(field, message)
user_data[field_name] = input_value
if field.many_to_many and input_value:
if not input_value.strip():
user_data[field_name] = None
self.stderr.write("Error: This field cannot be blank.")
continue
user_data[field_name] = [
pk.strip() for pk in input_value.split(",")
]
if not field.many_to_many:
fake_user_data[field_name] = user_data[field_name]
# Wrap any foreign keys in fake model instances.
if field.many_to_one:
fake_user_data[field_name] = field.remote_field.model(
user_data[field_name]
)
# Prompt for a password if the model has one.
while PASSWORD_FIELD in user_data and user_data[PASSWORD_FIELD] is None:
password = getpass.getpass()
password2 = getpass.getpass("Password (again): ")
if password != password2:
self.stderr.write("Error: Your passwords didn't match.")
# Don't validate passwords that don't match.
continue
if password.strip() == "":
self.stderr.write("Error: Blank passwords aren't allowed.")
# Don't validate blank passwords.
continue
try:
validate_password(password2, self.UserModel(**fake_user_data))
except exceptions.ValidationError as err:
self.stderr.write("\n".join(err.messages))
response = input(
"Bypass password validation and create user anyway? [y/N]: "
)
if response.lower() != "y":
continue
user_data[PASSWORD_FIELD] = password
else:
# Non-interactive mode.
# Use password from environment variable, if provided.
if (
PASSWORD_FIELD in user_data
and "DJANGO_SUPERUSER_PASSWORD" in os.environ
):
user_data[PASSWORD_FIELD] = os.environ["DJANGO_SUPERUSER_PASSWORD"]
# Use username from environment variable, if not provided in
# options.
if username is None:
username = os.environ.get(
"DJANGO_SUPERUSER_" + self.UserModel.USERNAME_FIELD.upper()
)
if username is None:
raise CommandError(
"You must use --%s with --noinput."
% self.UserModel.USERNAME_FIELD
)
else:
error_msg = self._validate_username(
username, verbose_field_name, database
)
if error_msg:
raise CommandError(error_msg)
user_data[self.UserModel.USERNAME_FIELD] = username
for field_name in self.UserModel.REQUIRED_FIELDS:
env_var = "DJANGO_SUPERUSER_" + field_name.upper()
value = options[field_name] or os.environ.get(env_var)
field = self.UserModel._meta.get_field(field_name)
if not value:
if field.blank and (
options[field_name] == "" or os.environ.get(env_var) == ""
):
continue
raise CommandError(
"You must use --%s with --noinput." % field_name
)
user_data[field_name] = field.clean(value, None)
if field.many_to_many and isinstance(user_data[field_name], str):
user_data[field_name] = [
pk.strip() for pk in user_data[field_name].split(",")
]
self.UserModel._default_manager.db_manager(database).create_superuser(
**user_data
)
if options["verbosity"] >= 1:
self.stdout.write("Superuser created successfully.")
except KeyboardInterrupt:
self.stderr.write("\nOperation cancelled.")
sys.exit(1)
except exceptions.ValidationError as e:
raise CommandError("; ".join(e.messages))
except NotRunningInTTYException:
self.stdout.write(
"Superuser creation skipped due to not running in a TTY. "
"You can run `manage.py createsuperuser` in your project "
"to create one manually."
)
def get_input_data(self, field, message, default=None):
"""
Override this method if you want to customize data inputs or
validation exceptions.
"""
raw_value = input(message)
if default and raw_value == "":
raw_value = default
try:
val = field.clean(raw_value, None)
except exceptions.ValidationError as e:
self.stderr.write("Error: %s" % "; ".join(e.messages))
val = None
return val
def _get_input_message(self, field, default=None):
return "%s%s%s: " % (
capfirst(field.verbose_name),
" (leave blank to use '%s')" % default if default else "",
(
" (%s.%s)"
% (
field.remote_field.model._meta.object_name,
(
field.m2m_target_field_name()
if field.many_to_many
else field.remote_field.field_name
),
)
if field.remote_field
else ""
),
)
@cached_property
def username_is_unique(self):
if self.username_field.unique:
return True
return any(
len(unique_constraint.fields) == 1
and unique_constraint.fields[0] == self.username_field.name
for unique_constraint in self.UserModel._meta.total_unique_constraints
)
def _validate_username(self, username, verbose_field_name, database):
"""Validate username. If invalid, return a string error message."""
if self.username_is_unique:
try:
self.UserModel._default_manager.db_manager(database).get_by_natural_key(
username
)
except self.UserModel.DoesNotExist:
pass
else:
return "Error: That %s is already taken." % verbose_field_name
if not username:
return "%s cannot be blank." % capfirst(verbose_field_name)
try:
self.username_field.clean(username, None)
except exceptions.ValidationError as e:
return "; ".join(e.messages)
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/management/commands/__init__.py | django/contrib/auth/management/commands/__init__.py | python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false | |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/migrations/0006_require_contenttypes_0002.py | django/contrib/auth/migrations/0006_require_contenttypes_0002.py | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("auth", "0005_alter_user_last_login_null"),
("contenttypes", "0002_remove_content_type_name"),
]
operations = [
# Ensure the contenttypes migration is applied before sending
# post_migrate signals (which create ContentTypes).
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/migrations/0002_alter_permission_name_max_length.py | django/contrib/auth/migrations/0002_alter_permission_name_max_length.py | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("auth", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="permission",
name="name",
field=models.CharField(max_length=255, verbose_name="name"),
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/migrations/0008_alter_user_username_max_length.py | django/contrib/auth/migrations/0008_alter_user_username_max_length.py | from django.contrib.auth import validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("auth", "0007_alter_validators_add_error_messages"),
]
operations = [
migrations.AlterField(
model_name="user",
name="username",
field=models.CharField(
error_messages={"unique": "A user with that username already exists."},
help_text=(
"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ "
"only."
),
max_length=150,
unique=True,
validators=[validators.UnicodeUsernameValidator()],
verbose_name="username",
),
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/migrations/0001_initial.py | django/contrib/auth/migrations/0001_initial.py | import django.contrib.auth.models
from django.contrib.auth import validators
from django.db import migrations, models
from django.utils import timezone
class Migration(migrations.Migration):
dependencies = [
("contenttypes", "__first__"),
]
operations = [
migrations.CreateModel(
name="Permission",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("name", models.CharField(max_length=50, verbose_name="name")),
(
"content_type",
models.ForeignKey(
to="contenttypes.ContentType",
on_delete=models.CASCADE,
verbose_name="content type",
),
),
("codename", models.CharField(max_length=100, verbose_name="codename")),
],
options={
"ordering": [
"content_type__app_label",
"content_type__model",
"codename",
],
"unique_together": {("content_type", "codename")},
"verbose_name": "permission",
"verbose_name_plural": "permissions",
},
managers=[
("objects", django.contrib.auth.models.PermissionManager()),
],
),
migrations.CreateModel(
name="Group",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"name",
models.CharField(unique=True, max_length=80, verbose_name="name"),
),
(
"permissions",
models.ManyToManyField(
to="auth.Permission", verbose_name="permissions", blank=True
),
),
],
options={
"verbose_name": "group",
"verbose_name_plural": "groups",
},
managers=[
("objects", django.contrib.auth.models.GroupManager()),
],
),
migrations.CreateModel(
name="User",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("password", models.CharField(max_length=128, verbose_name="password")),
(
"last_login",
models.DateTimeField(
default=timezone.now, verbose_name="last login"
),
),
(
"is_superuser",
models.BooleanField(
default=False,
help_text=(
"Designates that this user has all permissions without "
"explicitly assigning them."
),
verbose_name="superuser status",
),
),
(
"username",
models.CharField(
help_text=(
"Required. 30 characters or fewer. Letters, digits and "
"@/./+/-/_ only."
),
unique=True,
max_length=30,
verbose_name="username",
validators=[validators.UnicodeUsernameValidator()],
),
),
(
"first_name",
models.CharField(
max_length=30, verbose_name="first name", blank=True
),
),
(
"last_name",
models.CharField(
max_length=30, verbose_name="last name", blank=True
),
),
(
"email",
models.EmailField(
max_length=75, verbose_name="email address", blank=True
),
),
(
"is_staff",
models.BooleanField(
default=False,
help_text=(
"Designates whether the user can log into this admin site."
),
verbose_name="staff status",
),
),
(
"is_active",
models.BooleanField(
default=True,
verbose_name="active",
help_text=(
"Designates whether this user should be treated as active. "
"Unselect this instead of deleting accounts."
),
),
),
(
"date_joined",
models.DateTimeField(
default=timezone.now, verbose_name="date joined"
),
),
(
"groups",
models.ManyToManyField(
to="auth.Group",
verbose_name="groups",
blank=True,
related_name="user_set",
related_query_name="user",
help_text=(
"The groups this user belongs to. A user will get all "
"permissions granted to each of their groups."
),
),
),
(
"user_permissions",
models.ManyToManyField(
to="auth.Permission",
verbose_name="user permissions",
blank=True,
help_text="Specific permissions for this user.",
related_name="user_set",
related_query_name="user",
),
),
],
options={
"swappable": "AUTH_USER_MODEL",
"verbose_name": "user",
"verbose_name_plural": "users",
},
managers=[
("objects", django.contrib.auth.models.UserManager()),
],
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/migrations/0003_alter_user_email_max_length.py | django/contrib/auth/migrations/0003_alter_user_email_max_length.py | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("auth", "0002_alter_permission_name_max_length"),
]
operations = [
migrations.AlterField(
model_name="user",
name="email",
field=models.EmailField(
max_length=254, verbose_name="email address", blank=True
),
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
django/django | https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/contrib/auth/migrations/0010_alter_group_name_max_length.py | django/contrib/auth/migrations/0010_alter_group_name_max_length.py | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("auth", "0009_alter_user_last_name_max_length"),
]
operations = [
migrations.AlterField(
model_name="group",
name="name",
field=models.CharField(max_length=150, unique=True, verbose_name="name"),
),
]
| python | BSD-3-Clause | 3201a895cba335000827b28768a7b7105c81b415 | 2026-01-04T14:38:15.489092Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.