Whether you're building an API, a CLI tool, or a machine learning pipeline, security vulnerabilities can sneak into your code without you realizing. Here's how to lock it down.
1. Never Hardcode Secrets
Bad:
API_KEY = "sk-1234567890abcdef"
DATABASE_URL = "postgres://admin:password123@db.example.com"
Good:
import os
API_KEY = os.environ.get("API_KEY")
DATABASE_URL = os.environ.get("DATABASE_URL")
Use .env files locally (with python-dotenv), but never commit them:
# .gitignore
.env
*.pem
secrets.json
2. Avoid SQL Injection
Bad:
query = f"SELECT * FROM users WHERE id = {user_input}"
cursor.execute(query)
Good:
cursor.execute("SELECT * FROM users WHERE id = %s", (user_input,))
Always use parameterized queries. ORMs like SQLAlchemy handle this automatically.
3. Don't Use eval() or exec()
These execute arbitrary code. If user input ever reaches them, you're compromised.
# NEVER do this
result = eval(user_input)
If you need to parse data, use json.loads() or ast.literal_eval() for safe alternatives.
4. Pin Your Dependencies
Unpinned dependencies can introduce vulnerabilities:
# Bad: requirements.txt
requests
flask
# Good: requirements.txt
requests==2.31.0
flask==3.0.0
Run pip freeze > requirements.txt and audit regularly.
5. Use Security Linters
Add these to your CI pipeline:
pip install bandit safety
# Scan code for vulnerabilities
bandit -r your_project/
# Check dependencies for known CVEs
safety check
6. Automate Security in CI/CD
Add a security scan to every pull request. Here's a simple GitHub Action:
name: Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: Edensages/sage-security-action@v1
This catches issues before they reach production.
7. Quick Security Checklist
- [ ] No secrets in code or git history
- [ ] SQL queries are parameterized
- [ ] No
eval()orexec()with user input - [ ] Dependencies pinned and audited
- [ ] Security linter in CI pipeline
- [ ]
.gitignorecovers sensitive files
Free Security Scan
Want to check your repo right now?
👉 scanner.edensages.org - Paste your GitHub URL for a free AI-powered security analysis.
What security practices do you follow? Drop a comment below.
Top comments (0)