简体   繁体   中英

Azure Function Python - No such file or directory when using file.open

I'm using an Azure Function to retrieve a.xlsx file using an HTTP GET request and upload it to blob storage. In the code, I'm using file.open to write the content to a temporary file and then uploading the file to blob storage.

This is the code I'm using.

fileData = open(pathlib.Path(__file__).parent / fileString, 'w+').write(r.content)

but it fails, and the Application Insights response says:

Exception: FileNotFoundError: [Errno 2] No such file or directory:

The following two paths work well in singleton mode on my side:

1,

import logging
from pathlib import Path

import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
    path = str(Path.home()) + "/test.txt"
    fileData = open(path, 'w+').write("testsomething")
    return func.HttpResponse(
            "create file with no problem."+path,
            status_code=200
        )

2,

import logging
import tempfile
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    path = tempfile.gettempdir() + "/test.txt"
    fileData = open(path, 'w+').write("testsomething")
    return func.HttpResponse(
            "create file with no problem."+path,
            status_code=200
    )

This article says, Files written to the temporary directory aren't guaranteed to persist across invocations (Maybe your problem is similar, but not sure).

Your code seems to have nothing to do with multi-instance, but any way, this is not the recommended method. As user3732793 says in his answer, you can directly send data to storage blob without temporary file. Just retrieve a.xlsx file using an HTTP GET request and send data to blob storage by blob output binding or blob storage sdk .

I used tempfile to solve the issue.

    fp = tempfile.NamedTemporaryFile()
    fp.write(r.content)

And then, when uploading to blob storage, I had to open the file and read the bytes.

    with open(fp.name, 'rb') as data:
      logging.info(data)
      if azureConnector.exists():
        logging.info('connector exists')
        return
      azureConnector.upload_blob(data, overwrite=True)

This is uploading the file to Azure blob storage now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM