Dependency Injection implementation for aiogram 3.
Project description
Example of usage
import logging
from os import getenv
from typing import Annotated
from aiogram import Router, Bot, Dispatcher
from aiogram.types import Message, User
from aiogram3_di import DIMiddleware, Depends
router = Router()
def get_user_full_name(event_from_user: User) -> str:
return event_from_user.full_name
@router.message()
async def _(message: Message, full_name: Annotated[str, Depends(get_user_full_name)]) -> None:
await message.answer(f'Hi {full_name}')
def main() -> None:
logging.basicConfig(level=logging.INFO)
bot = Bot(token=getenv('BOT_TOKEN'))
dp = Dispatcher()
dp.include_router(router)
dp.message.middleware(DIMiddleware()) # register Dependency Injection middleware
dp.run_polling(bot)
if __name__ == '__main__':
main()
Handler Dependencies.
You can use Depends
in the flags parameter of the handler, for example:
flags={'dependencies': [Depends(verify_user)]}
Global Dependencies.
You can use Depends
in dispatcher
, for example:
dp = Dispatcher()
dp.dependencies = [Depends(verify_user)]
Or in router
, for example:
router = Router()
router.dependencies = [Depends(verify_user)]
Details
It is inspired by FastAPI.
If you define a normal def, your function will be called in a different thread.
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
aiogram3_di-1.0.4.tar.gz
(4.7 kB
view details)
File details
Details for the file aiogram3_di-1.0.4.tar.gz
.
File metadata
- Download URL: aiogram3_di-1.0.4.tar.gz
- Upload date:
- Size: 4.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.10.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | bc4268a3a2858c92e3b57c018bab8f1ff2e956d0db6723d8445b36498d935553 |
|
MD5 | 7e855fe99f1a139b202a49ac5b46bae4 |
|
BLAKE2b-256 | 4e68458c1dd4950c5805acc879341d8a80345996e593c68915357d8ebe50a5a7 |