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.

๐ŸŽ ๐Ÿ› ๏ธ

๐Ÿ“ค ๐Ÿ“š ๐ŸŽ ๐Ÿ”ซ ๐Ÿ› ๏ธ.

๐Ÿ–ผ:

๐Ÿ‘€ ๐ŸŽ ๐Ÿ’ช ๐Ÿ› ๏ธ โœ… ๐Ÿ’ƒ ๐Ÿ› ๏ธ ๐Ÿฉบ & ๐Ÿ”ซ ๐Ÿ‘Œ ๐Ÿ“‡.