【发布时间】:2021-09-24 10:14:39
【问题描述】:
我是 azure 函数应用的新手。我正在开发一个应用程序来生成 wordcloud,为此,我正在从 Cosmos DB 中获取我的数据。使用 VS Code 在本地一切正常。当我在 azure 函数应用程序上部署 azure 函数时,部署成功,在浏览器中,我收到以下消息。
This HTTP-triggered function was executed successfully. Pass a name in the query string or the request body for a personalized response.
表示部署成功。但是当我传递 Query 参数并调用 get_wordcloud 函数时,它会抛出 500 Internal Server Error。我的猜测是它无法在 Azure 环境中写入图像文件。以下是我的__init__.py 文件:
import logging
import azure.functions as func
from azure.cosmos import CosmosClient
import os
from pandas import json_normalize
from wordcloud import WordCloud, STOPWORDS
from PIL import Image
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
db_name = req.params.get('db_name')
container_name = req.params.get('container_name')
if not db_name and not container_name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
db_name = req_body.get('db_name')
container_name = req_body.get('container_name')
if db_name and container_name:
url = os.environ.get('ACCOUNT_URI')
key = os.environ.get('ACCOUNT_KEY')
client = CosmosClient(url, credential=key)
database = client.get_database_client(db_name)
container = database.get_container_client(container_name)
print(database)
print(container)
query = 'SELECT * FROM c'
result = list(container.query_items(
query, enable_cross_partition_query=True))
df = json_normalize(result)
stopwords = set(STOPWORDS)
wordcloud = WordCloud(
background_color='white',
stopwords=stopwords,
max_words=500,
width=1080,
height=640,
).generate(str(df))
wordcloud.to_file("wordcloud_result.png")
file = open(u'wordcloud_result.png', 'rb')
result = file.read()
return func.HttpResponse(result)
else:
return func.HttpResponse(
"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
status_code=200
)
下面是function.json文件:
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
在__init__.py 替换下面的代码时
wordcloud.to_file("wordcloud_result.png")
file = open(u'wordcloud_result.png', 'rb')
result = file.read()
return func.HttpResponse(result)
使用以下代码
return func.HttpResponse('Successful')
它正在成功运行。
【问题讨论】:
-
500 状态码表示存在未处理的异常。我建议将整个函数代码放在 try/catch 块中并记录异常。请在您的问题中分享该例外情况。
标签: azure-functions azure-cosmosdb azure-http-trigger