Toolforge Python 标志

Toolforge Python

社区
fuzheado
toolforge-python

Deploy Python web services on Wikimedia Toolforge — Flask (WSGI) and FastAPI (ASGI), gunicorn/uvicorn, Build Service and traditional Kubernetes backends, virtual environments, pip caching, PORT configuration, static files, logging, and common pitfalls

概览

发布者fuzheado
代码仓库Wikipedia-AI-Skills
技能名称toolforge-python
星标数
27
复刻数
10
附带文件
4
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载的 SKILL.md 文件,因此只有在请求确实匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 4 个随附文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 fuzheado 发布于 GitHub。请在安装前查看源内容。

安装

在 TypingMind 中安装 Toolforge Python AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/fuzheado/Wikipedia-AI-Skills/tree/main/.claude/skills/toolforge-python
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/fuzheado/Wikipedia-AI-Skills.git /tmp/Wikipedia-AI-Skills
mkdir -p .claude/skills
cp -r /tmp/Wikipedia-AI-Skills/.claude/skills/toolforge-python .claude/skills/toolforge-python
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Toolforge Python,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Toolforge Python。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Toolforge Python 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会获取指令,因此未使用的技能不会产生额外费用。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

⚠️ Prerequisites: This skill assumes you have a Toolforge account and can SSH in. See wikimedia-toolforge for account setup, tool creation, and basic SSH configuration.

⚠️ Over SSH, chain with sudo -niu tools.<tool> <cmd>. ssh host "become <tool>; <cmd>" runs <cmd> as you, not the tool — become uses exec, so it replaces the shell before the ; is reached. Passing the command as an argument (become <tool> <cmd>) is fine: the semicolon is the bug, not become. See wikimedia-toolforge §Guardrails & Common Pitfalls.

💡 Python is the dominant language on Toolforge. Most existing tools use Python, and the platform has first-class support for Python runtimes. This skill covers the standard Flask + gunicorn stack and FastAPI + uvicorn, which power the vast majority of Toolforge Python web services.

📖 Official documentation is spread across 7 pages on Wikitech with no clear "start here" signal. The table below maps each official page to this skill's SOPs so you know which to follow:

Wikitech PagePathMaps To
Help:Toolforge/PythonLanding pageAll SOPs — this skill is the curated replacement
Web/PythonTraditional uWSGISOP 1 (Flask) + SOP 1-D (conventions)
My first Flask OAuth toolTraditionalSOP 1 + wikimedia-auth-oauth
Buildpack Python (Flask)Build ServiceSOP 1-C
My first Python ASGI toolBuild ServiceSOP 1-B (FastAPI) + SOP 1-C
Buildpack DjangoBuild ServiceSOP 1-D (Django notes) + SOP 1-C

Recommendation for new tools: Use Build Service (SOP 1-C). It's the modern path, supports all Python versions, and avoids the fixed file layout of the traditional backend.

⚠️ Toolforge Rule #2 — Open Source License Required: All code in the Tools project must be published under an OSI-approved open source license. Add a LICENSE file to your repository before deploying. The absence of a license means default copyright laws apply, which is counter to the principles of the Wikimedia movement. See the full rules.

🔁 Deployment is moving to Toolforge Components (push-to-deploy) + opt-in alerting. For a long-lived tool, know the path: a public repo with a Procfile + a toolforge.yaml component config + a deployment token, so git push builds and deploys. The same config file is where you opt in to the new email alerting service (defaults.alerts.notify: true; opt-in opens October 2026, early access per tool on request). Commands, the supported/unsupported list and pitfalls: SOP 10 in the wikimedia-toolforge skill.


Quick Reference

GoalCommand / Pattern
Deploy a new Python serviceSee SOP 1
Choose a runtimepython3.11 (default), python3.9 (legacy) — see SOP 1.1
Start/restart a webservicebecome <tool> webservice --backend=kubernetes python3.11 start
See logsbecome <tool> kubectl logs -f deployment/<tool>
Set environment variablesbecome <tool> toolforge envvars create NAME value
Serve static filesUse Flask's send_from_directory() or static_url_path — see SOP 3
Install dependenciesUse a virtual environment and requirements.txt — see SOP 4
Run a cron jobbecome <tool> job schedule python3.11 --command 'python3 script.py' "0 * * * *"

SOP 1: Bootstrap a Python Web Service

The standard Toolforge Python stack: Flask + gunicorn, deployed in a virtual environment.

1.1 Choose a Runtime

Toolforge offers these Python runtime versions:

RuntimeKubernetes ImageStatus
python3.11docker-registry.tools.wmflabs.org/toolforge-python311-sssd-web:latest✅ Current default (Python 3.11)
python3.9docker-registry.tools.wmflabs.org/toolforge-python39-sssd-web:latest⚠️ Legacy (Python 3.9, available but not recommended for new tools)

The runtime image includes Python, pip, and system libraries. Your code and dependencies live on NFS at /data/project/<tool>/.

1.2 Create the Tool and Virtual Environment

bash
# From your local machine
ssh <user>@login.toolforge.org

# Create the tool (web UI only: https://toolsadmin.wikimedia.org/tools/create — no CLI equivalent)

# Enter the tool's home
become my-python-tool

# Create a virtual environment
python3 -m venv venv
source venv/bin/activate

# Install Flask and gunicorn
pip install flask gunicorn

1.3 Write Your App

Create app.py — a minimal Flask application:

python
# app.py — Flask web service for Toolforge
import os
from flask import Flask, jsonify, send_from_directory

app = Flask(__name__)

# Toolforge sets the PORT environment variable — your server must bind to it
PORT = int(os.environ.get('PORT', 8765))


@app.route('/')
def home():
    return '<h1>Hello from Toolforge!</h1>'


@app.route('/api/hello')
def hello():
    return jsonify(message='Hello from Toolforge!', status='ok')


@app.route('/api/status')
def status():
    return jsonify(status='running', port=PORT)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=PORT)

Key points:

  • Bind to 0.0.0.0:PORT (not 127.0.0.1) — Kubernetes needs the external interface
  • Always read PORT from the environment; the fallback (8765) is for local dev only
  • The if __name__ == '__main__' guard lets you test locally with python3 app.py

1.4 Deploy with gunicorn

gunicorn is the production WSGI server. Toolforge expects gunicorn to be installed in your virtual environment.

bash
# From your local machine — upload files
scp app.py <user>@login.toolforge.org:/data/project/my-python-tool/
scp requirements.txt <user>@login.toolforge.org:/data/project/my-python-tool/

# SSH in and set up
ssh <user>@login.toolforge.org
become my-python-tool

# Create venv and install dependencies
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# Start the webservice
webservice --backend=kubernetes python3.11 start

1.5 Verify

bash
# Check status
become my-python-tool webservice --backend=kubernetes python3.11 status

# View logs
become my-python-tool kubectl logs -f deployment/my-python-tool

# Test
curl https://my-python-tool.toolforge.org/
curl https://my-python-tool.toolforge.org/api/hello

SOP 1-B: FastAPI / ASGI (Alternative Framework)

FastAPI is a modern ASGI framework with automatic OpenAPI docs, async support, and built-in data validation. It runs on uvicorn — an ASGI server — rather than gunicorn directly.

Key Differences from Flask

Flask (WSGI)FastAPI (ASGI)
Servergunicorn directlygunicorn with uvicorn workers
AsyncLimitedNative async/await
DocsManualAuto-generated at /docs
ValidationManual or extensionsBuilt-in via Pydantic

Minimal FastAPI App

python
# app.py — FastAPI ASGI application for Toolforge
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def home():
    return {"Hello": "World"}


@app.get("/api/hello")
async def hello():
    return {"message": "Hello from Toolforge!", "status": "ok"}

Installing Dependencies

bash
pip install fastapi httpx "uvicorn[standard]" gunicorn

Procfile (Required for Build Service)

web: gunicorn app:app -k uvicorn.workers.UvicornWorker --workers=4 \
     --timeout 60 --bind 0.0.0.0 --forwarded-allow-ips=*

How this works: Gunicorn manages multiple uvicorn worker processes. Each worker runs an instance of the uvicorn ASGI server. Gunicorn handles process management and scaling; uvicorn handles async request processing.

Local Testing

bash
# FastAPI dev server (auto-reload, great for development)
uvicorn app:app --reload

# Open http://127.0.0.1:8000 to see the JSON response
# Open http://127.0.0.1:8000/docs for auto-generated API docs

Production Deploy (With Build Service)

FastAPI apps typically use the Build Service deployment path (see SOP 1-C). The key differences from Flask:

  • Prodfile uses -k uvicorn.workers.UvicornWorker
  • gunicorn wraps uvicorn, not the app directly
  • The app must be ASGI-compatible (FastAPI, Starlette, Quart, etc.)

SOP 1-C: Build Service Deployment (Container-Based)

The Build Service is the recommended path for new tools. Instead of scp-ing files and running webservice start, you push code to a Git repository and Toolforge builds a container image from it.

Benefits Over Traditional Deployment

Traditional (Kubernetes)Build Service (Container)
Manual scp uploadsgit push triggers deploy
Venv lives on NFSDependencies baked into image
Runtime tied to Toolforge imagesAny Python version via .python-version
ASGI/WSGI both work but manualNative support for both

Step-by-Step

1. Create a Git repo for your tool

Any public Git repository works as a build source — GitLab (gitlab.wikimedia.org/toolforge-repos/...), GitHub, or Gerrit. Two options:

  • Toolforge-hosted: go to toolsadmin.wikimedia.org → select your tool → Git repositories → create repository. Clone the resulting URL (use the public HTTPS URL for Build Service).
  • GitHub (verified working 2026-08-14 for the Reframe tool): push your repo to GitHub, then point the build at it:
bash
toolforge build start https://github.com/<user>/<repo>

2. Set up your project

bash
# Create a virtual environment for local dev
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install fastapi httpx "uvicorn[standard]" gunicorn
# Or for Flask:
pip install flask gunicorn

# Freeze dependencies
pip freeze > requirements.txt

⚠️ License requirement: All code on Toolforge must be under an OSI-approved open-source license. Include a license header in your source files and a LICENSE file in your repository. See the Right to fork policy.

3. Specify Python version (optional)

Create .python-version to pin a Python version — not runtime.txt. Buildpacks since heroku/python 6.x reject runtime.txt outright with Error: The runtime.txt file isn't supported ... replaced by the more widely supported .python-version file. Put the major.minor version only, no python- prefix, no patch:

bash
echo "3.12" > .python-version

If omitted, the latest available Python is used.

4. Create a Procfile

The Procfile tells Toolforge how to start your server:

web: gunicorn app:app -k uvicorn.workers.UvicornWorker --workers=4 --timeout 60 --bind 0.0.0.0 --forwarded-allow-ips=*

For Flask (WSGI, no uvicorn worker):

web: gunicorn app:app --workers=4 --timeout 60 --bind 0.0.0.0 --forwarded-allow-ips=*

The PORT environment variable is handled automatically — gunicorn reads it.

5. Commit and push

bash
git add .
git commit -m "Initial commit"
git push origin main

6. Build and start on Toolforge

bash
ssh <user>@login.toolforge.org
become my-python-tool

# Start the build (use the PUBLIC HTTPS URL)
toolforge build start https://gitlab.wikimedia.org/toolforge-repos/my-python-tool.git

# Check build status — wait for "ok (Succeeded)"
toolforge build show

# Start the webservice — give heavy apps memory headroom with -m (see gotchas)
toolforge webservice buildservice start --mount=none -m 1Gi

7. Verify

bash
curl https://my-python-tool.toolforge.org/
# FastAPI docs: https://my-python-tool.toolforge.org/docs

Updating Your App

bash
# Make changes locally, push, then rebuild
git add .
git commit -m "Update"
git push origin main

# SSH in and rebuild
ssh <user>@login.toolforge.org
become my-python-tool
toolforge build start https://gitlab.wikimedia.org/toolforge-repos/my-python-tool.git

Which Path to Choose?

ScenarioUse
New Python tool (2024+)Build Service (SOP 1-C)
FastAPI / ASGI appBuild Service required
Existing Flask app already on NFSTraditional (SOP 1)
Quick prototype, no Git setupTraditional (SOP 1)
Need to pin exact Python versionBuild Service with .python-version

Build Service Gotchas (field-tested 2026-08-14)

These bit the Reframe deployment (Flask + OpenCV on the buildservice backend) and are easy to hit again:

  • runtime.txt is dead. heroku/python ≥ 6.x fails the build with Error: The runtime.txt file isn't supported. Use .python-version containing just the major.minor (e.g. 3.11).
  • Default pod memory limit is 512 Mi. toolforge webservice buildservice start without -m gives you 512 Mi — fine for small Flask apps, but every gunicorn sync worker is a separate process, so memory-hungry libraries (OpenCV, numpy, ML models ~100–150 MB RSS each) blow the limit with --workers=4. Raise it at start time: toolforge webservice buildservice start --mount=none -m 1Gi.
  • OOM symptom signature: intermittent upstream connect error or disconnect/reset before headers. reset reason: connection termination from the ingress — looks like a network flake but is usually the container being killed mid-request. Diagnose:
    bash
    kubectl get pod <pod> -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}'
    # → OOMKilled
    kubectl top pods                     # live RSS
    kubectl get deployment -o jsonpath='{.spec.template.spec.containers[0].resources}'
    # → check memory limit
  • Budget memory per worker: sync workers × per-process RSS ≈ peak. Two workers at 1 Gi is comfortable for OpenCV-scale workloads.
  • gunicorn 26 prints a harmless startup error when its control server can't bind in the container (Control server error: [Errno 13] Permission denied) — non-fatal, ignore it.

SOP 1-D: Traditional Backend Conventions (uWSGI)

The traditional Kubernetes backend (not Build Service) uses uWSGI under the hood and expects specific file locations. If you're deploying via webservice --backend=kubernetes python3.11 start, these conventions apply.

Required File Layout

$HOME/www/python/
├── src/
│   └── app.py          # Entry point — must be named app.py
├── venv/                # Virtual environment — must be here
└── uwsgi.ini            # Optional uWSGI configuration

⚠️ These paths are non-negotiable for the traditional backend. Build Service (SOP 1-C) has no such restrictions — use whatever layout you prefer.

Entry Point Convention

The entry point must be $HOME/www/python/src/app.py and must expose a variable named app:

python
# $HOME/www/python/src/app.py
from flask import Flask
app = Flask(__name__)

For Django, create a wrapper that imports the WSGI application:

python
import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<tool-name>.settings')
app = get_wsgi_application()

💡 ModuleNotFoundError? Try importing os and setting the env var before importing Django — the settings module must be set before Django loads.

Virtual Environment

bash
# Open a shell in the target Python runtime
become my-tool
webservice --backend=kubernetes python3.11 shell

# Create the venv at the expected location
mkdir -p $HOME/www/python
python3 -m venv $HOME/www/python/venv
source $HOME/www/python/venv/bin/activate

# Upgrade pip (required for wheel support)
pip install --upgrade pip wheel

# Install dependencies
pip install -r $HOME/www/python/src/requirements.txt

# Exit and start
exit
toolforge webservice --backend=kubernetes python3.11 start

💡 Shortcut: Use webservice-python-bootstrap inside the shell to automate steps 2-6. For a fresh venv (e.g., switching Python versions): webservice-python-bootstrap --fresh

uWSGI Configuration (Optional)

Create $HOME/www/python/uwsgi.ini for additional configuration:

ini
[uwsgi]
# CORS headers
route = .* addheader:Access-Control-Allow-Origin: *

# Log rotation (10 MiB)
log-maxsize = 10485760

# Static file mapping (for Django)
static-map = /static=/data/project/<tool>/www/python/src/static

Django Production Setup

Building on the uWSGI wrapper above, a production Django deployment needs several additional configurations:

Static files: Django doesn't serve static files in production. Use WhiteNoise:

bash
pip install whitenoise
python
# settings.py
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static'
MIDDLEWARE = [
    'whitenoise.middleware.WhiteNoiseMiddleware',
    # ... other middleware
]

CSRF protection: Add your tool's domain to trusted origins:

python
# settings.py
CSRF_TRUSTED_ORIGINS = ['https://your-tool.toolforge.org']

Database (ToolsDB): For production, use ToolsDB instead of SQLite:

bash
pip install mysqlclient
bash
# Set these env vars via `toolforge envvars create`
DB_NAME=<name-of-db-in-toolsdb>
DJANGO_CONFIGURATION=Production
DJANGO_SETTINGS_MODULE=mysite.settings

Use django-configurations to manage separate dev/prod settings:

bash
pip install django-configurations
pip freeze > requirements.txt

Database migrations: Run as one-off jobs on Toolforge:

bash
# Build Service path (after toolforge build start)
toolforge jobs run \
    --image tool-<tool>/tool-<tool>:latest \
    --command "python manage.py migrate" \
    --wait migrate

Procfile for Django:

web: gunicorn mysite.wsgi --bind 0.0.0.0 --forwarded-allow-ips=*
migrate: python manage.py migrate

Logs

Traditional backend logs go to $HOME/uwsgi.log (not stdout/kubectl).

Troubleshooting: python_plugin.so Error

If you see this in logs:

open("/usr/lib/uwsgi/plugins/python_plugin.so"): No such file or directory
!!! UNABLE to load uWSGI plugin

It means your app is crashing on startup and the container is falling back to a Python 2 uWSGI plugin. Debug by opening a shell and running the app directly:

bash
webservice --backend=kubernetes python3.11 shell
source $HOME/www/python/venv/bin/activate
python $HOME/www/python/src/app.py  # See the actual error

SOP 2: The PORT Environment Variable

Toolforge's Kubernetes proxy routes incoming requests to your container. It sets the PORT environment variable — your server must bind to this port.

Do This

python
import os
PORT = int(os.environ.get('PORT', 8765))

# Flask dev server (for testing only — use gunicorn in production)
app.run(host='0.0.0.0', port=PORT)

gunicorn automatically reads PORT from the environment, so no extra configuration is needed:

bash
# gunicorn binds to PORT automatically
venv/bin/gunicorn --bind=0.0.0.0 app:app

Don't Do This

python
app.run(port=5000)       # ❌ Toolforge proxy won't find it
app.run(port=80)         # ❌ Not running as root
app.run(port='8080')     # ❌ PORT may be different

How It Works

Browser ─→ toolforge.org ─→ Kubernetes Ingress ─→ Pod:PORT
                                                      │
                                                process.env.PORT
                                               (e.g., "31245")

The PORT value is assigned per-pod and is not predictable — always read it from the environment.


SOP 3: Static File Serving

Using Flask

Flask serves static files from the static/ folder by default:

python
from flask import Flask, send_from_directory
import os

app = Flask(__name__)

# Option 1: Serve from Flask's built-in static route
# Place files in /data/project/my-tool/static/ — automatically served at /static/

# Option 2: Custom route for large files or specific directories
@app.route('/images/<path:filename>')
def serve_image(filename):
    return send_from_directory(
        os.path.join(app.root_path, 'static', 'images'),
        filename
    )

Cache-Control Headers

Toolforge uses Varnish as an HTTP accelerator. Set proper cache headers for performance:

Asset TypeRecommendationEffect
Images, thumbnailspublic, max-age=604800, immutable1 week, never revalidates
CSS, JSpublic, max-age=36001 hour
API responsesno-storeNever cached
python
@app.after_request
def add_cache_headers(response):
    if response.mimetype.startswith('image/'):
        response.headers['Cache-Control'] = 'public, max-age=604800, immutable'
    elif request.path.startswith('/static/'):
        response.headers['Cache-Control'] = 'public, max-age=3600'
    return response

SOP 4: Virtual Environments and Dependencies

The NFS Problem

Toolforge's NFS filesystem has slow metadata operations. Creating a virtual environment and running pip install can take minutes. Strategies to cope:

  1. Minimize dependencies — stick to Flask + stdlib when possible
  2. Use a single venv — create it once, reuse across deployments
  3. Pin exact versions — prevents pip from resolving dependency trees on every install

requirements.txt

txt
flask==3.1.0
gunicorn==23.0.0
requests==2.32.3

Full Setup

bash
# SSH into Toolforge
ssh <user>@login.toolforge.org
become my-python-tool

# Create venv (one time)
python3 -m venv venv

# Activate and install
source venv/bin/activate
pip install -r requirements.txt

# Freeze for reproducibility
pip freeze > requirements-frozen.txt

pip Cache Warning

pip's cache directory defaults to ~/.cache/pip, which is on NFS. For tools with many dependencies, this can slow things down. You can override it:

bash
# Use /tmp for pip cache (in-memory tmpfs, faster but ephemeral)
export PIP_CACHE_DIR=/tmp/pip-cache
pip install -r requirements.txt

⚠️ Do not run pip install in a cron job — it will be slow and unreliable. Install dependencies once in your venv and reference that in cron commands.


SOP 5: Environment Variables & Secrets

Store configuration and secrets via Toolforge's environment variable system:

bash
# Set (from a become shell)
become my-python-tool
toolforge envvars create SECRET_KEY your-secret-key-here
toolforge envvars create OAUTH_CLIENT_ID your-oauth-client-id
toolforge envvars create FLASK_ENV production

# List
toolforge envvars list

# Remove
toolforge envvars delete OLD_VAR

Accessing in Python

python
import os

SECRET_KEY = os.environ.get('SECRET_KEY')
OAUTH_CLIENT_ID = os.environ.get('OAUTH_CLIENT_ID')
FLASK_ENV = os.environ.get('FLASK_ENV', 'production')

⚠️ Never hardcode secrets in source files. Always use toolforge envvars create and read from the environment. Toolforge's env system stores values securely and they survive pod restarts.


SOP 6: Logging & Debugging

View Logs

bash
# Live tail
become my-python-tool kubectl logs -f deployment/my-python-tool

# Last 100 lines
become my-python-tool kubectl logs --tail=100 deployment/my-python-tool

Python Logging

Use the standard logging module with stdout (Toolforge captures it):

python
import logging
import sys

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    stream=sys.stdout,
)
logger = logging.getLogger(__name__)

logger.info(f"Server starting on port {PORT}")

Debugging a Crash Loop

If your pod keeps restarting:

  1. Check logs for tracebacks (kubectl logs shows the last crash)
  2. Test locally with the same Python version
  3. Verify requirements.txt is complete
  4. Check PORT binding — the most common crash cause

SOP 7: Cron Jobs

For batch processing, periodic syncs, or scheduled maintenance:

bash
# Run a script every hour
become my-python-tool job schedule python3.11 \
    --command '/data/project/my-python-tool/venv/bin/python3 /data/project/my-python-tool/cron/cleanup.py' \
    "0 * * * *"

# Run once
become my-python-tool job submit python3.11 \
    --command '/data/project/my-python-tool/venv/bin/python3 /data/project/my-python-tool/cron/backfill.py'

Cron Script Template

python
#!/usr/bin/env python3
# cron/cleanup.py — Scheduled script (no HTTP server needed)
import os
import time
from pathlib import Path

CACHE_DIR = Path('/data/project/my-python-tool/cache')
MAX_AGE_DAYS = 7


def cleanup():
    now = time.time()
    removed = 0
    for file in CACHE_DIR.glob('*'):
        if file.is_file():
            age_days = (now - file.stat().st_atime) / (60 * 60 * 24)
            if age_days > MAX_AGE_DAYS:
                file.unlink()
                removed += 1
    print(f'Cleanup: removed {removed} files (threshold: {MAX_AGE_DAYS} days)')


if __name__ == '__main__':
    cleanup()

⚠️ Always use full paths for the Python interpreter and scripts in cron commands. Cron runs in a minimal environment — no shell profile, no $PATH setup, no activated venv.


SOP 8: Restarting and Updating

Restart (zero-downtime)

bash
become my-python-tool webservice --backend=kubernetes python3.11 restart

The Kubernetes deployment performs a rolling restart — no downtime as long as your server starts quickly.

Update Code

bash
# Upload new version
scp app.py <user>@login.toolforge.org:/data/project/my-python-tool/

# If dependencies changed, reinstall
ssh <user>@login.toolforge.org "become my-python-tool bash -c 'source venv/bin/activate && pip install -r /data/project/my-python-tool/requirements.txt'"

# Restart
ssh <user>@login.toolforge.org "become my-python-tool webservice --backend=kubernetes python3.11 restart"

Stop

bash
become my-python-tool webservice --backend=kubernetes python3.11 stop

Reference: Quick Command Cheat Sheet

bash
# === Lifecycle ===
become my-python-tool webservice --backend=kubernetes python3.11 start
become my-python-tool webservice --backend=kubernetes python3.11 stop
become my-python-tool webservice --backend=kubernetes python3.11 restart
become my-python-tool webservice --backend=kubernetes python3.11 status

# === Logs ===
become my-python-tool kubectl logs -f deployment/my-python-tool
become my-python-tool kubectl logs --tail=100 deployment/my-python-tool

# === File Transfer (from local machine) ===
scp app.py <user>@login.toolforge.org:/data/project/my-python-tool/
scp -r static/ <user>@login.toolforge.org:/data/project/my-python-tool/

# === Virtual Environment ===
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# === Environment ===
become my-python-tool toolforge envvars create KEY value
become my-python-tool toolforge envvars list
become my-python-tool toolforge envvars delete KEY

# === Scheduled Jobs ===
become my-python-tool job schedule python3.11 \
    --command '/data/project/my-python-tool/venv/bin/python3 /data/project/my-python-tool/cron/script.py' \
    "0 * * * *"

Reference: Common Pitfalls

PitfallWhy It HappensPrevention
Missing PORTHardcoded port in codeAlways use int(os.environ.get('PORT', 8765))
Wrong bind addressapp.run() defaults to 127.0.0.1Always bind 0.0.0.0
Forgot venvpip installs globally, gunicorn not foundAlways source venv/bin/activate before pip install
Slow pip installNFS metadata operationsMinimize dependencies, pin versions, use PIP_CACHE_DIR=/tmp
No Cache-ControlMissing headers = re-download on every page loadAlways set cache headers for static assets
Cached 404 pages404 served with Cache-Control: publicUse no-store for error responses
Crash on startupImport error or missing dependencyTest locally with python3 app.py before deploying
Cron uses wrong PythonNo venv activation in cronAlways use full path to venv Python: /data/project/<tool>/venv/bin/python3
Stale venvDependencies outdated after code changeRe-run pip install -r requirements.txt after code updates
TLS/SSL errors from API callsMissing CA certificates in containerInstall certifi and use requests (handles this automatically)

Cross-References

Related SkillWhy
wikimedia-toolforgeAccount setup, tool creation, SSH, Kubernetes pods, cron jobs, database access
toolforge-nodejsNode.js equivalent — same platform, different language
wikimedia-api-accessUser-Agent, rate limiting, error handling
wikimedia-databaseSQL replicas — database access from Python tools
pywikibotBot framework — often deployed on Toolforge with Python
wikimedia-auth-oauthOAuth 1.0a/2.0 — authenticate users of your Python web app via Wikimedia accounts
wikimedia-codexCodex design system — components, design tokens, and icons for tool frontends

Tooling

🔧 Deploy Script (scripts/deploy-python.sh)

One-command deployment for Python tools:

bash
./scripts/deploy-python.sh my-python-tool

Uploads app.py, requirements.txt, and static files, reinstalls dependencies, and restarts the webservice.

🐍 Flask App Template (assets/flask-app-template.py)

Ready-to-deploy Flask app with:

  • Home page with status
  • Health check endpoint (/api/status)
  • Wikipedia API proxy (/api/summary/<title>, /api/search?q=...)
  • Static file serving with cache headers
  • Proper User-Agent for Wikimedia API requests
  • gunicorn compatibility
bash
cp assets/flask-app-template.py app.py
# Edit, test locally with `python3 app.py`, then deploy

🐍 Cron Script Template (assets/cron-template.py)

Template for scheduled Python scripts with:

  • Standard logging setup
  • Error handling and exit codes
  • NFS-safe file operations
  • Example: cache cleanup, data sync, batch processing

📚 requirements.txt Template (assets/requirements-template.txt)

Pre-configured dependency file with commonly used packages:

flask==3.1.0
gunicorn==23.0.0
requests==2.32.3

See Also

  • wikimedia-toolforge — Account setup, tool creation, SSH, Kubernetes pods, cron jobs, database access
    • SOP 9: Frontend Assets (Privacy-Preserving CDN) — Load JS/CSS/fonts from tools-static.wmflabs.org/cdnjs/ instead of external CDNs
  • toolforge-nodejs — Node.js-specific deployment patterns
  • wikimedia-api-access — User-Agent, rate limiting, error handling
  • wikimedia-security-and-privacy — CDN privacy risks and third-party script policies

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Toolforge Python AI 技能有什么作用?

Deploy Python web services on Wikimedia Toolforge — Flask (WSGI) and FastAPI (ASGI), gunicorn/uvicorn, Build Service and traditional Kubernetes backends, virtual environments, pip caching, PORT configuration, static files, logging, and common pitfalls

为什么在 TypingMind 中使用 Toolforge Python?

因为您只需安装一次,就能搭配任何模型使用。Toolforge Python 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型,甚至可以在聊天中途切换模型,而不会影响技能正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Toolforge Python?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/fuzheado/Wikipedia-AI-Skills/tree/main/.claude/skills/toolforge-python。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Toolforge Python?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Toolforge Python 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以搭配 Toolforge Python 使用,包括 GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等,都可在 TypingMind 中使用您自己的 API 密钥接入。

Toolforge Python AI 技能免费吗?

是的。该技能源自 fuzheado 在 GitHub 上以 MIT 许可证发布的项目。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇