IlmHamroh
Python kursi/Boshqa freymvorklar5/6-dars15 daqiqa
Mundarija (22)

22.5-dars: WSGI va ASGI

22-QISM — BOSHQA FREYMVORKLAR · 5-dars


1. Kirish va motivatsiya

Django, Flask (WSGI), FastAPI, Litestar (ASGI) — bu freymvorklar server bilan qanday gaplashadi? Javob — WSGI va ASGI standartlari. Bular Python veb-server (Gunicorn, Uvicorn) va ilova (freymvork) o'rtasidagi kelishuv (interfeys). Bularni tushunish — freymvorklar va serverlar qanday ishlashini anglash.

WSGI (sinxron) va ASGI (asinxron) — Python veb ekotizimining poydevori. Har freymvork WSGI yoki ASGI ilova beradi, har server WSGI yoki ASGI'ni tushunadi. Bu standart tufayli istalgan freymvork istalgan mos server bilan ishlaydi (Flask + Gunicorn, FastAPI + Uvicorn). Bu 21.16, 20.16 dagi deploy'ning texnik asosi.

Real vaziyat. Bir dasturchi "nima uchun Flask'ni Gunicorn bilan, FastAPI'ni Uvicorn bilan ishlatish kerak?" deb so'radi. Javob — WSGI vs ASGI: Flask WSGI ilova (Gunicorn — WSGI server), FastAPI ASGI ilova (Uvicorn — ASGI server). Standartni tushungach, u har freymvork/serverni to'g'ri juftladi. WSGI/ASGI — freymvork va server o'rtasidagi umumiy til.

Bu darsda WSGI va ASGI'ni — Python veb standartlarini o'rganamiz.

Bu darsda:

  • WSGI nima (sinxron interfeys)
  • WSGI ilova tuzilishi
  • ASGI nima (asinxron interfeys)
  • ASGI ilova tuzilishi
  • WSGI vs ASGI
  • Serverlar (Gunicorn, Uvicorn)
  • Nima uchun standart muhim
  • Amaliy: xom WSGI/ASGI

ℹ Misollarda xom WSGI/ASGI ilovalar sinaladi.


2. Nazariya — chuqur tushuntirish

2.1. WSGI nima

WSGI (Web Server Gateway Interface) — Python veb-server va ilova o'rtasidagi sinxron standart:

Server (Gunicorn) ←→ WSGI interfeys ←→ Ilova (Flask/Django)

WSGI — 2003 yildan Python veb standarti (PEP 333/3333). U server va ilova o'rtasidagi kelishuv: server so'rovni WSGI formatida beradi, ilova javobni WSGI formatida qaytaradi. Bu tufayli har WSGI ilova (Flask, Django) har WSGI server (Gunicorn, uWSGI) bilan ishlaydi.

2.2. WSGI ilova tuzilishi

WSGI ilova — (environ, start_response) oluvchi chaqiriladigan:

python
def wsgi_app(environ, start_response):
    # environ — so'rov ma'lumoti (dict)
    yol = environ["PATH_INFO"]
    metod = environ["REQUEST_METHOD"]
    # javob boshi
    start_response("200 OK", [("Content-Type", "text/plain")])
    # javob tanasi (bytes ro'yxati)
    return [b"Salom, WSGI!"]
Element Ma'no
environ So'rov ma'lumoti (dict)
start_response Status + sarlavha
return [bytes] Javob tanasi

WSGI ilova — funksiya (yoki chaqiriladigan obyekt): environ (so'rov dict'i), start_response (status/sarlavha), return [bytes] (javob). Freymvorklar bu murakkablikni yashiradi (siz @app.route yozasiz, freymvork WSGI'ni qiladi).

2.3. ASGI nima

ASGI (Asynchronous Server Gateway Interface) — WSGI'ning asinxron versiyasi:

Server (Uvicorn) ←→ ASGI interfeys ←→ Ilova (FastAPI/Litestar)

ASGI — zamonaviy Python veb standarti (async). WSGI sinxron (bir so'rov — bir oqim), ASGI asinxron (async view, WebSocket, uzun ulanish). FastAPI, Starlette, Litestar — ASGI ilovalar; Uvicorn — ASGI server. Bu 14-qism (async) ning veb tomoni.

2.4. ASGI ilova tuzilishi

ASGI ilova — (scope, receive, send) oluvchi coroutine:

python
async def asgi_app(scope, receive, send):
    # scope — ulanish ma'lumoti
    yol = scope["path"]
    # javob boshi
    await send({"type": "http.response.start", "status": 200,
                "headers": [(b"content-type", b"text/plain")]})
    # javob tanasi
    await send({"type": "http.response.body", "body": b"Salom, ASGI!"})
Element Ma'no
scope Ulanish ma'lumoti
receive So'rov o'qish (async)
send Javob yuborish (async)

ASGI ilova — async funksiya: scope (ulanish), receive (so'rov o'qish), send (javob yuborish). WSGI'dan farqli — async (await), WebSocket qo'llab-quvvatlaydi. Bu murakkabroq, lekin async imkonini beradi.

2.5. WSGI vs ASGI

Xususiyat WSGI ASGI
Turi Sinxron Asinxron
Yil 2003 2018
WebSocket Yo'q Ha
Async view Yo'q Ha
Freymvork Flask, Django FastAPI, Litestar
Server Gunicorn, uWSGI Uvicorn, Hypercorn

WSGI — sinxron (an'anaviy, oddiy, keng qo'llab-quvvatlangan); ASGI — asinxron (zamonaviy, WebSocket, async view, yuqori yuklama). Django ikkalasini ham (WSGI + ASGI). Yangi loyihalar ASGI (async imkoniyati); mavjud sinxron — WSGI yetarli.

2.6. Serverlar

Freymvork ilovani beradi, server uni ishga tushiradi:

Server Interfeys
Gunicorn WSGI (+ ASGI worker)
uWSGI WSGI
Uvicorn ASGI
Hypercorn ASGI
bash
gunicorn app:app             # WSGI (Flask, Django)
uvicorn app:app              # ASGI (FastAPI, Litestar)

Server — WSGI/ASGI ilovani real HTTP server qiladi (ko'p oqim, ishonchli). WSGI ilova → WSGI server (Gunicorn); ASGI ilova → ASGI server (Uvicorn). To'g'ri juftlik muhim (Flask + Uvicorn ishlamaydi — Flask WSGI).

2.7. Nima uchun standart muhim

Standart tufayli moslashuvchanlik:

Standart bermasa Standart bilan
Har freymvork o'z serveri Istalgan mos server
Bog'liq (qattiq) Almashtiriladigan
Kam tanlov Ko'p tanlov

WSGI/ASGI standarti tufayli freymvork va server mustaqil: istalgan WSGI freymvork (Flask, Django) istalgan WSGI server (Gunicorn, uWSGI) bilan. Bu 20.16 dagi "aniq shartnoma", 21.11 dagi ekotizim kabi — standart komponentlarni almashtiriladigan qiladi.

2.8. WSGI/ASGI — poydevor

Qatlam Vazifa
Freymvork Ilova mantiqi (@app.route)
WSGI/ASGI Standart interfeys
Server HTTP (Gunicorn/Uvicorn)
Nginx Reverse proxy, static

WSGI/ASGI — Python veb ekotizimining poydevori: freymvork (mantiq) va server (HTTP) o'rtasidagi standart. Bu qatlamli tuzilma (21.16 deploy) har komponentni mustaqil va almashtiriladigan qiladi. Standartni tushunish — butun ekotizimni anglash.


3. Tez ma'lumotnoma

python
# WSGI ilova (sinxron):
def wsgi_app(environ, start_response):
    start_response("200 OK", [("Content-Type", "text/plain")])
    return [b"Salom"]

# ASGI ilova (asinxron):
async def asgi_app(scope, receive, send):
    await send({"type": "http.response.start", "status": 200, "headers": [...]})
    await send({"type": "http.response.body", "body": b"Salom"})
bash
# WSGI server:  gunicorn app:app   (Flask, Django)
# ASGI server:  uvicorn app:app    (FastAPI, Litestar)

WSGI vs ASGI

WSGI — sinxron (environ, start_response) → Gunicorn → Flask/Django
ASGI — async (scope, receive, send) → Uvicorn → FastAPI/Litestar

4. Batafsil misollar

Misollarda xom WSGI/ASGI ilovalar sinaladi.

Misol 1 — Xom WSGI ilova

python
"""xom WSGI ilova (environ, start_response); so'rov ma'lumoti (environ); javob (bytes); freymvorksiz."""

import warnings
warnings.filterwarnings("ignore")

from werkzeug.test import Client


def wsgi_app(environ, start_response):
    yol = environ["PATH_INFO"]
    metod = environ["REQUEST_METHOD"]
    savol = environ.get("QUERY_STRING", "")
    start_response("200 OK", [("Content-Type", "text/plain; charset=utf-8")])
    return [f"WSGI: {metod} {yol} (savol: {savol})".encode()]


def main() -> None:
    client = Client(wsgi_app)

    print("=== 1. WSGI ilova (funksiya) ===")
    javob = client.get("/salom")
    print(f"  status: {javob.status}")

    print("\n=== 2. So'rov ma'lumoti (environ) ===")
    print(f"  javob: {b''.join(javob.response).decode()}")

    print("\n=== 3. So'rov parametri ===")
    javob = client.get("/qidir?q=python")
    print(f"  javob: {b''.join(javob.response).decode()}")

    print("\n=== 4. HTTP metod ===")
    javob = client.post("/kurslar")
    print(f"  POST javob: {b''.join(javob.response).decode()}")
    print("  ⭐ WSGI — (environ, start_response) → [bytes] (sinxron)")


if __name__ == "__main__":
    main()

Natijaning muhim qismi:

text
=== 1. WSGI ilova (funksiya) ===
  status: 200 OK

=== 2. So'rov ma'lumoti (environ) ===
  javob: WSGI: GET /salom (savol: )

=== 3. So'rov parametri ===
  javob: WSGI: GET /qidir (savol: q=python)

=== 4. HTTP metod ===
  POST javob: WSGI: POST /kurslar (savol: )
  ⭐ WSGI — (environ, start_response) → [bytes] (sinxron)

Nima ko'rsatdi: 2.1, 2.2-bo'limlar.

Misol 2 — Xom ASGI ilova

python
"""xom ASGI ilova (scope, receive, send); async; javob (http.response.start/body); WebSocket asosi."""

import warnings
warnings.filterwarnings("ignore")

import asyncio


async def asgi_app(scope, receive, send):
    assert scope["type"] == "http"
    yol = scope["path"]
    metod = scope["method"]
    await send({
        "type": "http.response.start",
        "status": 200,
        "headers": [(b"content-type", b"text/plain; charset=utf-8")],
    })
    await send({
        "type": "http.response.body",
        "body": f"ASGI: {metod} {yol}".encode(),
    })


async def asgi_test(app, metod, yol):
    natija = {}

    async def receive():
        return {"type": "http.request", "body": b"", "more_body": False}

    async def send(xabar):
        if xabar["type"] == "http.response.start":
            natija["status"] = xabar["status"]
        elif xabar["type"] == "http.response.body":
            natija["body"] = xabar["body"].decode()

    await app({"type": "http", "method": metod, "path": yol}, receive, send)
    return natija


def main() -> None:
    print("=== 1. ASGI ilova (async funksiya) ===")
    natija = asyncio.run(asgi_test(asgi_app, "GET", "/salom"))
    print(f"  status: {natija['status']}")

    print("\n=== 2. Javob (http.response.body) ===")
    print(f"  javob: {natija['body']}")

    print("\n=== 3. Boshqa yo'l ===")
    natija = asyncio.run(asgi_test(asgi_app, "POST", "/kurslar"))
    print(f"  javob: {natija['body']}")

    print("\n=== 4. Async (await) ===")
    print("  ASGI — scope, receive (await), send (await)")
    print("  ⭐ ASGI — (scope, receive, send) async → WebSocket, async view")


if __name__ == "__main__":
    main()

Natijaning muhim qismi:

text
=== 1. ASGI ilova (async funksiya) ===
  status: 200

=== 2. Javob (http.response.body) ===
  javob: ASGI: GET /salom

=== 3. Boshqa yo'l ===
  javob: ASGI: POST /kurslar

=== 4. Async (await) ===
  ASGI — scope, receive (await), send (await)
  ⭐ ASGI — (scope, receive, send) async → WebSocket, async view

Nima ko'rsatdi: 2.3, 2.4-bo'limlar.

Misol 3 — WSGI vs ASGI taqqoslash

python
"""WSGI (sinxron) va ASGI (asinxron) taqqoslash; bir xil natija, turli interfeys; freymvork/server juftligi."""

import warnings
warnings.filterwarnings("ignore")

import asyncio

from werkzeug.test import Client


# WSGI (sinxron)
def wsgi_app(environ, start_response):
    start_response("200 OK", [("Content-Type", "text/plain")])
    return [f"WSGI javob: {environ['PATH_INFO']}".encode()]


# ASGI (asinxron)
async def asgi_app(scope, receive, send):
    await send({"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")]})
    await send({"type": "http.response.body", "body": f"ASGI javob: {scope['path']}".encode()})


async def asgi_test(app, yol):
    natija = {}

    async def receive():
        return {"type": "http.request", "body": b""}

    async def send(x):
        if x["type"] == "http.response.body":
            natija["body"] = x["body"].decode()

    await app({"type": "http", "method": "GET", "path": yol}, receive, send)
    return natija


def main() -> None:
    print("=== 1. WSGI (sinxron) ===")
    wsgi_javob = b"".join(Client(wsgi_app).get("/kurslar").response).decode()
    print(f"  {wsgi_javob}")

    print("\n=== 2. ASGI (asinxron) ===")
    asgi_javob = asyncio.run(asgi_test(asgi_app, "/kurslar"))["body"]
    print(f"  {asgi_javob}")

    print("\n=== 3. Interfeys farqi ===")
    print("  WSGI: (environ, start_response), sinxron, [bytes]")
    print("  ASGI: (scope, receive, send), async, send()")

    print("\n=== 4. Server juftligi ===")
    print("  WSGI ilova → Gunicorn (WSGI server)")
    print("  ASGI ilova → Uvicorn (ASGI server)")
    print("  ⭐ WSGI sinxron, ASGI async — turli interfeys, mos server")


if __name__ == "__main__":
    main()

Natijaning muhim qismi:

text
=== 1. WSGI (sinxron) ===
  WSGI javob: /kurslar

=== 2. ASGI (asinxron) ===
  ASGI javob: /kurslar

=== 3. Interfeys farqi ===
  WSGI: (environ, start_response), sinxron, [bytes]
  ASGI: (scope, receive, send), async, send()

=== 4. Server juftligi ===
  WSGI ilova → Gunicorn (WSGI server)
  ASGI ilova → Uvicorn (ASGI server)
  ⭐ WSGI sinxron, ASGI async — turli interfeys, mos server

Nima ko'rsatdi: 2.5, 2.6-bo'limlar.

Misol 4 — Amaliy: WSGI middleware

WSGI/ASGI standarti tufayli middleware (ilovani o'ravchi qatlam) yozish mumkin — istalgan WSGI ilova bilan ishlaydi. Bu standartning kuchini ko'rsatadi.

python
"""WSGI middleware (ilovani o'ravchi); har so'rovni log; standart tufayli istalgan ilova bilan."""

import warnings
warnings.filterwarnings("ignore")

from werkzeug.test import Client

JURNAL = []


# asosiy WSGI ilova
def asosiy_app(environ, start_response):
    start_response("200 OK", [("Content-Type", "text/plain")])
    return [f"Javob: {environ['PATH_INFO']}".encode()]


# WSGI middleware — ilovani o'raydi
class LogMiddleware:
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        # so'rovdan oldin
        JURNAL.append(f"{environ['REQUEST_METHOD']} {environ['PATH_INFO']}")

        # javob sarlavhasini o'zgartirish
        def yangi_start(status, headers):
            headers.append(("X-Middleware", "ishladi"))
            return start_response(status, headers)

        return self.app(environ, yangi_start)


# middleware bilan o'rash
oralgan_app = LogMiddleware(asosiy_app)


def main() -> None:
    client = Client(oralgan_app)

    print("=== 1. Middleware bilan o'ralgan ilova ===")
    javob = client.get("/kurslar")
    print(f"  javob: {b''.join(javob.response).decode()}")

    print("\n=== 2. Middleware so'rovni logladi ===")
    print(f"  jurnal: {JURNAL}")

    print("\n=== 3. Middleware sarlavha qo'shdi ===")
    print(f"  X-Middleware: {javob.headers.get('X-Middleware')}")

    print("\n=== 4. Standart kuchi ===")
    client.get("/salom")
    print(f"  ikki so'rov: {JURNAL}")
    print("  ⭐ WSGI middleware — istalgan WSGI ilova bilan (standart tufayli)")


if __name__ == "__main__":
    main()

Natijaning muhim qismi:

text
=== 1. Middleware bilan o'ralgan ilova ===
  javob: Javob: /kurslar

=== 2. Middleware so'rovni logladi ===
  jurnal: ['GET /kurslar']

=== 3. Middleware sarlavha qo'shdi ===
  X-Middleware: ishladi

=== 4. Standart kuchi ===
  ikki so'rov: ['GET /kurslar', 'GET /salom']
  ⭐ WSGI middleware — istalgan WSGI ilova bilan (standart tufayli)

Nima ko'rsatdi: 2.7, 2.8-bo'limlar.


5. To'g'ri va noto'g'ri tushunishlar

Noto'g'ri fikr To'g'risi
"WSGI = server" Interfeys (standart)
"WSGI eskirgan" Hali keng ishlatiladi
"ASGI doim yaxshi" Async kerak bo'lsa
"Freymvork = server" Alohida (interfeys orqali)
"Flask Uvicorn bilan" Flask WSGI (Gunicorn)
"WSGI'ni qo'lda yozish" Freymvork qiladi
"ASGI faqat FastAPI" Django ham (async)
"Standart keraksiz" Moslashuvchanlik beradi

6. Keng tarqalgan xatolar va yechimlari

1. WSGI ilovani ASGI server bilan

bash
uvicorn flask_app:app                        # ⚠️ Flask WSGI
gunicorn flask_app:app                        # ✅ WSGI server

2. ASGI ilovani WSGI server bilan

bash
gunicorn fastapi_app:app                      # ⚠️ FastAPI ASGI
uvicorn fastapi_app:app                       # ✅ ASGI server
# (yoki gunicorn -k uvicorn.workers.UvicornWorker)

3. WSGI javobni str qaytarish

python
return ["salom"]                             # ❌ bytes kerak
return [b"salom"]                            # ✅

4. start_responseni chaqirmaslik

python
def app(environ, start_response):
    return [b"salom"]                        # ❌ status yo'q
    # ✅ start_response("200 OK", [...]) avval

5. ASGI'da awaitni unutish

python
send({...})                                  # ❌ coroutine
await send({...})                            # ✅

6. WSGI/ASGI'ni qo'lda yozish (freymvork bor)

python
# xom WSGI ilova qo'lda                        # ⚠️ murakkab
# ✅ Flask/FastAPI (freymvork WSGI/ASGI qiladi)

7. Freymvork va server juftligini chalkashtirish

Django + Uvicorn (WSGI mode)                  # ⚠️ noto'g'ri
Django (WSGI) + Gunicorn                       # ✅

7. Integratsiya — bu bilim qayerda kerak bo'ladi

  • 21.16-dars (o'tilgan): Django deploy — WSGI
  • 20.16-dars (o'tilgan): FastAPI deploy — ASGI
  • 14-qism (o'tilgan): async — ASGI asosi
  • 22.3-dars (o'tilgan): Starlette/Litestar — ASGI
  • 28-qism: infratuzilma — server sozlash

8. Eng yaxshi amaliyotlar

  1. WSGI ilova → WSGI server (Gunicorn); ASGI → Uvicorn.

  2. Async kerak bo'lsa ASGI (FastAPI, Litestar).

  3. Sinxron yetarli bo'lsa WSGI (Flask, Django).

  4. WSGI/ASGI'ni freymvork qiladi (qo'lda emas).

  5. Freymvork va server juftligini to'g'ri qiling.

  6. WSGI javob — bytes (str emas).

  7. ASGI'da await ishlating.

  8. Standartni tushuning (ekotizimni anglash).


9. Amaliy topshiriq

Vazifa 1: Bashorat qiling

python
1.  # WSGI nima?
2.  # ASGI nima?
3.  # WSGI ilova nima oladi?
4.  # ASGI ilova nima oladi?
5.  # WSGI sinxronmi?
6.  # ASGI async?
7.  # Flask qaysi?
8.  # FastAPI qaysi?
9.  # Gunicorn qaysi server?
10. # Uvicorn qaysi server?
11. # WSGI javob turi?
12. # standart nima uchun?
Javoblar
  1. Sinxron server-ilova interfeysi
  2. Asinxron server-ilova interfeysi
  3. (environ, start_response)
  4. (scope, receive, send)
  5. Ha (sinxron)
  6. Ha (async, await)
  7. WSGI
  8. ASGI
  9. WSGI server
  10. ASGI server
  11. bytes ro'yxati
  12. Moslashuvchanlik (freymvork/server mustaqil)

Vazifa 2: Xatolarni tuzating

bash
1.  uvicorn flask_app:app          # WSGI ilova

2.  gunicorn fastapi_app:app       # ASGI ilova

3.  return ["salom"]               # bytes

4.  send({...})                    # await

5.  # xom WSGI qo'lda              # freymvork
Javoblar
bash
1.  gunicorn flask_app:app

2.  uvicorn fastapi_app:app

3.  return [b"salom"]

4.  await send({...})

5.  # Flask/FastAPI ishlating

Vazifa 3: Xom WSGI

WSGI ilova yozing:

  1. (environ, start_response)
  2. So'rov ma'lumoti (PATH_INFO, REQUEST_METHOD)
  3. Javob (bytes)
  4. werkzeug.test.Client bilan test

Vazifa 4: Xom ASGI

ASGI ilova yozing:

  1. (scope, receive, send) async
  2. http.response.start/body
  3. Async test
  4. Natija

Vazifa 5: WSGI middleware

Middleware yozing:

  1. Ilovani o'ravchi klass
  2. So'rov log, sarlavha
  3. Standart tufayli ishlashi
  4. Test

Vazifa 6: Taqqoslash

WSGI vs ASGI:

  1. Bir xil ilova ikkalasida
  2. Interfeys farqi
  3. Server juftligi
  4. Qachon qaysi

Vazifa 7: O'ylash

WSGI/ASGI — standart interfeys: freymvork (Flask, FastAPI) va server (Gunicorn, Uvicorn) o'rtasidagi kelishuv. Bu standart tufayli istalgan mos freymvork istalgan mos server bilan ishlaydi (Flask + Gunicorn, FastAPI + Uvicorn). "Standart interfeys" (protokol, kelishuv) komponentlarni almashtiriladigan qiladi — nima uchun standartlar (WSGI, HTTP, USB) muhandislikda shunchalik kuchli, va ular innovatsiyani qanday tezlashtiradi?

Javob

Qisqa javob: WSGI/ASGI standart interfeys — freymvork va server bir tilda gaplashadi. Bu tufayli ular mustaqil: freymvork serverni bilmaydi (WSGI beradi), server freymvorkni bilmaydi (WSGI oladi). Standart komponentlarni almashtiriladigan qiladi (Flask'ni Gunicorn'dan uWSGI'ga o'tkazish — kod o'zgarmaydi). Standartlar (WSGI, HTTP, USB) kuchli, chunki ular umumiy til yaratadi — turli ishlab chiqaruvchilar mustaqil ishlay oladi (bir standartga amal qilsa, mos keladi). Bu innovatsiyani tezlashtiradi: yangi freymvork (Litestar) yangi server yozmasdan mavjud ASGI serverlar bilan ishlaydi; yangi server (Granian) yangi freymvork kutmaydi.

1. Standart — umumiy til

Freymvork va server kelishuvga (WSGI) amal qiladi — bir-birini bilmasdan ishlay oladi (interfeys orqali).

2. Almashtiriladiganlik

Standart bilan Standartsiz
Flask + istalgan WSGI server Har freymvork o'z serveri
Almashtirish oson Bog'liq (qattiq)
Ko'p tanlov Kam tanlov

3. Standart innovatsiyani tezlashtiradi

Yangi freymvork (Litestar) mavjud ASGI serverlar bilan darrov ishlaydi (server yozmaydi). Har ishlab chiqaruvchi o'z qismini yaxshilaydi (standartga amal qilsa, mos keladi).

4. Standartlar boshqa joyda

Standart Umumiy til
WSGI/ASGI Freymvork ↔ server
HTTP Mijoz ↔ server
USB Qurilma ↔ kompyuter
SQL Ilova ↔ baza
POSIX Dastur ↔ OS

5. Muhandislik saboqlari

  1. Standart — umumiy til (komponentlar mustaqil)
  2. Almashtiriladiganlik — moslashuvchanlik
  3. Standart innovatsiyani tezlashtiradi
  4. O'z qismini yaxshila (standartga amal qil)

6. Xulosa

  1. WSGI/ASGI — standart interfeys (umumiy til)
  2. Komponentlar mustaqil, almashtiriladigan
  3. Standart innovatsiyani tezlashtiradi
  4. Standartlar (HTTP, USB, SQL) — muhandislik kuchi

Nimani mustahkamlaydi: 2.1–2.8-bo'limlar.


Xulosa

Bu darsda WSGI va ASGI'ni — Python veb standartlarini o'rgandik.

Eng muhim uch fikr:

  1. WSGI — sinxron interfeys. WSGI (Web Server Gateway Interface) — Python veb-server va ilova o'rtasidagi sinxron standart (2003). WSGI ilova — (environ, start_response) oluvchi chaqiriladigan funksiya: environ (so'rov dict'i), start_response (status/sarlavha), return [bytes] (javob). Bu tufayli har WSGI ilova (Flask, Django) har WSGI server (Gunicorn, uWSGI) bilan ishlaydi. Freymvorklar bu murakkablikni yashiradi.

  2. ASGI — asinxron interfeys. ASGI (Asynchronous Server Gateway Interface) — WSGI'ning asinxron versiyasi (2018). ASGI ilova — (scope, receive, send) oluvchi coroutine (async): scope (ulanish), receive (so'rov o'qish, await), send (javob yuborish, await). WSGI'dan farqli — async, WebSocket qo'llab-quvvatlaydi. FastAPI, Starlette, Litestar — ASGI ilovalar; Uvicorn — ASGI server. WSGI ilova → WSGI server (Gunicorn); ASGI ilova → ASGI server (Uvicorn).

  3. Standart — moslashuvchanlik. WSGI/ASGI — Python veb ekotizimining poydevori: freymvork (mantiq) va server (HTTP) o'rtasidagi standart interfeys. Bu standart tufayli komponentlar mustaqil va almashtiriladigan (istalgan mos freymvork + istalgan mos server). Standartlar (WSGI, HTTP, USB, SQL) muhandislikda kuchli, chunki ular umumiy til yaratadi — turli ishlab chiqaruvchilar mustaqil ishlay oladi va innovatsiya tezlashadi (yangi freymvork mavjud serverlar bilan darrov ishlaydi).

Keyingi darsda shablon dvigatellari ni o'rganamiz va 22-qismni yakunlaymiz: Jinja2 va boshqa template dvigatellari — HTML generatsiyasi, sintaksis va freymvorklar bilan bog'lash.

Ulashish:Telegram'da

Izohlar (0)

Izoh yozish uchun kiring.

  • Hozircha izoh yo'q. Birinchi bo'ling!
22.5-dars: WSGI va ASGI — IlmHamroh