You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python开发Bot部署至Microsoft Azure Web App失败求助

Azure Web App部署Python Bot应用错误排查与解决

一、先定位具体错误

Azure Web App的泛用错误提示无法直接定位问题,先通过日志获取详细信息:

  • 登录Azure门户,找到目标Web App(apollo001webapp)
  • 左侧菜单选择「监控」→「日志流」,实时查看应用运行日志
  • 或进入「高级工具」→「Kudu」,在「Debug console」中查看LogFiles目录下的日志文件

二、代码与配置修复

1. 添加依赖声明文件

Azure需要通过requirements.txt安装Python依赖,创建该文件并写入以下内容:

aiohttp==3.9.3
botbuilder-core==4.22.0
botbuilder-schema==4.22.0
python-dotenv==1.0.1
openai==1.14.3

2. 调整端口适配Azure环境

Azure Web App通过PORT环境变量指定运行端口,修改代码启动逻辑:
首先在代码顶部补充导入os模块:

import os

然后修改启动部分:

if __name__ == "__main__":
    settings = BotFrameworkAdapterSettings(app_id="", app_password="")
    adapter = BotFrameworkAdapter(settings)
    bot = EchoBot()
    app = web.Application()

    async def messages(req: web.Request) -> web.Response:
        if "application/json" in req.headers.get("Content-Type", ""):
            body = await req.json()
            activity = Activity.deserialize(body)
            auth_header = req.headers.get("Authorization", "")
            await adapter.process_activity(activity, auth_header, bot.on_turn)
            return web.Response(status=200)
        return web.Response(status=415)

    app.router.add_post("/api/messages", messages)
    # 读取Azure指定端口,默认回退到3978
    port = int(os.getenv("PORT", 3978))
    web.run_app(app, host='0.0.0.0', port=port)

3. 修复异步初始化冲突

原代码中EchoBot初始化时用asyncio.run同步调用异步函数,在Web环境会导致循环冲突,修改为延迟初始化:

class EchoBot:
    def __init__(self):
        self.access_token = None
        self.token_expire_time = 0

    async def ensure_access_token(self):
        """ Ensure a valid access token is always available. """
        if not self.access_token or asyncio.get_running_loop().time() > self.token_expire_time:
            self.access_token, self.token_expire_time = await get_access_token()
            if not self.access_token:
                raise Exception("Unable to retrieve a valid token")

4. 配置Azure环境变量

放弃依赖本地.env文件,直接在Azure Web App中配置:

  • 进入Web App的「配置」→「应用程序设置」
  • 添加以下环境变量:
    • OPENAI_API_KEY
    • INGRAM_CLIENT_ID
    • INGRAM_CLIENT_SECRET
    • INGRAM_CUSTOMER_NUMBER
  • 若Bot已注册到Bot Framework,需额外添加MicrosoftAppId和MicrosoftAppPassword,并修改代码中的初始化逻辑:
settings = BotFrameworkAdapterSettings(
    app_id=os.getenv("MicrosoftAppId", ""),
    app_password=os.getenv("MicrosoftAppPassword", "")
)

三、重新部署验证

修改完成后,通过VS Code Azure扩展重新部署到Web App,部署完成后查看日志确认应用启动成功,再测试Bot功能。

内容的提问来源于stack exchange,提问作者K V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 18:22:32