-
|
Hi! I'm fairly new to FastAPI but I like it alot so far. Im working my way through to the more advanced stuff now; currently I'm trying to send E-mails as a background task. For this I want to use the internal Mail Client from our company, which is a context manager and works something like this: with MailClient(credentials) as mail_client:
mail.send(to="alice@example.com", subject="Hello world", message="some message")However im struggling how put together all the information I got from https://fastapi.tiangolo.com/tutorial/background-tasks/ and https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/ for my goal. What I'd like to achieve is something like that: @app.get("/send")
async def(mailer: Mailer = Depends()):
mailer.send(to="alice@example.com", subject="Hello world", message="some message")The Mailers send method should have the same signature as MailClient (or just use kwargs). Internally it should call add_task to invoke the send-method of the MailClient in background. Additionally the Mailer should open and close the connection to the smtp-Server (this is what the MailClient does in its __enter__ and __exit__ methods) when the request is processed. Is this even possible? Regards, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
|
I came up with this, but i dont know if it's the correct way of doing it: from mycompany import MailClient
def _client():
with MailClient({'username': 'john', 'password': 'secretsauce'}) as dep:
yield dep
class Mail:
def __init__(self, bt, client):
self.background_tasks = bt
self.client= client
@staticmethod
def inject(background_tasks: BackgroundTasks, client=Depends(_client)):
return Mail(background_tasks, client)
def send(self, *args, **kwargs):
self.background_tasks.add_task(self.client.send, *args, **kwargs)Now i can just from tasks import Mailer
app = FastAPI()
@app.get("/send")
async def send_mail(mail: Mail = Depends(Mail.inject)):
mail.send(message="...") |
Beta Was this translation helpful? Give feedback.
-
|
I would use something like this: async def send_mail():
try:
yield
finally:
# sending mail
# this part will be executed after the response, so it will be like background task, I think
@app.get("/send", dependencies=[Depends(send_mail)])
async def send_mail():
pass |
Beta Was this translation helpful? Give feedback.
I came up with this, but i dont know if it's the correct way of doing it:
Now i can just