我是天蓝色函数应用程序的新手。我正在开发一个应用程序来生成 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')
它工作成功。