n8n-code-python
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython Code Node (Beta)
Python代码节点(测试版)
Expert guidance for writing Python code in n8n Code nodes.
在n8n代码节点中编写Python代码的专业指导。
⚠️ Important: JavaScript First
⚠️ 重要提示:优先使用JavaScript
Recommendation: Use JavaScript for 95% of use cases. Only use Python when:
- You need specific Python standard library functions
- You're significantly more comfortable with Python syntax
- You're doing data transformations better suited to Python
Why JavaScript is preferred:
- Full n8n helper functions ($helpers.httpRequest, etc.)
- Luxon DateTime library for advanced date/time operations
- No external library limitations
- Better n8n documentation and community support
建议:95%的场景优先使用JavaScript。仅在以下情况使用Python:
- 你需要特定的Python标准库函数
- 你对Python语法更为熟悉
- 你正在进行更适合用Python处理的数据转换
优先选择JavaScript的原因:
- 完整的n8n辅助函数($helpers.httpRequest等)
- 用于高级日期/时间操作的Luxon DateTime库
- 无外部库限制
- 更完善的n8n文档和社区支持
Quick Start
快速入门
python
undefinedpython
undefinedBasic template for Python Code nodes
Python代码节点的基础模板
items = _input.all()
items = _input.all()
Process data
处理数据
processed = []
for item in items:
processed.append({
"json": {
**item["json"],
"processed": True,
"timestamp": datetime.now().isoformat()
}
})
return processed
undefinedprocessed = []
for item in items:
processed.append({
"json": {
**item["json"],
"processed": True,
"timestamp": datetime.now().isoformat()
}
})
return processed
undefinedEssential Rules
核心规则
- Consider JavaScript first - Use Python only when necessary
- Access data: ,
_input.all(), or_input.first()_input.item - CRITICAL: Must return format
[{"json": {...}}] - CRITICAL: Webhook data is under (not
_json["body"]directly)_json - CRITICAL LIMITATION: No external libraries (no requests, pandas, numpy)
- Standard library only: json, datetime, re, base64, hashlib, urllib.parse, math, random, statistics
- 优先考虑JavaScript - 仅在必要时使用Python
- 访问数据:、
_input.all()或_input.first()_input.item - 关键要求:必须返回格式
[{"json": {...}}] - 关键要求:Webhook数据位于下(而非直接在
_json["body"]中)_json - 关键限制:不支持外部库(无法使用requests、pandas、numpy等)
- 仅支持标准库:json、datetime、re、base64、hashlib、urllib.parse、math、random、statistics
Mode Selection Guide
模式选择指南
Same as JavaScript - choose based on your use case:
与JavaScript相同 - 根据你的使用场景选择:
Run Once for All Items (Recommended - Default)
对所有项目执行一次(推荐 - 默认)
Use this mode for: 95% of use cases
- How it works: Code executes once regardless of input count
- Data access: or
_input.all()array (Native mode)_items - Best for: Aggregation, filtering, batch processing, transformations
- Performance: Faster for multiple items (single execution)
python
undefined适用场景:95%的使用场景
- 工作原理:无论输入数量多少,代码仅执行一次
- 数据访问:或
_input.all()数组(原生模式)_items - 最适合:聚合、过滤、批处理、转换
- 性能:处理多个项目时速度更快(单次执行)
python
undefinedExample: Calculate total from all items
示例:计算所有项目的总和
all_items = _input.all()
total = sum(item["json"].get("amount", 0) for item in all_items)
return [{
"json": {
"total": total,
"count": len(all_items),
"average": total / len(all_items) if all_items else 0
}
}]
undefinedall_items = _input.all()
total = sum(item["json"].get("amount", 0) for item in all_items)
return [{
"json": {
"total": total,
"count": len(all_items),
"average": total / len(all_items) if all_items else 0
}
}]
undefinedRun Once for Each Item
对每个项目执行一次
Use this mode for: Specialized cases only
- How it works: Code executes separately for each input item
- Data access: or
_input.item(Native mode)_item - Best for: Item-specific logic, independent operations, per-item validation
- Performance: Slower for large datasets (multiple executions)
python
undefined适用场景:仅用于特殊场景
- 工作原理:代码会为每个输入项目单独执行
- 数据访问:或
_input.item(原生模式)_item - 最适合:项目专属逻辑、独立操作、逐个项目验证
- 性能:处理大型数据集时速度较慢(多次执行)
python
undefinedExample: Add processing timestamp to each item
示例:为每个项目添加处理时间戳
item = _input.item
return [{
"json": {
**item["json"],
"processed": True,
"processed_at": datetime.now().isoformat()
}
}]
---item = _input.item
return [{
"json": {
**item["json"],
"processed": True,
"processed_at": datetime.now().isoformat()
}
}]
---Python Modes: Beta vs Native
Python模式:测试版 vs 原生版
n8n offers two Python execution modes:
n8n提供两种Python执行模式:
Python (Beta) - Recommended
Python(测试版)- 推荐
- Use: ,
_input,_jsonhelper syntax_node - Best for: Most Python use cases
- Helpers available: ,
_now,_today_jmespath() - Import:
from datetime import datetime
python
undefined- 使用方式:、
_input、_json辅助语法_node - 最适合:大多数Python使用场景
- 可用辅助工具:、
_now、_today_jmespath() - 导入:
from datetime import datetime
python
undefinedPython (Beta) example
Python(测试版)示例
items = _input.all()
now = _now # Built-in datetime object
return [{
"json": {
"count": len(items),
"timestamp": now.isoformat()
}
}]
undefineditems = _input.all()
now = _now # 内置datetime对象
return [{
"json": {
"count": len(items),
"timestamp": now.isoformat()
}
}]
undefinedPython (Native) (Beta)
Python(原生版)(测试版)
- Use: ,
_itemsvariables only_item - No helpers: No ,
_input, etc._now - More limited: Standard Python only
- Use when: Need pure Python without n8n helpers
python
undefined- 使用方式:仅能使用、
_items变量_item - 无辅助工具:没有、
_input等_now - 限制更多:仅支持标准Python
- 适用场景:需要纯Python环境,无需n8n辅助工具时
python
undefinedPython (Native) example
Python(原生版)示例
processed = []
for item in _items:
processed.append({
"json": {
"id": item["json"].get("id"),
"processed": True
}
})
return processed
**Recommendation**: Use **Python (Beta)** for better n8n integration.
---processed = []
for item in _items:
processed.append({
"json": {
"id": item["json"].get("id"),
"processed": True
}
})
return processed
**建议**:使用**Python(测试版)**以获得更好的n8n集成效果。
---Data Access Patterns
数据访问模式
Pattern 1: _input.all() - Most Common
模式1:_input.all() - 最常用
Use when: Processing arrays, batch operations, aggregations
python
undefined适用场景:处理数组、批处理操作、聚合
python
undefinedGet all items from previous node
获取前一个节点的所有项目
all_items = _input.all()
all_items = _input.all()
Filter, transform as needed
根据需要过滤、转换数据
valid = [item for item in all_items if item["json"].get("status") == "active"]
processed = []
for item in valid:
processed.append({
"json": {
"id": item["json"]["id"],
"name": item["json"]["name"]
}
})
return processed
undefinedvalid = [item for item in all_items if item["json"].get("status") == "active"]
processed = []
for item in valid:
processed.append({
"json": {
"id": item["json"]["id"],
"name": item["json"]["name"]
}
})
return processed
undefinedPattern 2: _input.first() - Very Common
模式2:_input.first() - 非常常用
Use when: Working with single objects, API responses
python
undefined适用场景:处理单个对象、API响应
python
undefinedGet first item only
仅获取第一个项目
first_item = _input.first()
data = first_item["json"]
return [{
"json": {
"result": process_data(data),
"processed_at": datetime.now().isoformat()
}
}]
undefinedfirst_item = _input.first()
data = first_item["json"]
return [{
"json": {
"result": process_data(data),
"processed_at": datetime.now().isoformat()
}
}]
undefinedPattern 3: _input.item - Each Item Mode Only
模式3:_input.item - 仅适用于逐个项目模式
Use when: In "Run Once for Each Item" mode
python
undefined适用场景:处于“对每个项目执行一次”模式时
python
undefinedCurrent item in loop (Each Item mode only)
循环中的当前项目(仅适用于逐个项目模式)
current_item = _input.item
return [{
"json": {
**current_item["json"],
"item_processed": True
}
}]
undefinedcurrent_item = _input.item
return [{
"json": {
**current_item["json"],
"item_processed": True
}
}]
undefinedPattern 4: _node - Reference Other Nodes
模式4:_node - 引用其他节点
Use when: Need data from specific nodes in workflow
python
undefined适用场景:需要工作流中特定节点的数据时
python
undefinedGet output from specific node
获取特定节点的输出
webhook_data = _node["Webhook"]["json"]
http_data = _node["HTTP Request"]["json"]
return [{
"json": {
"combined": {
"webhook": webhook_data,
"api": http_data
}
}
}]
**See**: [DATA_ACCESS.md](DATA_ACCESS.md) for comprehensive guide
---webhook_data = _node["Webhook"]["json"]
http_data = _node["HTTP Request"]["json"]
return [{
"json": {
"combined": {
"webhook": webhook_data,
"api": http_data
}
}
}]
**参考**:[DATA_ACCESS.md](DATA_ACCESS.md)获取完整指南
---Critical: Webhook Data Structure
关键提示:Webhook数据结构
MOST COMMON MISTAKE: Webhook data is nested under
["body"]python
undefined最常见错误:Webhook数据嵌套在下
["body"]python
undefined❌ WRONG - Will raise KeyError
❌ 错误 - 会引发KeyError
name = _json["name"]
email = _json["email"]
name = _json["name"]
email = _json["email"]
✅ CORRECT - Webhook data is under ["body"]
✅ 正确 - Webhook数据位于["body"]下
name = _json["body"]["name"]
email = _json["body"]["email"]
name = _json["body"]["name"]
email = _json["body"]["email"]
✅ SAFER - Use .get() for safe access
✅ 更安全 - 使用.get()进行安全访问
webhook_data = _json.get("body", {})
name = webhook_data.get("name")
**Why**: Webhook node wraps all request data under `body` property. This includes POST data, query parameters, and JSON payloads.
**See**: [DATA_ACCESS.md](DATA_ACCESS.md) for full webhook structure details
---webhook_data = _json.get("body", {})
name = webhook_data.get("name")
**原因**:Webhook节点会将所有请求数据封装在`body`属性下,包括POST数据、查询参数和JSON负载。
**参考**:[DATA_ACCESS.md](DATA_ACCESS.md)获取完整的Webhook结构详情
---Return Format Requirements
返回格式要求
CRITICAL RULE: Always return list of dictionaries with key
"json"关键规则:必须返回包含键的字典列表
"json"Correct Return Formats
正确的返回格式
python
undefinedpython
undefined✅ Single result
✅ 单个结果
return [{
"json": {
"field1": value1,
"field2": value2
}
}]
return [{
"json": {
"field1": value1,
"field2": value2
}
}]
✅ Multiple results
✅ 多个结果
return [
{"json": {"id": 1, "data": "first"}},
{"json": {"id": 2, "data": "second"}}
]
return [
{"json": {"id": 1, "data": "first"}},
{"json": {"id": 2, "data": "second"}}
]
✅ List comprehension
✅ 列表推导式
transformed = [
{"json": {"id": item["json"]["id"], "processed": True}}
for item in _input.all()
if item["json"].get("valid")
]
return transformed
transformed = [
{"json": {"id": item["json"]["id"], "processed": True}}
for item in _input.all()
if item["json"].get("valid")
]
return transformed
✅ Empty result (when no data to return)
✅ 空结果(无数据返回时)
return []
return []
✅ Conditional return
✅ 条件返回
if should_process:
return [{"json": processed_data}]
else:
return []
undefinedif should_process:
return [{"json": processed_data}]
else:
return []
undefinedIncorrect Return Formats
错误的返回格式
python
undefinedpython
undefined❌ WRONG: Dictionary without list wrapper
❌ 错误:未用列表包裹的字典
return {
"json": {"field": value}
}
return {
"json": {"field": value}
}
❌ WRONG: List without json wrapper
❌ 错误:未用json包裹的列表
return [{"field": value}]
return [{"field": value}]
❌ WRONG: Plain string
❌ 错误:纯字符串
return "processed"
return "processed"
❌ WRONG: Incomplete structure
❌ 错误:不完整的结构
return [{"data": value}] # Should be {"json": value}
**Why it matters**: Next nodes expect list format. Incorrect format causes workflow execution to fail.
**See**: [ERROR_PATTERNS.md](ERROR_PATTERNS.md) #2 for detailed error solutions
---return [{"data": value}] # 应该是{"json": value}
**重要性**:后续节点需要列表格式,错误格式会导致工作流执行失败。
**参考**:[ERROR_PATTERNS.md](ERROR_PATTERNS.md) #2获取详细的错误解决方案
---Critical Limitation: No External Libraries
关键限制:不支持外部库
MOST IMPORTANT PYTHON LIMITATION: Cannot import external packages
Python最重要的限制:无法导入外部包
What's NOT Available
不可用的库
python
undefinedpython
undefined❌ NOT AVAILABLE - Will raise ModuleNotFoundError
❌ 不可用 - 会引发ModuleNotFoundError
import requests # ❌ No
import pandas # ❌ No
import numpy # ❌ No
import scipy # ❌ No
from bs4 import BeautifulSoup # ❌ No
import lxml # ❌ No
undefinedimport requests # ❌ 不支持
import pandas # ❌ 不支持
import numpy # ❌ 不支持
import scipy # ❌ 不支持
from bs4 import BeautifulSoup # ❌ 不支持
import lxml # ❌ 不支持
undefinedWhat IS Available (Standard Library)
可用的库(标准库)
python
undefinedpython
undefined✅ AVAILABLE - Standard library only
✅ 可用 - 仅支持标准库
import json # ✅ JSON parsing
import datetime # ✅ Date/time operations
import re # ✅ Regular expressions
import base64 # ✅ Base64 encoding/decoding
import hashlib # ✅ Hashing functions
import urllib.parse # ✅ URL parsing
import math # ✅ Math functions
import random # ✅ Random numbers
import statistics # ✅ Statistical functions
undefinedimport json # ✅ JSON解析
import datetime # ✅ 日期/时间操作
import re # ✅ 正则表达式
import base64 # ✅ Base64编码/解码
import hashlib # ✅ 哈希函数
import urllib.parse # ✅ URL解析
import math # ✅ 数学函数
import random # ✅ 随机数
import statistics # ✅ 统计函数
undefinedWorkarounds
替代方案
Need HTTP requests?
- ✅ Use HTTP Request node before Code node
- ✅ Or switch to JavaScript and use
$helpers.httpRequest()
Need data analysis (pandas/numpy)?
- ✅ Use Python statistics module for basic stats
- ✅ Or switch to JavaScript for most operations
- ✅ Manual calculations with lists and dictionaries
Need web scraping (BeautifulSoup)?
- ✅ Use HTTP Request node + HTML Extract node
- ✅ Or switch to JavaScript with regex/string methods
See: STANDARD_LIBRARY.md for complete reference
需要HTTP请求?
- ✅ 在代码节点前使用HTTP请求节点
- ✅ 或切换到JavaScript并使用
$helpers.httpRequest()
需要数据分析(pandas/numpy)?
- ✅ 使用Python的statistics模块进行基础统计
- ✅ 或切换到JavaScript执行大多数操作
- ✅ 使用列表和字典手动计算
需要网页抓取(BeautifulSoup)?
- ✅ 使用HTTP请求节点 + HTML提取节点
- ✅ 或切换到JavaScript并使用正则表达式/字符串方法
参考:STANDARD_LIBRARY.md获取完整参考
Common Patterns Overview
常见模式概述
Based on production workflows, here are the most useful Python patterns:
基于生产工作流,以下是最实用的Python模式:
1. Data Transformation
1. 数据转换
Transform all items with list comprehensions
python
items = _input.all()
return [
{
"json": {
"id": item["json"].get("id"),
"name": item["json"].get("name", "Unknown").upper(),
"processed": True
}
}
for item in items
]使用列表推导式转换所有项目
python
items = _input.all()
return [
{
"json": {
"id": item["json"].get("id"),
"name": item["json"].get("name", "Unknown").upper(),
"processed": True
}
}
for item in items
]2. Filtering & Aggregation
2. 过滤与聚合
Sum, filter, count with built-in functions
python
items = _input.all()
total = sum(item["json"].get("amount", 0) for item in items)
valid_items = [item for item in items if item["json"].get("amount", 0) > 0]
return [{
"json": {
"total": total,
"count": len(valid_items)
}
}]使用内置函数进行求和、过滤、计数
python
items = _input.all()
total = sum(item["json"].get("amount", 0) for item in items)
valid_items = [item for item in items if item["json"].get("amount", 0) > 0]
return [{
"json": {
"total": total,
"count": len(valid_items)
}
}]3. String Processing with Regex
3. 使用正则表达式处理字符串
Extract patterns from text
python
import re
items = _input.all()
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
all_emails = []
for item in items:
text = item["json"].get("text", "")
emails = re.findall(email_pattern, text)
all_emails.extend(emails)从文本中提取模式
python
import re
items = _input.all()
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
all_emails = []
for item in items:
text = item["json"].get("text", "")
emails = re.findall(email_pattern, text)
all_emails.extend(emails)Remove duplicates
去重
unique_emails = list(set(all_emails))
return [{
"json": {
"emails": unique_emails,
"count": len(unique_emails)
}
}]
undefinedunique_emails = list(set(all_emails))
return [{
"json": {
"emails": unique_emails,
"count": len(unique_emails)
}
}]
undefined4. Data Validation
4. 数据验证
Validate and clean data
python
items = _input.all()
validated = []
for item in items:
data = item["json"]
errors = []
# Validate fields
if not data.get("email"):
errors.append("Email required")
if not data.get("name"):
errors.append("Name required")
validated.append({
"json": {
**data,
"valid": len(errors) == 0,
"errors": errors if errors else None
}
})
return validated验证并清理数据
python
items = _input.all()
validated = []
for item in items:
data = item["json"]
errors = []
# 验证字段
if not data.get("email"):
errors.append("需要邮箱")
if not data.get("name"):
errors.append("需要姓名")
validated.append({
"json": {
**data,
"valid": len(errors) == 0,
"errors": errors if errors else None
}
})
return validated5. Statistical Analysis
5. 统计分析
Calculate statistics with statistics module
python
from statistics import mean, median, stdev
items = _input.all()
values = [item["json"].get("value", 0) for item in items if "value" in item["json"]]
if values:
return [{
"json": {
"mean": mean(values),
"median": median(values),
"stdev": stdev(values) if len(values) > 1 else 0,
"min": min(values),
"max": max(values),
"count": len(values)
}
}]
else:
return [{"json": {"error": "No values found"}}]See: COMMON_PATTERNS.md for 10 detailed Python patterns
使用statistics模块计算统计数据
python
from statistics import mean, median, stdev
items = _input.all()
values = [item["json"].get("value", 0) for item in items if "value" in item["json"]]
if values:
return [{
"json": {
"mean": mean(values),
"median": median(values),
"stdev": stdev(values) if len(values) > 1 else 0,
"min": min(values),
"max": max(values),
"count": len(values)
}
}]
else:
return [{"json": {"error": "未找到数值"}}]参考:COMMON_PATTERNS.md获取10种详细的Python模式
Error Prevention - Top 5 Mistakes
错误预防 - 五大常见错误
#1: Importing External Libraries (Python-Specific!)
#1:导入外部库(Python专属问题!)
python
undefinedpython
undefined❌ WRONG: Trying to import external library
❌ 错误:尝试导入外部库
import requests # ModuleNotFoundError!
import requests # 会引发ModuleNotFoundError!
✅ CORRECT: Use HTTP Request node or JavaScript
✅ 正确:使用HTTP请求节点或JavaScript
Add HTTP Request node before Code node
在代码节点前添加HTTP请求节点
OR switch to JavaScript and use $helpers.httpRequest()
或切换到JavaScript并使用$helpers.httpRequest()
undefinedundefined#2: Empty Code or Missing Return
#2:代码为空或缺少返回语句
python
undefinedpython
undefined❌ WRONG: No return statement
❌ 错误:无返回语句
items = _input.all()
items = _input.all()
Processing...
处理数据...
Forgot to return!
忘记返回!
✅ CORRECT: Always return data
✅ 正确:必须返回数据
items = _input.all()
items = _input.all()
Processing...
处理数据...
return [{"json": item["json"]} for item in items]
undefinedreturn [{"json": item["json"]} for item in items]
undefined#3: Incorrect Return Format
#3:返回格式错误
python
undefinedpython
undefined❌ WRONG: Returning dict instead of list
❌ 错误:返回字典而非列表
return {"json": {"result": "success"}}
return {"json": {"result": "success"}}
✅ CORRECT: List wrapper required
✅ 正确:需要列表包裹
return [{"json": {"result": "success"}}]
undefinedreturn [{"json": {"result": "success"}}]
undefined#4: KeyError on Dictionary Access
#4:字典访问引发KeyError
python
undefinedpython
undefined❌ WRONG: Direct access crashes if missing
❌ 错误:直接访问会在字段缺失时崩溃
name = _json["user"]["name"] # KeyError!
name = _json["user"]["name"] # 会引发KeyError!
✅ CORRECT: Use .get() for safe access
✅ 正确:使用.get()进行安全访问
name = _json.get("user", {}).get("name", "Unknown")
undefinedname = _json.get("user", {}).get("name", "Unknown")
undefined#5: Webhook Body Nesting
#5:Webhook数据嵌套错误
python
undefinedpython
undefined❌ WRONG: Direct access to webhook data
❌ 错误:直接访问Webhook数据
email = _json["email"] # KeyError!
email = _json["email"] # 会引发KeyError!
✅ CORRECT: Webhook data under ["body"]
✅ 正确:Webhook数据位于["body"]下
email = _json["body"]["email"]
email = _json["body"]["email"]
✅ BETTER: Safe access with .get()
✅ 更优:使用.get()进行安全访问
email = _json.get("body", {}).get("email", "no-email")
**See**: [ERROR_PATTERNS.md](ERROR_PATTERNS.md) for comprehensive error guide
---email = _json.get("body", {}).get("email", "无邮箱")
**参考**:[ERROR_PATTERNS.md](ERROR_PATTERNS.md)获取完整的错误指南
---Standard Library Reference
标准库参考
Most Useful Modules
最实用的模块
python
undefinedpython
undefinedJSON operations
JSON操作
import json
data = json.loads(json_string)
json_output = json.dumps({"key": "value"})
import json
data = json.loads(json_string)
json_output = json.dumps({"key": "value"})
Date/time
日期/时间
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
formatted = now.strftime("%Y-%m-%d")
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
formatted = now.strftime("%Y-%m-%d")
Regular expressions
正则表达式
import re
matches = re.findall(r'\d+', text)
cleaned = re.sub(r'[^\w\s]', '', text)
import re
matches = re.findall(r'\d+', text)
cleaned = re.sub(r'[^\w\s]', '', text)
Base64 encoding
Base64编码
import base64
encoded = base64.b64encode(data).decode()
decoded = base64.b64decode(encoded)
import base64
encoded = base64.b64encode(data).decode()
decoded = base64.b64decode(encoded)
Hashing
哈希
import hashlib
hash_value = hashlib.sha256(text.encode()).hexdigest()
import hashlib
hash_value = hashlib.sha256(text.encode()).hexdigest()
URL parsing
URL解析
import urllib.parse
params = urllib.parse.urlencode({"key": "value"})
parsed = urllib.parse.urlparse(url)
import urllib.parse
params = urllib.parse.urlencode({"key": "value"})
parsed = urllib.parse.urlparse(url)
Statistics
统计
from statistics import mean, median, stdev
average = mean([1, 2, 3, 4, 5])
**See**: [STANDARD_LIBRARY.md](STANDARD_LIBRARY.md) for complete reference
---from statistics import mean, median, stdev
average = mean([1, 2, 3, 4, 5])
**参考**:[STANDARD_LIBRARY.md](STANDARD_LIBRARY.md)获取完整参考
---Best Practices
最佳实践
1. Always Use .get() for Dictionary Access
1. 始终使用.get()访问字典
python
undefinedpython
undefined✅ SAFE: Won't crash if field missing
✅ 安全:字段缺失时不会崩溃
value = item["json"].get("field", "default")
value = item["json"].get("field", "default")
❌ RISKY: Crashes if field doesn't exist
❌ 危险:字段不存在时会崩溃
value = item["json"]["field"]
undefinedvalue = item["json"]["field"]
undefined2. Handle None/Null Values Explicitly
2. 显式处理None/空值
python
undefinedpython
undefined✅ GOOD: Default to 0 if None
✅ 良好实践:字段为None时默认设为0
amount = item["json"].get("amount") or 0
amount = item["json"].get("amount") or 0
✅ GOOD: Check for None explicitly
✅ 良好实践:显式检查None
text = item["json"].get("text")
if text is None:
text = ""
undefinedtext = item["json"].get("text")
if text is None:
text = ""
undefined3. Use List Comprehensions for Filtering
3. 使用列表推导式进行过滤
python
undefinedpython
undefined✅ PYTHONIC: List comprehension
✅ Python风格:列表推导式
valid = [item for item in items if item["json"].get("active")]
valid = [item for item in items if item["json"].get("active")]
❌ VERBOSE: Manual loop
❌ 冗余:手动循环
valid = []
for item in items:
if item["json"].get("active"):
valid.append(item)
undefinedvalid = []
for item in items:
if item["json"].get("active"):
valid.append(item)
undefined4. Return Consistent Structure
4. 返回一致的结构
python
undefinedpython
undefined✅ CONSISTENT: Always list with "json" key
✅ 一致:始终返回包含"json"键的列表
return [{"json": result}] # Single result
return results # Multiple results (already formatted)
return [] # No results
undefinedreturn [{"json": result}] # 单个结果
return results # 多个结果(已格式化)
return [] # 无结果
undefined5. Debug with print() Statements
5. 使用print()语句调试
python
undefinedpython
undefinedDebug statements appear in browser console (F12)
调试语句会显示在浏览器控制台(F12)
items = _input.all()
print(f"Processing {len(items)} items")
print(f"First item: {items[0] if items else 'None'}")
---items = _input.all()
print(f"正在处理 {len(items)} 个项目")
print(f"第一个项目:{items[0] if items else 'None'}")
---When to Use Python vs JavaScript
Python与JavaScript的使用场景对比
Use Python When:
优先使用Python的场景:
- ✅ You need module for statistical operations
statistics - ✅ You're significantly more comfortable with Python syntax
- ✅ Your logic maps well to list comprehensions
- ✅ You need specific standard library functions
- ✅ 需要模块执行统计操作
statistics - ✅ 你对Python语法更为熟悉
- ✅ 你的逻辑更适合用列表推导式实现
- ✅ 你需要特定的标准库函数
Use JavaScript When:
优先使用JavaScript的场景:
- ✅ You need HTTP requests ($helpers.httpRequest())
- ✅ You need advanced date/time (DateTime/Luxon)
- ✅ You want better n8n integration
- ✅ For 95% of use cases (recommended)
- ✅ 需要HTTP请求($helpers.httpRequest())
- ✅ 需要高级日期/时间处理(DateTime/Luxon)
- ✅ 你需要更好的n8n集成效果
- ✅ 95%的场景(推荐)
Consider Other Nodes When:
优先考虑其他节点的场景:
- ❌ Simple field mapping → Use Set node
- ❌ Basic filtering → Use Filter node
- ❌ Simple conditionals → Use IF or Switch node
- ❌ HTTP requests only → Use HTTP Request node
- ❌ 简单字段映射 → 使用设置节点
- ❌ 基础过滤 → 使用过滤节点
- ❌ 简单条件判断 → 使用IF或开关节点
- ❌ 仅需HTTP请求 → 使用HTTP请求节点
Integration with Other Skills
与其他技能的集成
Works With:
可集成的技能:
n8n Expression Syntax:
- Expressions use syntax in other nodes
{{ }} - Code nodes use Python directly (no )
{{ }} - When to use expressions vs code
n8n MCP Tools Expert:
- How to find Code node:
search_nodes({query: "code"}) - Get configuration help:
get_node_essentials("nodes-base.code") - Validate code:
validate_node_operation()
n8n Node Configuration:
- Mode selection (All Items vs Each Item)
- Language selection (Python vs JavaScript)
- Understanding property dependencies
n8n Workflow Patterns:
- Code nodes in transformation step
- When to use Python vs JavaScript in patterns
n8n Validation Expert:
- Validate Code node configuration
- Handle validation errors
- Auto-fix common issues
n8n Code JavaScript:
- When to use JavaScript instead
- Comparison of JavaScript vs Python features
- Migration from Python to JavaScript
n8n表达式语法:
- 其他节点中使用语法的表达式
{{ }} - 代码节点直接使用Python(无需)
{{ }} - 表达式与代码的使用场景对比
n8n MCP工具专家:
- 如何查找代码节点:
search_nodes({query: "code"}) - 获取配置帮助:
get_node_essentials("nodes-base.code") - 验证代码:
validate_node_operation()
n8n节点配置:
- 模式选择(所有项目 vs 逐个项目)
- 语言选择(Python vs JavaScript)
- 理解属性依赖关系
n8n工作流模式:
- 转换步骤中的代码节点
- 工作流模式中Python与JavaScript的选择
n8n验证专家:
- 验证代码节点配置
- 处理验证错误
- 自动修复常见问题
n8n JavaScript代码:
- 何时改用JavaScript
- JavaScript与Python的功能对比
- 从Python迁移到JavaScript
Quick Reference Checklist
快速参考检查清单
Before deploying Python Code nodes, verify:
- Considered JavaScript first - Using Python only when necessary
- Code is not empty - Must have meaningful logic
- Return statement exists - Must return list of dictionaries
- Proper return format - Each item:
{"json": {...}} - Data access correct - Using ,
_input.all(), or_input.first()_input.item - No external imports - Only standard library (json, datetime, re, etc.)
- Safe dictionary access - Using to avoid KeyError
.get() - Webhook data - Access via if from webhook
["body"] - Mode selection - "All Items" for most cases
- Output consistent - All code paths return same structure
部署Python代码节点前,请验证:
- 已优先考虑JavaScript - 仅在必要时使用Python
- 代码非空 - 必须包含有意义的逻辑
- 存在返回语句 - 必须返回数据
- 返回格式正确 - 每个项目为格式
{"json": {...}} - 数据访问方式正确 - 使用、
_input.all()或_input.first()_input.item - 未导入外部库 - 仅使用标准库(json、datetime、re等)
- 使用安全的字典访问方式 - 使用避免KeyError
.get() - Webhook数据访问正确 - 从下获取数据
["body"] - 模式选择正确 - 大多数场景使用“所有项目”模式
- 输出结构一致 - 所有代码路径返回相同结构
Additional Resources
额外资源
Related Files
相关文件
- DATA_ACCESS.md - Comprehensive Python data access patterns
- COMMON_PATTERNS.md - 10 Python patterns for n8n
- ERROR_PATTERNS.md - Top 5 errors and solutions
- STANDARD_LIBRARY.md - Complete standard library reference
- DATA_ACCESS.md - 完整的Python数据访问模式指南
- COMMON_PATTERNS.md - 10种n8n Python模式
- ERROR_PATTERNS.md - 五大常见错误及解决方案
- STANDARD_LIBRARY.md - 完整的标准库参考
n8n Documentation
n8n官方文档
- Code Node Guide: https://docs.n8n.io/code/code-node/
- Python in n8n: https://docs.n8n.io/code/builtin/python-modules/
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.
- 代码节点指南:https://docs.n8n.io/code/code-node/
- n8n中的Python:https://docs.n8n.io/code/builtin/python-modules/
准备好在n8n代码节点中编写Python代码了吗?但请优先考虑JavaScript! 仅在特定需求时使用Python,参考错误模式指南避免常见问题,并有效利用标准库。