来自 python 类函数的异步响应

问题描述 投票:0回答:1

我能够成功地使用 Mailgun 示例发送电子邮件,但是在转换为类时,无法发送电子邮件。我假设它与异步响应有关,但我不确定。这是我第一次使用异步响应和 AsyncClient。

这是课程:

class Mail:

     def __init__(self):
         self.base_url = 'https://api.mailgun.net/v3/{url}'
         self.api_key = '{Key}'
         self.lstAttachment = []
         self.built = False
     def BuildMail(self):
         self.build_request_kwargs = {
                "url": "/messages",
                "method": "POST",
                "data": {
                        #"template": "template_name",
                        "from": "[email protected]",
                        "to": ["[email protected]"],
                        "subject": "Python E-mail Send",
                        "html": "<p>Hello from Python</p>"
                        },
                "files": self.lstAttachment
         }

      async def SendMail(self):
    
         if self.built == True:    
             client = httpx.AsyncClient(base_url=self.base_url, auth=("api", self.api_key))       
             return await self.__MsgSend(client)
    
         else:
             return 'Msg Not Built'


     async def __MsgSend(self, client):
         async with client as C: 
             request = C.build_request(**self.build_request_kwargs)
             response = await C.send(request)
             response.raise_for_status()
         return response

然后在我的主脚本中:

Email = M.Mail()
Email.BuildMail()
result = Email.SendMail()

我期望的是消息将被发送并且响应将返回到主脚本。

python async-await mailgun python-class
1个回答
0
投票

你不是在等待异步功能

Mail.SendMail
。我也看不到你在使用的任何地方
asyncio.run
尝试这样的事情:

async def main():
    Email = M.Mail()
    Email.BuildMail()
    result = await Email.SendMail()

asyncio.run(main())
© www.soinside.com 2019 - 2024. All rights reserved.