Skip to content

🏧 🛠️

👑 🔰 👆 ✍ ❔ 🚮 🛃 🛠️ 👆 🈸.

& ⤴️ 👆 ✍ ❔ 🍵 ⚜ ⏮️ CORSMiddleware.

👉 📄 👥 🔜 👀 ❔ ⚙️ 🎏 🛠️.

❎ 🔫 🛠️

FastAPI ⚓️ 🔛 💃 & 🛠️ 🔫 🔧, 👆 💪 ⚙️ 🙆 🔫 🛠️.

🛠️ 🚫 ✔️ ⚒ FastAPI ⚖️ 💃 👷, 📏 ⚫️ ⏩ 🔫 🔌.

🏢, 🔫 🛠️ 🎓 👈 ⌛ 📨 🔫 📱 🥇 ❌.

, 🧾 🥉-🥳 🔫 🛠️ 👫 🔜 🎲 💬 👆 🕳 💖:

from unicorn import UnicornMiddleware

app = SomeASGIApp()

new_app = UnicornMiddleware(app, some_config="rainbow")

✋️ FastAPI (🤙 💃) 🚚 🙅 🌌 ⚫️ 👈 ⚒ 💭 👈 🔗 🛠️ 🍵 💽 ❌ & 🛃 ⚠ 🐕‍🦺 👷 ☑.

👈, 👆 ⚙️ app.add_middleware() (🖼 ⚜).

from fastapi import FastAPI
from unicorn import UnicornMiddleware

app = FastAPI()

app.add_middleware(UnicornMiddleware, some_config="rainbow")

app.add_middleware() 📨 🛠️ 🎓 🥇 ❌ & 🙆 🌖 ❌ 🚶‍♀️ 🛠️.

🛠️ 🛠️

FastAPI 🔌 📚 🛠️ ⚠ ⚙️ 💼, 👥 🔜 👀 ⏭ ❔ ⚙️ 👫.

📡 ℹ

⏭ 🖼, 👆 💪 ⚙️ from starlette.middleware.something import SomethingMiddleware.

FastAPI 🚚 📚 🛠️ fastapi.middleware 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.

HTTPSRedirectMiddleware

🛠️ 👈 🌐 📨 📨 🔜 👯‍♂️ https ⚖️ wss.

🙆 📨 📨 http ⚖️ ws 🔜 ❎ 🔐 ⚖ ↩️.

from fastapi import FastAPI
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware

app = FastAPI()

app.add_middleware(HTTPSRedirectMiddleware)


@app.get("/")
async def main():
    return {"message": "Hello World"}

TrustedHostMiddleware

🛠️ 👈 🌐 📨 📨 ✔️ ☑ ⚒ Host 🎚, ✔ 💂‍♂ 🛡 🇺🇸🔍 🦠 🎚 👊.

from fastapi import FastAPI
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()

app.add_middleware(
    TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"]
)


@app.get("/")
async def main():
    return {"message": "Hello World"}

📄 ❌ 🐕‍🦺:

  • allowed_hosts - 📇 🆔 📛 👈 🔜 ✔ 📛. 🃏 🆔 ✅ *.example.com 🐕‍🦺 🎀 📁. ✔ 🙆 📛 👯‍♂️ ⚙️ allowed_hosts=["*"] ⚖️ 🚫 🛠️.

🚥 📨 📨 🔨 🚫 ✔ ☑ ⤴️ 400 📨 🔜 📨.

GZipMiddleware

🍵 🗜 📨 🙆 📨 👈 🔌 "gzip" Accept-Encoding 🎚.

🛠️ 🔜 🍵 👯‍♂️ 🐩 & 🎥 📨.

from fastapi import FastAPI
from fastapi.middleware.gzip import GZipMiddleware

app = FastAPI()

app.add_middleware(GZipMiddleware, minimum_size=1000)


@app.get("/")
async def main():
    return "somebigcontent"

📄 ❌ 🐕‍🦺:

  • minimum_size - 🚫 🗜 📨 👈 🤪 🌘 👉 💯 📐 🔢. 🔢 500.

🎏 🛠️

📤 📚 🎏 🔫 🛠️.

🖼:

👀 🎏 💪 🛠️ ✅ 💃 🛠️ 🩺 & 🔫 👌 📇.