[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-654d18c0-db36-4e33-aa35-9a00b7af4caf":3,"$f7HsIPer-GP3s0x9km2oGNl6nYU4U38_Y69dpp2-WIws":42},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":33},"654d18c0-db36-4e33-aa35-9a00b7af4caf","n8n-code-python","在n8n代码节点中编写Python代码。当在n8n中编写Python时，使用_input\u002F_json\u002F_node语法，使用标准库或需要了解n8n代码节点中Python的限制。","cat_coding_backend","mod_coding","sickn33,coding","---\nname: n8n-code-python\ndescription: Write Python code in n8n Code nodes. Use when writing Python in n8n, using _input\u002F_json\u002F_node syntax, working with standard library, or need to understand Python limitations in n8n Code nodes.\nrisk: unknown\nsource: community\n---\n\n# Python Code Node (Beta)\n\nExpert guidance for writing Python code in n8n Code nodes.\n\n---\n\n## ⚠️ Important: JavaScript First\n\n**Recommendation**: Use **JavaScript for 95% of use cases**. Only use Python when:\n- You need specific Python standard library functions\n- You're significantly more comfortable with Python syntax\n- You're doing data transformations better suited to Python\n\n**Why JavaScript is preferred:**\n- Full n8n helper functions ($helpers.httpRequest, etc.)\n- Luxon DateTime library for advanced date\u002Ftime operations\n- No external library limitations\n- Better n8n documentation and community support\n\n---\n\n## Quick Start\n\n```python\n# Basic template for Python Code nodes\nitems = _input.all()\n\n# Process data\nprocessed = []\nfor item in items:\n    processed.append({\n        \"json\": {\n            **item[\"json\"],\n            \"processed\": True,\n            \"timestamp\": datetime.now().isoformat()\n        }\n    })\n\nreturn processed\n```\n\n### Essential Rules\n\n1. **Consider JavaScript first** - Use Python only when necessary\n2. **Access data**: `_input.all()`, `_input.first()`, or `_input.item`\n3. **CRITICAL**: Must return `[{\"json\": {...}}]` format\n4. **CRITICAL**: Webhook data is under `_json[\"body\"]` (not `_json` directly)\n5. **CRITICAL LIMITATION**: **No external libraries** (no requests, pandas, numpy)\n6. **Standard library only**: json, datetime, re, base64, hashlib, urllib.parse, math, random, statistics\n\n---\n\n## Mode Selection Guide\n\nSame as JavaScript - choose based on your use case:\n\n### Run Once for All Items (Recommended - Default)\n\n**Use this mode for:** 95% of use cases\n\n- **How it works**: Code executes **once** regardless of input count\n- **Data access**: `_input.all()` or `_items` array (Native mode)\n- **Best for**: Aggregation, filtering, batch processing, transformations\n- **Performance**: Faster for multiple items (single execution)\n\n```python\n# Example: Calculate total from all items\nall_items = _input.all()\ntotal = sum(item[\"json\"].get(\"amount\", 0) for item in all_items)\n\nreturn [{\n    \"json\": {\n        \"total\": total,\n        \"count\": len(all_items),\n        \"average\": total \u002F len(all_items) if all_items else 0\n    }\n}]\n```\n\n### Run Once for Each Item\n\n**Use this mode for:** Specialized cases only\n\n- **How it works**: Code executes **separately** for each input item\n- **Data access**: `_input.item` or `_item` (Native mode)\n- **Best for**: Item-specific logic, independent operations, per-item validation\n- **Performance**: Slower for large datasets (multiple executions)\n\n```python\n# Example: Add processing timestamp to each item\nitem = _input.item\n\nreturn [{\n    \"json\": {\n        **item[\"json\"],\n        \"processed\": True,\n        \"processed_at\": datetime.now().isoformat()\n    }\n}]\n```\n\n---\n\n## Python Modes: Beta vs Native\n\nn8n offers two Python execution modes:\n\n### Python (Beta) - Recommended\n- **Use**: `_input`, `_json`, `_node` helper syntax\n- **Best for**: Most Python use cases\n- **Helpers available**: `_now`, `_today`, `_jmespath()`\n- **Import**: `from datetime import datetime`\n\n```python\n# Python (Beta) example\nitems = _input.all()\nnow = _now  # Built-in datetime object\n\nreturn [{\n    \"json\": {\n        \"count\": len(items),\n        \"timestamp\": now.isoformat()\n    }\n}]\n```\n\n### Python (Native) (Beta)\n- **Use**: `_items`, `_item` variables only\n- **No helpers**: No `_input`, `_now`, etc.\n- **More limited**: Standard Python only\n- **Use when**: Need pure Python without n8n helpers\n\n```python\n# Python (Native) example\nprocessed = []\n\nfor item in _items:\n    processed.append({\n        \"json\": {\n            \"id\": item[\"json\"].get(\"id\"),\n            \"processed\": True\n        }\n    })\n\nreturn processed\n```\n\n**Recommendation**: Use **Python (Beta)** for better n8n integration.\n\n---\n\n## Data Access Patterns\n\n### Pattern 1: _input.all() - Most Common\n\n**Use when**: Processing arrays, batch operations, aggregations\n\n```python\n# Get all items from previous node\nall_items = _input.all()\n\n# Filter, transform as needed\nvalid = [item for item in all_items if item[\"json\"].get(\"status\") == \"active\"]\n\nprocessed = []\nfor item in valid:\n    processed.append({\n        \"json\": {\n            \"id\": item[\"json\"][\"id\"],\n            \"name\": item[\"json\"][\"name\"]\n        }\n    })\n\nreturn processed\n```\n\n### Pattern 2: _input.first() - Very Common\n\n**Use when**: Working with single objects, API responses\n\n```python\n# Get first item only\nfirst_item = _input.first()\ndata = first_item[\"json\"]\n\nreturn [{\n    \"json\": {\n        \"result\": process_data(data),\n        \"processed_at\": datetime.now().isoformat()\n    }\n}]\n```\n\n### Pattern 3: _input.item - Each Item Mode Only\n\n**Use when**: In \"Run Once for Each Item\" mode\n\n```python\n# Current item in loop (Each Item mode only)\ncurrent_item = _input.item\n\nreturn [{\n    \"json\": {\n        **current_item[\"json\"],\n        \"item_processed\": True\n    }\n}]\n```\n\n### Pattern 4: _node - Reference Other Nodes\n\n**Use when**: Need data from specific nodes in workflow\n\n```python\n# Get output from specific node\nwebhook_data = _node[\"Webhook\"][\"json\"]\nhttp_data = _node[\"HTTP Request\"][\"json\"]\n\nreturn [{\n    \"json\": {\n        \"combined\": {\n            \"webhook\": webhook_data,\n            \"api\": http_data\n        }\n    }\n}]\n```\n\n**See**: DATA_ACCESS.md for comprehensive guide\n\n---\n\n## Critical: Webhook Data Structure\n\n**MOST COMMON MISTAKE**: Webhook data is nested under `[\"body\"]`\n\n```python\n# ❌ WRONG - Will raise KeyError\nname = _json[\"name\"]\nemail = _json[\"email\"]\n\n# ✅ CORRECT - Webhook data is under [\"body\"]\nname = _json[\"body\"][\"name\"]\nemail = _json[\"body\"][\"email\"]\n\n# ✅ SAFER - Use .get() for safe access\nwebhook_data = _json.get(\"body\", {})\nname = webhook_data.get(\"name\")\n```\n\n**Why**: Webhook node wraps all request data under `body` property. This includes POST data, query parameters, and JSON payloads.\n\n**See**: DATA_ACCESS.md for full webhook structure details\n\n---\n\n## Return Format Requirements\n\n**CRITICAL RULE**: Always return list of dictionaries with `\"json\"` key\n\n### Correct Return Formats\n\n```python\n# ✅ Single result\nreturn [{\n    \"json\": {\n        \"field1\": value1,\n        \"field2\": value2\n    }\n}]\n\n# ✅ Multiple results\nreturn [\n    {\"json\": {\"id\": 1, \"data\": \"first\"}},\n    {\"json\": {\"id\": 2, \"data\": \"second\"}}\n]\n\n# ✅ List comprehension\ntransformed = [\n    {\"json\": {\"id\": item[\"json\"][\"id\"], \"processed\": True}}\n    for item in _input.all()\n    if item[\"json\"].get(\"valid\")\n]\nreturn transformed\n\n# ✅ Empty result (when no data to return)\nreturn []\n\n# ✅ Conditional return\nif should_process:\n    return [{\"json\": processed_data}]\nelse:\n    return []\n```\n\n### Incorrect Return Formats\n\n```python\n# ❌ WRONG: Dictionary without list wrapper\nreturn {\n    \"json\": {\"field\": value}\n}\n\n# ❌ WRONG: List without json wrapper\nreturn [{\"field\": value}]\n\n# ❌ WRONG: Plain string\nreturn \"processed\"\n\n# ❌ WRONG: Incomplete structure\nreturn [{\"data\": value}]  # Should be {\"json\": value}\n```\n\n**Why it matters**: Next nodes expect list format. Incorrect format causes workflow execution to fail.\n\n**See**: ERROR_PATTERNS.md #2 for detailed error solutions\n\n---\n\n## Critical Limitation: No External Libraries\n\n**MOST IMPORTANT PYTHON LIMITATION**: Cannot import external packages\n\n### What's NOT Available\n\n```python\n# ❌ NOT AVAILABLE - Will raise ModuleNotFoundError\nimport requests  # ❌ No\nimport pandas  # ❌ No\nimport numpy  # ❌ No\nimport scipy  # ❌ No\nfrom bs4 import BeautifulSoup  # ❌ No\nimport lxml  # ❌ No\n```\n\n### What IS Available (Standard Library)\n\n```python\n# ✅ AVAILABLE - Standard library only\nimport json  # ✅ JSON parsing\nimport datetime  # ✅ Date\u002Ftime operations\nimport re  # ✅ Regular expressions\nimport base64  # ✅ Base64 encoding\u002Fdecoding\nimport hashlib  # ✅ Hashing functions\nimport urllib.parse  # ✅ URL parsing\nimport math  # ✅ Math functions\nimport random  # ✅ Random numbers\nimport statistics  # ✅ Statistical functions\n```\n\n### Workarounds\n\n**Need HTTP requests?**\n- ✅ Use **HTTP Request node** before Code node\n- ✅ Or switch to **JavaScript** and use `$helpers.httpRequest()`\n\n**Need data analysis (pandas\u002Fnumpy)?**\n- ✅ Use Python **statistics** module for basic stats\n- ✅ Or switch to **JavaScript** for most operations\n- ✅ Manual calculations with lists and dictionaries\n\n**Need web scraping (BeautifulSoup)?**\n- ✅ Use **HTTP Request node** + **HTML Extract node**\n- ✅ Or switch to **JavaScript** with regex\u002Fstring methods\n\n**See**: STANDARD_LIBRARY.md for complete reference\n\n---\n\n## Common Patterns Overview\n\nBased on production workflows, here are the most useful Python patterns:\n\n### 1. Data Transformation\nTransform all items with list comprehensions\n\n```python\nitems = _input.all()\n\nreturn [\n    {\n        \"json\": {\n            \"id\": item[\"json\"].get(\"id\"),\n            \"name\": item[\"json\"].get(\"name\", \"Unknown\").upper(),\n            \"processed\": True\n        }\n    }\n    for item in items\n]\n```\n\n### 2. Filtering & Aggregation\nSum, filter, count with built-in functions\n\n```python\nitems = _input.all()\ntotal = sum(item[\"json\"].get(\"amount\", 0) for item in items)\nvalid_items = [item for item in items if item[\"json\"].get(\"amount\", 0) > 0]\n\nreturn [{\n    \"json\": {\n        \"total\": total,\n        \"count\": len(valid_items)\n    }\n}]\n```\n\n### 3. String Processing with Regex\nExtract patterns from text\n\n```python\nimport re\n\nitems = _input.all()\nemail_pattern = r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n\nall_emails = []\nfor item in items:\n    text = item[\"json\"].get(\"text\", \"\")\n    emails = re.findall(email_pattern, text)\n    all_emails.extend(emails)\n\n# Remove duplicates\nunique_emails = list(set(all_emails))\n\nreturn [{\n    \"json\": {\n        \"emails\": unique_emails,\n        \"count\": len(unique_emails)\n    }\n}]\n```\n\n### 4. Data Validation\nValidate and clean data\n\n```python\nitems = _input.all()\nvalidated = []\n\nfor item in items:\n    data = item[\"json\"]\n    errors = []\n\n    # Validate fields\n    if not data.get(\"email\"):\n        errors.append(\"Email required\")\n    if not data.get(\"name\"):\n        errors.append(\"Name required\")\n\n    validated.append({\n        \"json\": {\n            **data,\n            \"valid\": len(errors) == 0,\n            \"errors\": errors if errors else None\n        }\n    })\n\nreturn validated\n```\n\n### 5. Statistical Analysis\nCalculate statistics with statistics module\n\n```python\nfrom statistics import mean, median, stdev\n\nitems = _input.all()\nvalues = [item[\"json\"].get(\"value\", 0) for item in items if \"value\" in item[\"json\"]]\n\nif values:\n    return [{\n        \"json\": {\n            \"mean\": mean(values),\n            \"median\": median(values),\n            \"stdev\": stdev(values) if len(values) > 1 else 0,\n            \"min\": min(values),\n            \"max\": max(values),\n            \"count\": len(values)\n        }\n    }]\nelse:\n    return [{\"json\": {\"error\": \"No values found\"}}]\n```\n\n**See**: COMMON_PATTERNS.md for 10 detailed Python patterns\n\n---\n\n## Error Prevention - Top 5 Mistakes\n\n### #1: Importing External Libraries (Python-Specific!)\n\n```python\n# ❌ WRONG: Trying to import external library\nimport requests  # ModuleNotFoundError!\n\n# ✅ CORRECT: Use HTTP Request node or JavaScript\n# Add HTTP Request node before Code node\n# OR switch to JavaScript and use $helpers.httpRequest()\n```\n\n### #2: Empty Code or Missing Return\n\n```python\n# ❌ WRONG: No return statement\nitems = _input.all()\n# Processing...\n# Forgot to return!\n\n# ✅ CORRECT: Always return data\nitems = _input.all()\n# Processing...\nreturn [{\"json\": item[\"json\"]} for item in items]\n```\n\n### #3: Incorrect Return Format\n\n```python\n# ❌ WRONG: Returning dict instead of list\nreturn {\"json\": {\"result\": \"success\"}}\n\n# ✅ CORRECT: List wrapper required\nreturn [{\"json\": {\"result\": \"success\"}}]\n```\n\n### #4: KeyError on Dictionary Access\n\n```python\n# ❌ WRONG: Direct access crashes if missing\nname = _json[\"user\"][\"name\"]  # KeyError!\n\n# ✅ CORRECT: Use .get() for safe access\nname = _json.get(\"user\", {}).get(\"name\", \"Unknown\")\n```\n\n### #5: Webhook Body Nesting\n\n```python\n# ❌ WRONG: Direct access to webhook data\nemail = _json[\"email\"]  # KeyError!\n\n# ✅ CORRECT: Webhook data under [\"body\"]\nemail = _json[\"body\"][\"email\"]\n\n# ✅ BETTER: Safe access with .get()\nemail = _json.get(\"body\", {}).get(\"email\", \"no-email\")\n```\n\n**See**: ERROR_PATTERNS.md for comprehensive error guide\n\n---\n\n## Standard Library Reference\n\n### Most Useful Modules\n\n```python\n# JSON operations\nimport json\ndata = json.loads(json_string)\njson_output = json.dumps({\"key\": \"value\"})\n\n# Date\u002Ftime\nfrom datetime import datetime, timedelta\nnow = datetime.now()\ntomorrow = now + timedelta(days=1)\nformatted = now.strftime(\"%Y-%m-%d\")\n\n# Regular expressions\nimport re\nmatches = re.findall(r'\\d+', text)\ncleaned = re.sub(r'[^\\w\\s]', '', text)\n\n# Base64 encoding\nimport base64\nencoded = base64.b64encode(data).decode()\ndecoded = base64.b64decode(encoded)\n\n# Hashing\nimport hashlib\nhash_value = hashlib.sha256(text.encode()).hexdigest()\n\n# URL parsing\nimport urllib.parse\nparams = urllib.parse.urlencode({\"key\": \"value\"})\nparsed = urllib.parse.urlparse(url)\n\n# Statistics\nfrom statistics import mean, median, stdev\naverage = mean([1, 2, 3, 4, 5])\n```\n\n**See**: STANDARD_LIBRARY.md for complete reference\n\n---\n\n## Best Practices\n\n### 1. Always Use .get() for Dictionary Access\n\n```python\n# ✅ SAFE: Won't crash if field missing\nvalue = item[\"json\"].get(\"field\", \"default\")\n\n# ❌ RISKY: Crashes if field doesn't exist\nvalue = item[\"json\"][\"field\"]\n```\n\n### 2. Handle None\u002FNull Values Explicitly\n\n```python\n# ✅ GOOD: Default to 0 if None\namount = item[\"json\"].get(\"amount\") or 0\n\n# ✅ GOOD: Check for None explicitly\ntext = item[\"json\"].get(\"text\")\nif text is None:\n    text = \"\"\n```\n\n### 3. Use List Comprehensions for Filtering\n\n```python\n# ✅ PYTHONIC: List comprehension\nvalid = [item for item in items if item[\"json\"].get(\"active\")]\n\n# ❌ VERBOSE: Manual loop\nvalid = []\nfor item in items:\n    if item[\"json\"].get(\"active\"):\n        valid.append(item)\n```\n\n### 4. Return Consistent Structure\n\n```python\n# ✅ CONSISTENT: Always list with \"json\" key\nreturn [{\"json\": result}]  # Single result\nreturn results  # Multiple results (already formatted)\nreturn []  # No results\n```\n\n### 5. Debug with print() Statements\n\n```python\n# Debug statements appear in browser console (F12)\nitems = _input.all()\nprint(f\"Processing {len(items)} items\")\nprint(f\"First item: {items[0] if items else 'None'}\")\n```\n\n---\n\n## When to Use Python vs JavaScript\n\n### Use Python When:\n- ✅ You need `statistics` module for statistical operations\n- ✅ You're significantly more comfortable with Python syntax\n- ✅ Your logic maps well to list comprehensions\n- ✅ You need specific standard library functions\n\n### Use JavaScript When:\n- ✅ You need HTTP requests ($helpers.httpRequest())\n- ✅ You need advanced date\u002Ftime (DateTime\u002FLuxon)\n- ✅ You want better n8n integration\n- ✅ **For 95% of use cases** (recommended)\n\n### Consider Other Nodes When:\n- ❌ Simple field mapping → Use **Set** node\n- ❌ Basic filtering → Use **Filter** node\n- ❌ Simple conditionals → Use **IF** or **Switch** node\n- ❌ HTTP requests only → Use **HTTP Request** node\n\n---\n\n## Integration with Other Skills\n\n### Works With:\n\n**n8n Expression Syntax**:\n- Expressions use `{{ }}` syntax in other nodes\n- Code nodes use Python directly (no `{{ }}`)\n- When to use expressions vs code\n\n**n8n MCP Tools Expert**:\n- How to find Code node: `search_nodes({query: \"code\"})`\n- Get configuration help: `get_node_essentials(\"nodes-base.code\")`\n- Validate code: `validate_node_operation()`\n\n**n8n Node Configuration**:\n- Mode selection (All Items vs Each Item)\n- Language selection (Python vs JavaScript)\n- Understanding property dependencies\n\n**n8n Workflow Patterns**:\n- Code nodes in transformation step\n- When to use Python vs JavaScript in patterns\n\n**n8n Validation Expert**:\n- Validate Code node configuration\n- Handle validation errors\n- Auto-fix common issues\n\n**n8n Code JavaScript**:\n- When to use JavaScript instead\n- Comparison of JavaScript vs Python features\n- Migration from Python to JavaScript\n\n---\n\n## Quick Reference Checklist\n\nBefore deploying Python Code nodes, verify:\n\n- [ ] **Considered JavaScript first** - Using Python only when necessary\n- [ ] **Code is not empty** - Must have meaningful logic\n- [ ] **Return statement exists** - Must return list of dictionaries\n- [ ] **Proper return format** - Each item: `{\"json\": {...}}`\n- [ ] **Data access correct** - Using `_input.all()`, `_input.first()`, or `_input.item`\n- [ ] **No external imports** - Only standard library (json, datetime, re, etc.)\n- [ ] **Safe dictionary access** - Using `.get()` to avoid KeyError\n- [ ] **Webhook data** - Access via `[\"body\"]` if from webhook\n- [ ] **Mode selection** - \"All Items\" for most cases\n- [ ] **Output consistent** - All code paths return same structure\n\n---\n\n## Additional Resources\n\n### Related Files\n- DATA_ACCESS.md - Comprehensive Python data access patterns\n- COMMON_PATTERNS.md - 10 Python patterns for n8n\n- ERROR_PATTERNS.md - Top 5 errors and solutions\n- STANDARD_LIBRARY.md - Complete standard library reference\n\n### n8n Documentation\n- Code Node Guide: https:\u002F\u002Fdocs.n8n.io\u002Fcode\u002Fcode-node\u002F\n- Python in n8n: https:\u002F\u002Fdocs.n8n.io\u002Fcode\u002Fbuiltin\u002Fpython-modules\u002F\n\n---\n\n**Ready to write Python in n8n Code nodes - but consider JavaScript first!** Use Python for specific needs, reference the error patterns guide to avoid common mistakes, and leverage the standard library effectively.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,117,260,"2026-05-16 13:30:09",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":25,"skillCount":32,"createdAt":26},"后端开发","backend","mdi-server","API、数据库、服务端架构",296,[34],{"id":35,"skillId":4,"version":36,"fileName":37,"fileSize":38,"filePath":39,"fileHash":40,"manifest":41,"createdAt":19},"edce19e2-43ef-43ad-b44c-5bf9e6196aac","1.0.0","n8n-code-python.zip",6220,"uploads\u002Fskills\u002F654d18c0-db36-4e33-aa35-9a00b7af4caf\u002Fn8n-code-python.zip","fad835df23b22e4072bdeca1ecb9de630b59cf4d5b81b9a3fdaa7c3c44a3d909","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":18092}]",{"code":43,"message":44,"data":45},200,"success",{"items":46,"stats":47,"page":50},[],{"averageRating":48,"totalRatings":48,"ratingCounts":49},0,[48,48,48,48,48],{"limit":51,"offset":48,"hasMore":52,"nextOffset":51,"ratedOnly":16},15,false]