简体   繁体   中英

Passing arguments to python azure function via url

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()

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:\local\Temp\Functions\Binding\79fcec12-baf3-470e-87c3-113f64ffcef0\req
# during the execution

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.

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?

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.

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'] .

I was also having this issue. The example at this link says to test it with a url of type

https://<app_name>.azurewebsites.net/api/MyHttpTrigger?name=<yourname>

When testing locally this format works, but I finally figured out that when testing once deployed that the link it gives in the command line of type

https://<appname>.azurewebsites.net/api/MyHttpTrigger?code=<randomcode>/<randomcode>==

is what you really need. Add on your &name=<yourName> to this link instead. Mine worked for

https://<appname>.azurewebsites.net/api/MyHttpTrigger?code=<randomcode>/<randomcode>==&name=<yourName>

Not sure if you have already tried this since your question wasn't entirely clear, but hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM