在 VS Code Azure Function App 选项卡中调用我的 python 函数(http 触发器)

发布于 2025-01-12 01:38:30 字数 3023 浏览 4 评论 0原文

我是 Azure Function App 的新手。

我有我的 python 代码,我想在调用 http 触发器时运行它。

我有新项目并调用“__ init __.py” 调用我的代码的正确方法是什么?

这是“__ init __.py”:

import logging
import azure.functions as func
import UploadToGCS


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        UploadToGCS(UploadToGCS.upload_files)     <--- I called it here
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

目前我收到“401错误”页面

,您能建议一下该怎么做吗?

这是我的 python 代码:(我正在使用 config_file = find("gcs_config.json", "C:/") 中的详细信息将文件上传到 Google Cloud Storage 存储桶):

from google.cloud import storage
import os
import glob
import json

# Finding path to config file that is called "gcs_config.json" in directory C:/
def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)

def upload_files(config_file):
    # Reading 3 Parameters for upload from JSON file
    with open(config_file, "r") as file:
        contents = json.loads(file.read())
        print(contents)

    # Setting up login credentials
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = contents['login_credentials']
    # The ID of GCS bucket
    bucket_name = contents['bucket_name']
    # Setting path to files
    LOCAL_PATH = contents['folder_from']

    for source_file_name in glob.glob(LOCAL_PATH + '/**'):

    # For multiple files upload
    # Setting destination folder according to file name 
        if os.path.isfile(source_file_name):
            partitioned_file_name = os.path.split(source_file_name)[-1].partition("-")
            file_type_name = partitioned_file_name[0]

            # Setting folder where files will be uploaded
            destination_blob_name = file_type_name + "/" + os.path.split(source_file_name)[-1]

            # Setting up required variables for GCS 
            storage_client = storage.Client()
            bucket = storage_client.bucket(bucket_name)
            blob = bucket.blob(destination_blob_name)

            # Running upload and printing confirmation message
            blob.upload_from_filename(source_file_name)
            print("File from {} uploaded to {} in bucket {}.".format(
                source_file_name, destination_blob_name, bucket_name
            ))

config_file = find("gcs_config.json", "C:/")

upload_files(config_file)

谨致问候, 安娜

I'm new to Azure Function App.

I have my python code that I want to run when http trigger called.

I have new project and calling in "__ init __.py"
What is the correct way to call my code?

Here is "__ init __.py":

import logging
import azure.functions as func
import UploadToGCS


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        UploadToGCS(UploadToGCS.upload_files)     <--- I called it here
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

Currently I receive "401 error" page

Can you please, suggest how it should be done?

Here is my python code: (I'm uploading file to Google Cloud Storage bucket using details in config_file = find("gcs_config.json", "C:/")):

from google.cloud import storage
import os
import glob
import json

# Finding path to config file that is called "gcs_config.json" in directory C:/
def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)

def upload_files(config_file):
    # Reading 3 Parameters for upload from JSON file
    with open(config_file, "r") as file:
        contents = json.loads(file.read())
        print(contents)

    # Setting up login credentials
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = contents['login_credentials']
    # The ID of GCS bucket
    bucket_name = contents['bucket_name']
    # Setting path to files
    LOCAL_PATH = contents['folder_from']

    for source_file_name in glob.glob(LOCAL_PATH + '/**'):

    # For multiple files upload
    # Setting destination folder according to file name 
        if os.path.isfile(source_file_name):
            partitioned_file_name = os.path.split(source_file_name)[-1].partition("-")
            file_type_name = partitioned_file_name[0]

            # Setting folder where files will be uploaded
            destination_blob_name = file_type_name + "/" + os.path.split(source_file_name)[-1]

            # Setting up required variables for GCS 
            storage_client = storage.Client()
            bucket = storage_client.bucket(bucket_name)
            blob = bucket.blob(destination_blob_name)

            # Running upload and printing confirmation message
            blob.upload_from_filename(source_file_name)
            print("File from {} uploaded to {} in bucket {}.".format(
                source_file_name, destination_blob_name, bucket_name
            ))

config_file = find("gcs_config.json", "C:/")

upload_files(config_file)

Kind regards,
Anna

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纸伞微斜 2025-01-19 01:38:30

我以其他人没有做过的方式回复这个问题,有人可能会偶然发现这个帖子来寻找答案。

要从 VS Code 本地运行函数:

  1. 在本地环境中启动函数,在 vscode 内的终端中运行命令:

    函数初始化

这将在您的文件夹和虚拟环境中创建所有必需的文件(如果您使用的是 Anaconda,则需要为 vscode 配置setting.json指向 Conda 环境)。

  1. 完成您的 init.py 文件。然后启动该函数:

    函数开始

该函数将在本地主机上部署并为您提供一个链接。

  1. 如果您想将其部署在云中,请安装 Azure Function 扩展,您可以选择登录并选择您的订阅。完成此操作后,您可以将函数部署在 Azure 中创建的任何 Function App 下。

I'm replying to this as no one else did, and someone might stumble upon this thread looking for an answer.

To run your function locally from VS Code:

  1. Initiate the function in your local environment, run the command in terminal inside vscode:

    func init

This will create all the necessary files in your folder and a virtual environments (if you're using Anaconda, you need to configure the setting.json for vscode that points to the Conda environments).

  1. Finish your init.py file. Then start the function with:

    func start

The function will deploy at localhost and give you a link.

  1. If you want to deploy it in the cloud, install Azure Function extension, you'll have option to login and select your subscription. After this is done, you can deploy the functions under any Function App that was created in Azure.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文