通过 url 将参数传递给 python azure 函数

2022-01-17 00:00:00 python azure azure-functions

问题描述

我正在尝试通过 azure 函数使 hello world 示例适用于 python.基本函数尝试通过 url 检索名称作为输入,然后响应Hello Name".事实证明,通过 azure 门户提供的示例模板不能开箱即用.基本示例如下所示:

I'm trying to make the hello world example work for python via azure functions. The basic function tries to retrieve a name as input through the url and then respond "Hello Name". It turns out that the example-template which is available through the azure portal does not work out of the box. The basic example looks like this:

import os
import json

postreqdata = json.loads(open(os.environ['req']).read())
response = open(os.environ['res'], 'w')
response.write("hello world from "+postreqdata['name'])
response.close()

两个环境变量 req 和 res 是临时文件的路径,该文件将函数的输入和输出存储为 json.这个想法是通过 url 传递的输入应该在 json.loads() 返回的字典中可用.唯一的困境是无论我做什么,位于 os.environ['req'] 的文件都是空的.

The two environment variables req and res are paths to temporary files storing input and output from the function as json. The idea is that input passed through the url should be available in the dictionary returned by json.loads(). The only dilemma is that the file located at os.environ['req'] is empty no matter what I do.

os.path.isfile(os.environ['req'])
# Returns True so the file is located at:
# D:localTempFunctionsBinding79fcec12-baf3-470e-87c3-113f64ffcef0eq
# during the execution

我也尝试了 Hello world JavaScript 示例,它直接在 azure-functions 上开箱即用.我的 python 脚本在 azure-portal 中执行时工作正常,但从 Web 浏览器触发时失败.

I tried the Hello world JavaScript example as well which works directly out of the box on azure-functions. My python script works fine when executing in within the azure-portal, but fails when triggering it from a web browser.

该函数在 Python 2.7.13 上运行,扩展名为 &name=MyName 到 https 地址.

The function runs on Python 2.7.13 with extension &name=MyName to the https adress.

我相信错误不在脚本本身,而是隐藏在某个地方的主干中.有人试过吗?

I believe the bug is not in the script itself, but hidden in the backbone somewhere. Anyone tried the same?


解决方案

你参考的默认示例(来源here) 接受 http POST 请求,并要求您的请求正文是具有名称"属性的 JSON 有效负载.

The default sample you refer to (source here) accepts an http POST request, and requires your request body to be a JSON payload with a "name" property.

为了访问 URL 查询参数,我们将它们作为不同的环境变量提供给您.例如,如果您发送查询参数foo",您可以通过 os.environ['req_query_foo'] 访问它.

To access URL query parameters, we make them available to you as distinct environment variables. For example, if you send query parameter "foo", you can access it via os.environ['req_query_foo'].

相关文章