嗨,我有一个 python 代码,我需要使用 azure 函数来执行它,问题是它不起作用,因为它说它没有安装请求,我知道我需要使用 requests.txt 来安装但如果我使用无服务器选项,我该如何使用它,我该如何执行此代码?
import logging
import requests
from azure.functions import TimerRequest
from datetime import datetime, timezone
def main(mytimer: TimerRequest) -> None:
utc_timestamp = datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()
if mytimer.past_due:
logging.info('The timer is past due!')
url = "https://test.com/dtes/1"
payload={}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
它显示:结果:失败异常:ModuleNotFoundError:没有名为“requests”的模块。
我需要做什么来解决这个问题?
谢谢
失败异常:ModuleNotFoundError:没有名为“requests”的模块。
要解决 Azure Function 中的问题
ModuleNotFoundError: No module named 'requests'
,您需要确保 requests
库在您的函数环境中可用。
requirements.txt
文件中指定所需的依赖项来处理此问题。我已经在
requests
中添加了requirements.txt
库,并使用pip install -r requirements.txt
命令安装了requirement.txt。
以下功能代码运行成功。
import logging
import requests
from datetime import datetime, timezone
import azure.functions as func
def main(mytimer: func.TimerRequest) -> None:
utc_timestamp = datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()
if mytimer.past_due:
logging.info('The timer is past due!')
url = "http://localhost:8000/"
headers = {}
try:
# Make GET request to the specified URL
response = requests.get(url, headers=headers)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Parse JSON data from the response
json_data = response.json()
# Iterate over each item in the JSON array
for item in json_data:
item_id = item.get('id')
item_name = item.get('name')
item_price = item.get('price')
# Log details of each item
logging.info(f"Item ID: {item_id}, Name: {item_name}, Price: ${item_price:.2f}")
else:
logging.error(f"HTTP GET request failed with status code: {response.status_code}")
except requests.RequestException as e:
logging.error(f"Error occurred during HTTP GET request: {str(e)}")
except ValueError as e:
logging.error(f"Error parsing JSON response: {str(e)}")
except Exception as e:
logging.error(f"An unexpected error occurred: {str(e)}")
我能够获得有效负载响应。检查下面:
输出: