我是 Azure 函数和 python 的新手。我已经使用 python v2 编程模型创建了一个 Azure 函数,并且可以从 VS code 成功执行它。但是,当尝试使用 VS 代码扩展和 CLI 进行部署时,部署成功,但该功能没有出现。我已经尝试了网上建议的大部分选项,但没有解决这个问题。我已经被困在这个问题上有一段时间了。任何帮助将不胜感激。
注意:由于我的功能正在使用消费计划,所以我无法真正使用 kudu 来检查 wwwroot 目录。我已尝试按照建议使用 API 手动同步触发器,但该功能仍然没有出现。
import azure.functions as func
import logging
import psycopg2
import flask
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
@app.route(route="InsertFileInfo")
def InsertFileInfo(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
# Connection string information
host = "host"
dbname = "dbname"
user = "dbname"
password = "password"
sslmode = "require"
# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
# Get JSON payload from the HTTP request
try:
payload = req.get_json()
except ValueError:
return func.HttpResponse("Invalid JSON payload", status_code=400)
file_details = payload.get('fileDetails', {})
sender = payload.get('sender', {})
workflow_id = payload.get('workflowID')
workflow_event = payload.get('workflowEvent')
# Extracting values from nested dictionaries
created_at = file_details.get('createdAt')
file_id = file_details.get('fileID')
file_key = file_details.get('key')
receiver_sha256_hash = file_details.get('receiverSHA256Hash')
application_id = sender.get('applicationID')
zone = sender.get('zone')
# Connect to the database
try:
connection = psycopg2.connect(conn_string)
cursor = connection.cursor()
# SQL query to insert data into the table
insert_query = """INSERT INTO file_info (created_at, file_id, file_key, receiver_sha256_hash,
sender_applicationid, zone, workflow_id, workflow_event)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"""
# Data tuple to be inserted
data_tuple = (created_at, file_id, file_key, receiver_sha256_hash, application_id, zone, workflow_id, workflow_event)
# Executing the SQL command
cursor.execute(insert_query, data_tuple)
# Committing the changes to the database
connection.commit()
# Close Cursor and Connection
cursor.close()
connection.close()
return func.HttpResponse("Data inserted successfully", status_code=200)
except Exception as e:
logging.error(str(e))
return func.HttpResponse("Error inserting data", status_code=500)
local.settings.json 文件:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=cftwebhook;AccountKey=M2fgac7RMXqWEXDhfxcTP2MjogasutKC4PZzrLCoHerChvVH6SDXuEnCnxOh7DX1R7Ezst4s/LhM+ASt3Y7PYQ==;EndpointSuffix=core.windows.net",
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsFeatureFlags": "EnableWorkerIndexing"
}
}
主机 json 文件:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
注意:当我打开主机 json 文件时,我看到以下错误。
需求.txt:
azure-functions==1.18.0
Flask==3.0.0
psycopg2==2.9.9
psycopg2-binary==2.9.9
输出:
PS C:\Sivanesan> func azure functionapp publish cftwebhook
Getting site publishing info...
[2024-04-05T04:05:42.430Z] Starting the function app deployment...
Creating archive for current directory...
Performing remote build for functions project.
Deleting the old .python_packages directory
Could not find gozip for packaging. Using DotNetZip to package. This may cause problems preserving file permissions when using in a Linux based environment.
Uploading 3.99 KB [###############################################################################]
Remote build in progress, please wait...
Updating submodules.
Preparing deployment for commit id '8da31d4a-5'.
PreDeployment: context.CleanOutputPath False
PreDeployment: context.OutputPath /home/site/wwwroot
Repository path is /tmp/zipdeploy/extracted
Running oryx build...
Command: oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform python --platform-version 3.11 -p packagedir=.python_packages/lib/site-packages
Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx
You can report issues at https://github.com/Microsoft/Oryx/issues
Oryx Version: 0.2.20230210.1, Commit: a49c8f6b8abbe95b4356552c4c884dea7fd0d86e, ReleaseTagName: 20230210.1
Build Operation ID: 650efe847b4b9431
Repository Commit : 8da31d4a-5cb9-4b4d-a70c-9db4219f620c
OS Type : bullseye
Image Type : githubactions
Detecting platforms...
Detected following platforms:
python: 3.11.8
Source directory : /tmp/zipdeploy/extracted
Destination directory: /home/site/wwwroot
Python Version: /tmp/oryx/platforms/python/3.11.8/bin/python3.11
Creating directory for command manifest file if it does not exist
Removing existing manifest file
Running pip install...
Done in 12 sec(s).
[04:05:55+0000] Collecting azure-functions==1.18.0
[04:05:55+0000] Using cached azure_functions-1.18.0-py3-none-any.whl (173 kB)
[04:05:55+0000] Collecting Flask==3.0.0
[04:05:55+0000] Using cached flask-3.0.0-py3-none-any.whl (99 kB)
[04:05:55+0000] Collecting psycopg2==2.9.9
[04:05:55+0000] Using cached psycopg2-2.9.9.tar.gz (384 kB)
[04:05:56+0000] Collecting psycopg2-binary==2.9.9
[04:05:56+0000] Using cached psycopg2_binary-2.9.9-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.0 MB)
[04:05:56+0000] Collecting itsdangerous>=2.1.2
[04:05:56+0000] Using cached itsdangerous-2.1.2-py3-none-any.whl (15 kB)
[04:05:56+0000] Collecting Werkzeug>=3.0.0
[04:05:56+0000] Downloading werkzeug-3.0.2-py3-none-any.whl (226 kB)
[04:05:56+0000] Collecting blinker>=1.6.2
[04:05:56+0000] Downloading blinker-1.7.0-py3-none-any.whl (13 kB)
[04:05:56+0000] Collecting click>=8.1.3
[04:05:56+0000] Using cached click-8.1.7-py3-none-any.whl (97 kB)
[04:05:56+0000] Collecting Jinja2>=3.1.2
[04:05:56+0000] Downloading Jinja2-3.1.3-py3-none-any.whl (133 kB)
[04:05:56+0000] Collecting MarkupSafe>=2.0
[04:05:56+0000] Downloading MarkupSafe-2.1.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (28 kB)
[04:05:56+0000] Building wheels for collected packages: psycopg2
[04:05:56+0000] Building wheel for psycopg2 (setup.py): started
[04:06:05+0000] Building wheel for psycopg2 (setup.py): finished with status 'done'
[04:06:05+0000] Created wheel for psycopg2: filename=psycopg2-2.9.9-cp311-cp311-linux_x86_64.whl size=490670 sha256=fb3a4c4671c5e98d77e3d855f216298afa3bde8c4121a0657c18a8668138258c
[04:06:05+0000] Stored in directory: /usr/local/share/pip-cache/wheels/ab/34/b9/78ebef1b3220b4840ee482461e738566c3c9165d2b5c914f51
[04:06:05+0000] Successfully built psycopg2
[04:06:05+0000] Installing collected packages: MarkupSafe, Werkzeug, Jinja2, itsdangerous, click, blinker, psycopg2-binary, psycopg2, Flask, azure-functions
[04:06:06+0000] Successfully installed Flask-3.0.0 Jinja2-3.1.3 MarkupSafe-2.1.5 Werkzeug-3.0.2 azure-functions-1.18.0 blinker-1.7.0 click-8.1.7 itsdangerous-2.1.2 psycopg2-2.9.9 psycopg2-binary-2.9.9
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
WARNING: You are using pip version 21.2.4; however, version 24.0 is available.
You should consider upgrading via the '/tmp/oryx/platforms/python/3.11.8/bin/python3.11 -m pip install --upgrade pip' command.
Not a vso image, so not writing build commands
Preparing output...
Copying files to destination directory '/home/site/wwwroot'...
Done in 0 sec(s).
Removing existing manifest file
Creating a manifest file...
Manifest file created.
Copying .ostype to manifest output directory.
Done in 12 sec(s).
Running post deployment command(s)...
Generating summary of Oryx build
Deployment Log file does not exist in /tmp/oryx-build.log
The logfile at /tmp/oryx-build.log is empty. Unable to fetch the summary of build
Triggering recycle (preview mode disabled).
Linux Consumption plan has a 1.5 GB memory limit on a remote build container.
To check our service limit, please visit https://docs.microsoft.com/en-us/azure/azure-functions/functions-scale#service-limits
Writing the artifacts to a squashfs file
Parallel mksquashfs: Using 1 processor
Creating 4.0 filesystem on /home/site/artifacts/functionappartifact.squashfs, block size 131072.
[===============================================================\] 576/576 100%
Exportable Squashfs 4.0 filesystem, gzip compressed, data block size 131072
compressed data, compressed metadata, compressed fragments,
compressed xattrs, compressed ids
duplicates are removed
Filesystem size 5302.05 Kbytes (5.18 Mbytes)
35.94% of uncompressed filesystem size (14751.09 Kbytes)
Inode table size 5697 bytes (5.56 Kbytes)
29.56% of uncompressed inode table size (19270 bytes)
Directory table size 5688 bytes (5.55 Kbytes)
38.25% of uncompressed directory table size (14870 bytes)
Number of duplicate files found 31
Number of inodes 593
Number of files 532
Number of fragments 58
Number of symbolic links 0
Number of device nodes 0
Number of fifo nodes 0
Number of socket nodes 0
Number of directories 61
Number of ids (unique uids + gids) 1
Number of uids 1
root (0)
Number of gids 1
root (0)
Creating placeholder blob for linux consumption function app...
SCM_RUN_FROM_PACKAGE placeholder blob scm-latest-CFTWebhook.zip located
Uploading built content /home/site/artifacts/functionappartifact.squashfs for linux consumption function app...
Resetting all workers for cftwebhook.azurewebsites.net
Deployment successful. deployer = Push-Deployer deploymentPath = Functions App ZipDeploy. Extract zip. Remote build.
Remote build succeeded!
[2024-04-05T04:06:19.747Z] Syncing triggers...
Functions in CFTWebhook:
我已经尝试了网上提供的大部分建议,但无法正常工作
问候 西瓦内桑
尝试使用下面的代码并将您的函数部署到基于消费的函数应用程序:-
我的函数HttpTrigger代码:-
import azure.functions as func
import logging
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
@app.route(route="InsertFileInfo")
def InsertFileInfo(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
# Connection string information
host = "host"
dbname = "dbname"
user = "dbname"
password = "password"
sslmode = "require"
# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
# Get JSON payload from the HTTP request
try:
payload = req.get_json()
except ValueError:
return func.HttpResponse("Invalid JSON payload", status_code=400)
file_details = payload.get('fileDetails', {})
sender = payload.get('sender', {})
workflow_id = payload.get('workflowID')
workflow_event = payload.get('workflowEvent')
# Extracting values from nested dictionaries
created_at = file_details.get('createdAt')
file_id = file_details.get('fileID')
file_key = file_details.get('key')
receiver_sha256_hash = file_details.get('receiverSHA256Hash')
application_id = sender.get('applicationID')
zone = sender.get('zone')
# Connect to the database
try:
connection = psycopg2.connect(conn_string)
cursor = connection.cursor()
# SQL query to insert data into the table
insert_query = """INSERT INTO file_info (created_at, file_id, file_key, receiver_sha256_hash,
sender_applicationid, zone, workflow_id, workflow_event)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"""
# Data tuple to be inserted
data_tuple = (created_at, file_id, file_key, receiver_sha256_hash, application_id, zone, workflow_id, workflow_event)
# Executing the SQL command
cursor.execute(insert_query, data_tuple)
# Committing the changes to the database
connection.commit()
# Close Cursor and Connection
cursor.close()
connection.close()
return func.HttpResponse("Data inserted successfully", status_code=200)
except Exception as e:
logging.error(str(e))
return func.HttpResponse("Error inserting data", status_code=500)
输出:-
确保您的函数应用配置设置或环境变量中存在以下设置:-
"name": "AzureWebJobsFeatureFlags",
"value": "EnableWorkerIndexing",