安全编码是防御的第一道防线。本文介绍常见漏洞的编码防护方法。 ## SQL注入防护 ```python cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,)) ``` ## XSS防护 ```python from markupsafe import escape return f"
{escape(user_input)}
" ``` ## CSRF防护 ```python from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect(app) ``` ## 路径遍历防护 ```python import os.path def safe_path(base_dir, filename): filepath = os.path.realpath(os.path.join(base_dir, filename)) if not filepath.startswith(os.path.realpath(base_dir)): raise SecurityError("Path traversal detected") return filepath ``` 安全编码是一种习惯,不是一次性的检查。