简体   繁体   中英

Store a gzip file in a storage account with Azure function

I'm trying to store in my storage account a gzip file following a dump of my database, with Azure function and python code.

I tried to follow this documentation

I have an error on this line (outputBlob.set(f)):

import datetime
import logging
import os
import gzip
import subprocess

import azure.functions as func

def main(mytimer: func.TimerRequest,outputBlob: func.Out[bytes]) -> None:

    utc_timestamp = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()

    # Get the setting named 'myAppSetting'
    my_app_setting_value = os.environ["LIVE_CONNECTIONSTRING"]
    logging.info(f'My app setting value:{my_app_setting_value}')

    cmd = "pg_dump " + my_app_setting_value + " | sed 's/LOCALE/LC_COLLATE/'"
    logging.info(f'commande : {cmd}')

    with gzip.open('backup.gz', "wb") as f:

        popen = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, universal_newlines=True)

        for stdout_line in iter(popen.stdout.readline, ""):
            f.write(stdout_line.encode("utf-8"))

        popen.stdout.close()
        popen.wait()

    logging.info(type(f))
    logging.info(f)
    logging.info(outputBlob)
    ---> outputBlob.set(f) <---

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

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

Logs:

2022-12-01T22:46:53Z   [Information]   <class 'gzip.GzipFile'>
2022-12-01T22:46:53Z   [Information]   <gzip on 0x7fca9c5868b0>
2022-12-01T22:46:53Z   [Information]   <azure_functions_worker.bindings.out.Out object at 0x7fca9c586160>
2022-12-01T22:46:53Z   [Error]   Executed 'Functions.TimerTriggerDump' (Failed, Id=7c1664ad-5ab2-431a-9818-4f66473b3ceb, Duration=199ms)

Has anyone ever encountered this case?

I tried to change the parameter type of my outputblob

Check if the below steps helps to fix the issue:

  • The error you are seeing is occurring on the line outputBlob.set(f) , where outputBlob is a binding of type func.Out[bytes] and f is a file object returned by gzip.open .

  • To fix this error, you will need to read the contents of the gzip file and pass them as a bytes object to outputBlob.set . You can do this by calling f.read() on the file object and passing the resulting bytes object to outputBlob.set .

Here is an example of how you can modify your code to fix the error:

    with gzip.open('backup.gz', "rb") as f:
     # Read the contents of the gzip file as bytes
      file_contents = f.read()
       # Set the contents of the gzip file to the output binding
      outputBlob.set(file_contents)

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