You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6.2 KiB

🔆 🎉

👆 💪 🔬 ⚛ (📟) 👈 🔜 🛠️🈸 ▶️ 🆙. 👉👈 👉 📟 🔜 🛠️ 🕐, 🈸 ▶️ 📨 📨.

🎏 🌌, 👆 💪 🔬 ⚛ (📟) 👈 🔜 🛠️ 🕐 🈸 🤫 🔽. 👉 💼, 👉 📟 🔜 🛠️ 🕐, ⏮️ ✔️ 🍵 🎲 📚 📨.

↩️ 👉 📟 🛠️🈸 ▶️ 📨, & ▶️⏮️ 🏁 🚚 📨, 📔 🎂 🈸 🔆 (🔤 "🔆" 🔜🥈 👶).

👉 💪 📶 ⚠ ⚒ 🆙 👈 👆 💪 ⚙️ 🎂 📱, & 👈 💰 👪 📨, &/⚖️ 👈 👆 💪 🧹 🆙 ⏮️. 🖼, 💽 🔗 🎱, ⚖️ 🚚 🔗 🎰 🏫 🏷.

⚙️ 💼

➡️ ▶️ ⏮️ 🖼 ⚙️ 💼 & ⤴️ 👀 ⏮️ 👉.

➡️ 🌈 👈 👆 ✔️ 🎰 🏫 🏷 👈 👆 💚 ⚙️ 🍵 📨. 👶

🎏 🏷 🔗 👪 📨,, 🚫 1️⃣ 🏷 📍 📨, ⚖️ 1️⃣ 📍 👩‍💻 ⚖️ 🕳 🎏.

➡️ 🌈 👈 🚚 🏷 💪 🕰, ↩️ ✔️📚 💽 ➡️ 💾. 👆 🚫 💚 🔠 📨.

👆 💪 📐 🔝 🎚 🕹/📁, 👈 🔜👈 🔜 📐 🏷 🚥 👆 🏃‍♂ 🙅 🏧 💯, ⤴️ 👈 💯 🔜 🐌 ↩️ 🔜 ✔️ 🏷 📐💆‍♂ 💪 🏃 🔬 🍕 📟.

👈 👥 🔜 , ➡️ 📐 🏷 ⏭ 📨 🍵, ️ 🕴 ▶️️ ⏭ 🈸 ▶️ 📨 📨, 🚫 📟 📐.

🔆

👆 💪 🔬 👉 🕴 & 🤫⚙️ lifespan 🔢 FastAPI 📱, & "🔑 👨‍💼" (👤 🔜 🎦 👆 👈 🥈).

➡️ ▶️ ⏮️ 🖼 & ⤴️ 👀 ️ ℹ.

👥🔁 🔢 lifespan() ⏮️ yield 💖 👉:

{!../../../docs_src/events/tutorial003.py!}

📥 👥😥 🕴 🛠️ 🚚 🏷 🚮 () 🏷 🔢 📖 ⏮️ 🎰 🏫 🏷 ⏭ yield. 👉 📟 🔜 🛠️ 🈸 ▶️ 📨, ⏮️ 🕴.

& ⤴️, ▶️⏮️ yield, 👥 🚚 🏷. 👉 📟 🔜 🛠️ ⏮️ 🈸 🏁 🚚 📨, ▶️️ ⏭ 🤫. 👉 💪, 🖼, 🚀💖 💾 ⚖️ 💻.

!!! tip shutdown 🔜 🔨 🕐 👆 🈸.

🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷

🔆 🔢

🥇 👜 👀, 👈 👥🔁 🔢 ⏮️ yield. 👉 📶 🎏 🔗 ⏮️ yield.

{!../../../docs_src/events/tutorial003.py!}

🥇 🍕 🔢, ⏭ yield, 🔜 🛠️ 🈸 ▶️.

& 🍕 ⏮️ yield 🔜 🛠️ ⏮️ 🈸 ✔️ 🏁.

🔁 🔑 👨‍💼

🚥 👆 , 🔢 🎀 ⏮️ @asynccontextmanager.

👈 🗜 🔢 🔘 🕳 🤙 "🔁 🔑 👨‍💼".

{!../../../docs_src/events/tutorial003.py!}

🔑 👨‍💼 🐍 🕳 👈 👆 💪 ⚙️ with 📄, 🖼, open() 💪 ⚙️ 🔑 👨‍💼:

with open("file.txt") as file:
    file.read()

⏮️ 🐍, 📤 🔁 🔑 👨‍💼. 👆 🔜 ⚙️ ⏮️ async with:

async with lifespan(app):
    await do_stuff()

🕐 👆🔑 👨‍💼 ⚖️ 🔁 🔑 👨‍💼 💖 🔛, 🔨 👈, ⏭ 🛬 with 🍫, 🔜 🛠️ 📟yield, & ⏮️ with 🍫, 🔜 🛠️ 📟 ⏮️ yield.

👆 📟 🖼 🔛, 👥 🚫 ⚙️ 🔗, 👥 🚶‍♀️ ️ FastAPI ⚙️ ️.

lifespan 🔢 FastAPI 📱 🔁 🔑 👨‍💼, 👥 💪 🚶‍♀️ 👆 🆕 lifespan 🔁 🔑 👨‍💼 ️.

{!../../../docs_src/events/tutorial003.py!}

🎛 🎉 (😢)

!!! warning 👍 🌌 🍵 🕴 & 🤫 ⚙️ lifespan 🔢 FastAPI 📱 🔬 🔛.

👆 💪 🎲 🚶 👉 🍕.

📤 🎛 🌌 🔬 👉🛠️ ⏮️ 🕴 & ⏮️ 🤫.

👆 💪 🔬 🎉 🐕‍🦺 (🔢) 👈 💪 🛠️🈸 ▶️ 🆙, ⚖️ 🕐 🈸 🤫 🔽.

👫 🔢 💪 📣 ⏮️ async def ⚖️ 😐 def.

startup 🎉

🚮 🔢 👈 🔜 🏃🈸 ▶️, 📣 ⏮️ 🎉 "startup":

{!../../../docs_src/events/tutorial001.py!}

👉 💼, startup 🎉 🐕‍🦺 🔢 🔜 🔢 🏬 "💽" ( dict) ⏮️ 💲.

👆 💪 🚮 🌅 🌘 1️⃣ 🎉 🐕‍🦺 🔢.

& 👆 🈸 🏆 🚫 ▶️ 📨 📨🌐 startup 🎉 🐕‍🦺 ✔️ 🏁.

shutdown 🎉

🚮 🔢 👈 🔜 🏃 🕐 🈸 🤫 🔽, 📣 ⏮️ 🎉 "shutdown":

{!../../../docs_src/events/tutorial002.py!}

📥, shutdown 🎉 🐕‍🦺 🔢 🔜 ✍ ✍ ⏸ "Application shutdown" 📁 log.txt.

!!! info open() 🔢, mode="a" ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚.

!!! tip 👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 open() 🔢 👈 🔗 ⏮️ 📁.

, ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾.

✋️ `open()` 🚫 ⚙️ `async` & `await`.

, 👥 📣 🎉 🐕‍🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`.

!!! info 👆 💪🌅 🔃 👫 🎉 🐕‍🦺 💃 🎉' 🩺.

startup & shutdown 👯‍♂️

📤🤞 👈👆 🕴 & 🤫 🔗, 👆 💪 💚 ▶️ 🕳 & ⤴️ 🏁 ️, 📎 ℹ & ⤴️ 🚀 ️, ️.

🔨 👈 👽 🔢 👈 🚫 💰⚖️ 🔢 👯‍♂️ 🌅👆 🔜 💪 🏪 💲 🌐 🔢 ⚖️ 🎏 🎱.

↩️ 👈, 🔜 👍 ↩️ ⚙️ lifespan 🔬 🔛.

📡

📡😟 🤓. 👶

🔘, 🔫 📡 🔧, 👉 🍕 🔆 🛠️, & 🔬 🎉 🤙 startup & shutdown.

🎧 🈸

👶 ✔️ 🤯 👈 👫 🔆 🎉 (🕴 & 🤫) 🔜 🕴 🛠️ 👑 🈸, 🚫 🎧 🈸 - 🗻{.internal-link target=_blank}.