I found using Depends (DI approach) more ergonomic than initializing them.
For instance, payme:
@app.post("/payments/payme/webhook")
async def payme_webhook(request: Request, db: Session = Depends(get_db)):
handler = CustomPaymeWebhookHandler(
db=db,
payme_id="your_merchant_id",
payme_key="your_merchant_key",
account_model=Order,
account_field='id',
amount_field='amount'
)
return await handler.handle_webhook(request)
DI approach:
from fastapi import Depends
def get_payme_handler(db: Session = Depends(get_db)): # <- should be provided from library
return CustomPaymeWebhookHandler(
db=db,
payme_id="your_merchant_id",
payme_key="your_merchant_key",
account_model=Order,
account_field='id',
amount_field='amount'
)
...
@app.post("/payments/payme/webhook") # <- client's code (library's user)
async def payme_webhook(
request: Request,
handler: CustomPaymeWebhookHandler = Depends(get_payme_handler),
):
return await handler.handle_webhook(request)
Defining these dependencies (get_payme_handler) or documenting this approach would be beneficial I guess. My version, might be oversimplified, I haven't provided way of passing database dependency etc. Overall, I think webhook handler should be provided as a dependency.
If library will have support - that's great, otherwise, documenting this as "usage" also informative.
I found using
Depends(DI approach) more ergonomic than initializing them.For instance, payme:
DI approach:
Defining these dependencies (
get_payme_handler) or documenting this approach would be beneficial I guess. My version, might be oversimplified, I haven't provided way of passing database dependency etc. Overall, I think webhook handler should be provided as a dependency.If library will have support - that's great, otherwise, documenting this as "usage" also informative.