☀️Siang
Python

Python WSGI & ASGI: Panduan Lengkap

Tutorial mendalam tentang WSGI dan ASGI di Python — Gunicorn, Uvicorn, Starlette, protokol web server, dan deployment aplikasi web production-ready

Artikel: Python Wsgi Asgi Artikel: Python Wsgi Asgi

1. Pengenalan WSGI & ASGI

Ketika Anda menjalankan aplikasi web Python (Flask, Django, FastAPI), Anda memerlukan web server yang menerima HTTP request dari browser dan meneruskannya ke aplikasi Anda. WSGI dan ASGI adalah standar protokol yang mendefinisikan bagaimana web server berkomunikasi dengan aplikasi Python.

Apa Itu WSGI dan ASGI?

Aspek WSGI ASGI
KepanjanganWeb Server Gateway InterfaceAsynchronous Server Gateway Interface
PEPPEP 3333Proprietary (Django project)
Sync/AsyncSynchronousAsynchronous
WebSocket❌ Tidak✅ Ya
HTTP/2Terbatas✅ Ya
FrameworkFlask, Django (legacy)FastAPI, Starlette, Django 3.0+
ServerGunicorn, uWSGIUvicorn, Daphne, Hypercorn
Diagram: WSGI vs ASGI Architecture
WSGI vs ASGI Architecture

ASGI (Asynchronous)

HTTP/WS Request

ASGI Server\n(Uvicorn/Daphne)

ASGI App\n(FastAPI/Django)

HTTP/WS Response

WSGI (Synchronous)

HTTP Request

WSGI Server\n(Gunicorn/uWSGI)

WSGI App\n(Flask/Django)

HTTP Response

2. WSGI: Konsep Dasar

WSGI (PEP 3333) adalah standar antarmuka antara web server dan aplikasi web Python. WSGI memastikan kompatibilitas antara berbagai server dan framework.

Bagaimana WSGI Bekerja

Aplikasi WSGI adalah sebuah callable (fungsi atau objek dengan __call__) yang menerima dua argumen:

  • environ — dictionary berisi informasi request (method, path, headers, dll)
  • start_response — callback untuk mengirim status dan headers
flowchart TB
    User["👤 User"] --> Nginx["🌐 Nginx\n(Reverse Proxy)"]
    Nginx -->|"Static files"| Static["📁 Static Files"]
    Nginx -->|"Dynamic"| App["🐍 Python App\n(Gunicorn/uvicorn)"]
    App --> DB["("#quot;🗄️ Database#quot;")"]
    App --> Cache["⚡ Redis Cache"]
    App --> Queue["📋 Task Queue\n(Celery)"]

    style User fill:#2a0f1e,stroke:#f472b6
    style Nginx fill:#2a1f0a,stroke:#f59e0b,stroke-width:2px
    style App fill:#0f2a1f,stroke:#3ecf8e,stroke-width:2px
    style DB fill:#0f1d3a,stroke:#60a5fa,stroke-width:1.5px
    style Cache fill:#1a0f2e,stroke:#a78bfa
    style Queue fill:#0a2a1f,stroke:#34d399

Nginx Reverse Proxy Config

Nginx — Reverse Proxy
# /etc/nginx/sites-available/myapp
server {
    listen 80;
    server_name myapp.example.com;
    
    # Redirect HTTP → HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name myapp.example.com;
    
    ssl_certificate /etc/ssl/certs/myapp.crt;
    ssl_certificate_key /etc/ssl/private/myapp.key;
    
    # Static files (langsung serve oleh Nginx)
    location /static/ {
        alias /var/www/myapp/static/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    # Dynamic requests → Gunicorn/Uvicorn
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # Timeouts
        proxy_connect_timeout 10s;
        proxy_read_timeout 30s;
        proxy_send_timeout 30s;
    }
    
    # WebSocket support (untuk ASGI)
    location /ws/ {
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
}

Systemd Service

Systemd — Service File
# /etc/systemd/system/myapp.service
[Unit]
Description=My Python Web Application
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/var/www/myapp/venv/bin/gunicorn app:app -c gunicorn.conf.py
ExecReload=/bin/kill -s HUP $MAINPID
Restart=always
RestartSec=5
KillMode=mixed
TimeoutStopSec=10

[Install]
WantedBy=multi-user.target

11. Best Practices

💡 Tips Penting
  • Development → Gunakan uvicorn --reload atau flask run --debug
  • Production WSGI → Gunicorn dengan sync atau gthread workers
  • Production ASGI → Uvicorn dengan multiple workers atau Gunicorn + UvicornWorker
  • Selalu gunakan reverse proxy (Nginx/Caddy) di production
  • Workers formula2 × CPU cores + 1
  • Jangan gunakan development server Flask/Django untuk production

12. Quiz Pemahaman

🧠 Quiz: WSGI & ASGI

1. Apa kepanjangan WSGI?

2. Apa keunggulan utama ASGI dibanding WSGI?

3. Server apa yang direkomendasikan untuk FastAPI di production?

4. Berapa rekomendasi jumlah Gunicorn workers?

5. Mengapa tidak boleh pakai Flask/Django dev server di production?

🔍 Zoom
100%
🎨 Tema