[英]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.我正在使用 Azure Function 使用 HTTP GET 请求检索 a.xlsx 文件并将其上传到 blob 存储。 In the code, I'm using file.open to write the content to a temporary file and then uploading the file to blob storage.
在代码中,我使用 file.open 将内容写入临时文件,然后将文件上传到 blob 存储。
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:但它失败了,Application Insights 响应说:
Exception: FileNotFoundError: [Errno 2] No such file or directory:
The following two paths work well in singleton mode on my side:以下两条路径在我这边的 singleton 模式下运行良好:
1, 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, 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.
正如 user3732793 在他的回答中所说,您可以直接将数据发送到存储 blob 而无需临时文件。 Just retrieve a.xlsx file using an HTTP GET request and send data to blob storage by blob output binding or blob storage sdk .
只需使用 HTTP GET 请求检索 a.xlsx 文件,然后通过blob output 绑定或blob 存储 sdk将数据发送到 blob 存储。
I used tempfile to solve the issue.我使用 tempfile 来解决这个问题。
fp = tempfile.NamedTemporaryFile()
fp.write(r.content)
And then, when uploading to blob storage, I had to open the file and read the bytes.然后,当上传到 blob 存储时,我必须打开文件并读取字节。
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.现在正在将文件上传到 Azure blob 存储。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.