Check if file exists in blob storage using python azure functions

Viewed 533

I want to check if a file exists in azure blob storage using python azure functions. We can use the python library BlobServiceClient, but it needs a connection with the blob. I'm looking for a methode without using connection keys because I'm already connected to my azure account via vs code.

1 Answers

Even though your environment is logged into azure account, you need access key or connection string to connect to your storage account. After reproducing from our end here is how we could able to check if the blob is present or not in azure storage.

import logging

import azure.functions as func
from azure.storage.blob import BlockBlobService


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    
    ContainerName="<YOUR_CONTAINER_NAME>";
    AccountName="<YOUR_ACCOUNT_NAME>";
    AccountKey="<ACCESS_KEY>";

    block_blob_service = BlockBlobService(account_name=AccountName, account_key=AccountKey)
    
    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
           return func.HttpResponse(f"Enter the blob you are searching for")
        else:
            name = req_body.get('name')

    if block_blob_service.exists(container_name=ContainerName, blob_name=name):
        return func.HttpResponse(f"{name}, Is already Present in container")
    else:
        return func.HttpResponse(
             "{name}, Is not Present in container",
             status_code=200
        )

RESULT:

enter image description here

enter image description here

enter image description here

Related