首页 > 解决方案 > Python 中 Azure Functions 上的文件操作

问题描述

我有一个运行 Python 代码的 Azure Function 应用程序。这个 Python 应用使用 JSON 文件访问 BigQuery,读取一些数据,然后从中创建一个 JSON 文件。

我尝试了所有有意义的方法,但 Azure 生态系统异常复杂。

from google.cloud import bigquery
from google.oauth2 import service_account
import pandas as pd
import json
import datetime
import logging
import azure.functions as func


def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

    if mytimer.past_due:
        logging.info('The timer is past due!')

    logging.info('Python timer trigger function ran at %s', utc_timestamp)

    # RE01
    key_path = "bigquery-key.json"

    credentials = service_account.Credentials.from_service_account_file(
        key_path,
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )

    client = bigquery.Client(
        credentials=credentials,
        project=credentials.project_id,
    )

    project_id = "test-database"

    sql = """
    SELECT *
    FROM test.dummy_table
    """
    # Create a dataframe and save first 10 rows to a list
    df = client.query(sql).to_dataframe()
    top_ten = df["column1"][1:10].to_list()

    with open('top_10.json', 'w') as json_file:
        json.dump(top_ten, json_file)

有人能告诉我我的 JSON 文件保存在哪里吗?我似乎无法运行此功能。

标签: pythonazureazure-functions

解决方案


一旦函数执行结束(或者当您的实例因不活动而被逐出时),您在函数内部写入本地磁盘的任何内容都会丢失。如果要存储结果文件,则需要在外部存储系统上进行。这正是(输出)绑定的用途。例如 Azure Blob 存储。有关如何在 python 中使用它的示例,请参见此处:

https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob#output---python-example


推荐阅读