Reputation: 861
I'm trying to create a simple Azure Function that checks whether a given URL is available (this is just a proof-of-concept). My problem is I can't figure out which library I need to import to get thr client class. The Azure docs are not at all clear, and all examples are C# or .NET
import logging
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
target = req.params.get('target')
if not target:
try:
req_body = req.get_json()
except ValueError:
pass
else:
target = req_body.get('target')
if target:
try:
MyClient = HttpClient()
response = MyClient.GetAsync(f"http://{target}")
except:
return func.HttpResponse("Error", status_code = 500)
if response.StatusCode == 200 or response.StatusCode == 302:
return func.HttpResponse("OK")
else:
return func.HttpResponse("Bad", status_code = 503)
else:
return func.HttpResponse(
"No target specified",
status_code=400
)
Requirements.txt:
azure-functions==1.2.1
altgraph==0.17
future==0.18.2
pefile==2019.4.18
PyInstaller==3.6
pywin32-ctypes==0.2.0
PyYAML==5.3.1
requests==2.24.0
Upvotes: 1
Views: 439
Reputation: 15734
For this requirement, you can install requests
in your python function by running the below command in "Terminal" window of VS code.
pip install requests
And then import it and use it as below (just check the status_code
of response
):
Update:
According to some test, I reproduced your problem. It seems you didn't install the requests
module success on azure, you just install it in your function in local. Please refer to the steps below:
1. I assume you have installed the requests
module in local and run the function success in local(if still have problem, please let me know). Then please run the below command in "Terminal" window in VS code to generate the "requirements.txt".
pip freeze > requirements.txt
The "requirements.txt" is used to install modules, when you deploy the function to azure, azure will install the modules according to the content in "requirements.txt". After running the command above to generate the "requirements.txt", you can see it show like this:
The reason for your function showed 500 error(with "this page isn't working") is missing "requests" in "requirements.txt".
2. Then run the command in "Terminal" window to deploy the function from local to azure.
func azure functionapp publish <functionAppName> --build remote
The <functionAppName>
is the name of the function app(python) you created on azure portal.
3. After that, go to azure portal to test your function, it will work fine.
Upvotes: 1