Giriş: ConnectionError Nedir?

ConnectionError, Python'da ağ bağlantısı kurmaya veya sürdürmeye çalışırken ortaya çıkan temel istisna (base exception) sınıfıdır. Bu hata, genellikle:

✔ Sunucuya bağlanılamadığında
✔ Ağ kesintisi olduğunda
✔ Bağlantı zaman aşımına uğradığında
✔ Hedef servis kullanılamadığında

görülür. Bu makalede, ConnectionError türlerini, çözüm yöntemlerini ve profesyonel kullanım senaryolarını detaylıca inceleyeceğiz.


1. ConnectionError Hiyerarşisi ve Türleri

Python'da ConnectionError, diğer önemli bağlantı hatalarının temel sınıfıdır:

text
Copy
Download
ConnectionError
 ├── ConnectionAbortedError
 ├── ConnectionRefusedError
 ├── ConnectionResetError
 └── BrokenPipeError

a) ConnectionRefusedError

Sunucu bağlantıyı reddettiğinde oluşur (ERR_CONN_REFUSED).

python
Copy
Download
import socket

try:
    s = socket.socket()
    s.connect(('localhost', 12345))  # Açık olmayan port
except ConnectionRefusedError as e:
    print(f"Hata: {e}")  # [Errno 111] Connection refused

b) ConnectionResetError

Bağlantının karşı taraf tarafından aniden kesilmesi.

python
Copy
Download
import requests

try:
    response = requests.get('http://example.com')
    response.raise_for_status()
except requests.exceptions.ConnectionError as e:
    print(f"Bağlantı hatası: {e}")

2. ConnectionError'ın Yaygın Nedenleri

a) Sunucu Kullanılamaz Durumda

  • Sunucu çökmüş olabilir

  • Bakım modunda olabilir

b) Ağ Konfigürasyon Sorunları

  • Yanlış IP/port kullanımı

  • Firewall engellemeleri

c) Zaman Aşımı Problemleri

python
Copy
Download
import urllib.request

try:
    urllib.request.urlopen('http://example.com', timeout=0.001)
except urllib.error.URLError as e:
    print(f"Zaman aşımı: {e}")

3. ConnectionError Nasıl Çözülür?

a) Yeniden Deneme Mekanizması

python
Copy
Download
import time
from functools import wraps

def retry_on_connection_error(max_retries=3, delay=1):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_retries):
                try:
                    return func(*args, **kwargs)
                except ConnectionError as e:
                    if attempt == max_retries - 1:
                        raise
                    print(f"Yeniden deneme {attempt + 1}/{max_retries}")
                    time.sleep(delay * (attempt + 1))
        return wrapper
    return decorator

@retry_on_connection_error()
def fetch_data(url):
    return requests.get(url).json()

b) Bağlantı Havuzu Kullanımı

python
Copy
Download
from urllib3 import PoolManager

http = PoolManager(maxsize=10, timeout=5.0)

try:
    response = http.request('GET', 'http://example.com')
except ConnectionError as e:
    print(f"Havuz bağlantı hatası: {e}")

c) Async/Await ile Bağlantı Yönetimi

python
Copy
Download
import aiohttp
import asyncio

async def async_fetch():
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get('http://example.com') as response:
                return await response.text()
    except aiohttp.ClientConnectionError as e:
        print(f"Async bağlantı hatası: {e}")

asyncio.run(async_fetch())

4. Gerçek Dünya Senaryoları

a) Veritabanı Bağlantı Yönetimi

python
Copy
Download
import psycopg2
from psycopg2 import OperationalError

def get_db_connection():
    retry_count = 0
    max_retries = 3
    
    while retry_count < max_retries:
        try:
            return psycopg2.connect(
                host="localhost",
                database="mydb",
                user="user",
                password="pass"
            )
        except OperationalError as e:
            retry_count += 1
            print(f"Veritabanı bağlantı hatası: {e}")
            time.sleep(2 ** retry_count)
    raise ConnectionError("Veritabanına bağlanılamadı")

b) Mikroservis İletişimi

python
Copy
Download
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

def create_resilient_session():
    session = requests.Session()
    retry = Retry(
        total=3,
        backoff_factor=1,
        status_forcelist=[500, 502, 503, 504]
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    return session

session = create_resilient_session()
try:
    response = session.get("http://api.service.com/data", timeout=5)
except ConnectionError as e:
    print(f"Mikroservis hatası: {e}")

5. Performans ve Güvenlik Optimizasyonları

✔ Keep-Alive bağlantıları kullanarak performansı artırın
✔ TLS/SSL sertifika doğrulamalarını atlamayın
✔ Bağlantı havuzu boyutunu sistem kaynaklarına göre ayarlayın
✔ Zaman aşımı değerlerini servis SLA'larına göre belirleyin

Örnek: Güvenli ve Optimize Edilmiş Bağlantı

python
Copy
Download
import ssl
import urllib3

# Güvenli bağlantı havuzu
secure_pool = urllib3.HTTPSConnectionPool(
    'api.secure.com',
    maxsize=5,
    timeout=10.0,
    retries=3,
    ssl_context=ssl.create_default_context()
)

try:
    response = secure_pool.request('GET', '/data')
except urllib3.exceptions.MaxRetryError as e:
    print(f"Maksimum yeniden deneme aşıldı: {e}")
except ConnectionError as e:
    print(f"Güvenli bağlantı hatası: {e}")

Sonuç

✅ ConnectionError, ağ tabanlı uygulamalarda sık karşılaşılan kritik bir hatadır
✅ Yeniden deneme mekanizmaları ve bağlantı havuzları ile hatalara dirençli sistemler geliştirilebilir
✅ Zaman aşımı ve SSL ayarları güvenlik için hayati öneme sahiptir
✅ Asenkron programlama ile yüksek performanslı bağlantı yönetimi sağlanabilir


Sık Sorulan Sorular (SSS)

❓ ConnectionError ile TimeoutError arasındaki fark nedir?

  • ConnectionError: Bağlantı kurulamaması

  • TimeoutError: İşlemin belirtilen sürede tamamlanamaması

❓ Hangi Python sürümlerinde bulunur?

  • Python 3.3+ ile standart kütüphanede

❓ Tüm HTTP hatalarını ConnectionError olarak yakalamalı mıyım?

  • Hayır, sadece bağlantı sorunlarında kullanın. HTTP 4xx/5xx hataları için HTTPError kullanın


Özet Tablo

YöntemKullanım AlanıAvantajlar
Yeniden DenemeKararsız ağ bağlantılarıBasit uygulama
Bağlantı HavuzuYüksek trafikli sistemlerKaynak verimliliği
Async/AwaitYüksek performans gerektiren uygulamalarÖlçeklenebilirlik