CodeBlanks Logo Icon CodeBlanks

async get

await session.get ile GET isteğini öğrenirsin.

async get

session.get(url), bir GET isteği yapan asenktron metottur. Yanıt bir bağlam yöneticisi olarak döner; async with ile açılır.

async with session.get("https://example.com") as resp:
    text = await resp.text()

resp.status durum kodunu, resp.text() gövdeyi döndürür. Gövde bir coroutine olduğu için await ile beklenir.

durum kodu ve gövde

Bir GET yanıtında iki temel bilgi vardır: durum kodu (ör. 200, 404) ve gövde. Durum kodu resp.status özniteliğinden, gövde await resp.text() veya await resp.read() ile alınır.

async with session.get(url) as resp:
    print(resp.status)
    print(await resp.text())

200 başarılı, 404 bulunamadı, 500 sunucu hatası demektir. Gövdeyi bir kez okuyabilirsin; ikinci okuma boş döner.

Uygulama async get ile gövde oku

import asyncio ve import aiohttp ile başla. async def main() içinde async with aiohttp.ClientSession() as session: aç. İçinde async with session.get("https://example.com") as resp: ile GET isteği yap. print(await resp.text()) ile gövdeyi yazdır. asyncio.run(main()) çağrısı ekle.

Başlangıç kodu

main.py
# asyncio ve aiohttp modüllerini içe aktar
# async with ile bir oturum aç
# oturum üzerinde get ile bir istek yap
# await ile gövdeyi oku ve yazdır
# asyncio.run ile main'i çalıştır

Örnek çözüm

main.py
import asyncio
import aiohttp

class _S:
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def get(self, url): return self
    async def text(self): return 'merhaba'

aiohttp.ClientSession = _S

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get('https://example.com') as resp:
            print(await resp.text())

asyncio.run(main())

Beklenen çıktı

merhaba

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 get kavramlarını eşleştir

Kavram Anlamı
session.get GET isteği yapar
resp.status Durum kodu verir
await resp.text Gövde döndürür
async with Kaynağı kapatır

2 session.get(url) ne döndürür?

  • Bir bağlam yöneticisi Doğru cevap
  • Bir sözlük
  • Bir dize
  • Bir dosya nesnesi

Açıklama: session.get bir bağlam yöneticisi döndürür; async with ile açılır.

3 get çağrısını tamamla

Soru
async with ____("https://example.com") as resp:
Cevap
async with session.get("https://example.com") as resp:

Açıklama: session.get(url) ile GET isteği yapılır.

İleri seviye bölümündeki tüm dersler