نظرة عامة
سنبني خط CI/CD لتطبيق Django مع Python، اختبارات، تحليل جودة الكود، Docker، ونشر تلقائي.
هيكل المشروع
my-django-app/
├── config/
│ ├── settings.py
│ └── urls.py
├── myapp/
│ ├── models.py
│ └── views.py
├── tests/
├── Dockerfile
├── requirements.txt
├── .github/workflows/ci-cd.yml
└── manage.py
CI/CD Pipeline
name: Django CI/CD
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: test
POSTGRES_DB: testdb
ports:
- 5432:5432
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r requirements.txt
- run: |
cp .env.example .env
python manage.py migrate
python manage.py test
env:
DATABASE_URL: postgres://postgres:test@localhost:5432/testdb
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install ruff
- run: ruff check .
docker-build:
needs: [test, lint]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: |
docker build -t my-django-app:${{ github.sha }} .
echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin
docker tag my-django-app:${{ github.sha }} ghcr.io/${{ github.repository }}:${{ github.sha }}
docker push ghcr.io/${{ github.repository }}:${{ github.sha }}
Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN python manage.py collectstatic --noinput
EXPOSE 8000
CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000"]
اختبارات Django
# tests/test_views.py
from django.test import TestCase
from django.urls import reverse
class HomePageTest(TestCase):
def test_home_page_status(self):
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
def test_home_page_template(self):
response = self.client.get(reverse('home'))
self.assertTemplateUsed(response, 'home.html')
⚠️ لا تضع
SECRET_KEYأوDATABASE_URLفي الكود. استخدم GitHub Secrets و.env.example.
🎯 التالي: Kubernetes — مقدمة