Azure-Samples / Azure-Samples/visionary-lab

Code fails if AZURE_STORAGE_CONNECTION_STRING is defined

Open
#1 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
97
Forks
64
Avg merge
1d 17h
Merged PRs (30d)
13

Description

I got a few errors after defining AZURE_STORAGE_CONNECTION_STRING, the code tries to generate the SAS key with the ENVs provided, even if AZURE_STORAGE_CONNECTION_STRING is defined.

I made this basic workaround on the following files:

backend/api/core/__init__.py

try:
if settings.AZURE_STORAGE_CONNECTION_STRING:
# Use the SAS token from the connection string
image_sas_token = settings.AZURE_STORAGE_CONNECTION_STRING.split("SharedAccessSignature=")[1]
logger.info("Using SAS token from AZURE_STORAGE_CONNECTION_STRING for image container.")
else:
# Fallback: Generate a container-specific SAS token if account key is available
if not settings.AZURE_STORAGE_ACCOUNT_KEY:
raise ValueError("AZURE_STORAGE_ACCOUNT_KEY is required when AZURE_STORAGE_CONNECTION_STRING is not provided.")
image_sas_token = generate_container_sas(
account_name=settings.AZURE_STORAGE_ACCOUNT_NAME,
container_name=settings.AZURE_BLOB_IMAGE_CONTAINER,
account_key=settings.AZURE_STORAGE_ACCOUNT_KEY,
permission=ContainerSasPermissions(read=True, list=True),
expiry=datetime.now(timezone.utc) + timedelta(hours=4),
)
logger.info("Generated container-specific SAS token for image container.")
except Exception as e:
logger.error(f"Failed to define image_sas_token: {str(e)}")
# Fallback to None or raise an error, depending on your needs
image_sas_token = None

backend/api/endpoints/gallery.ts

...

@router.get("/sas-tokens", response_model=SasTokenResponse)
async def get_sas_tokens():
"""Return SAS token for frontend direct access to blob storage"""
try:
# Construct container URL
container_url = f"{settings.AZURE_BLOB_SERVICE_URL}{settings.AZURE_BLOB_IMAGE_CONTAINER}"

# Set a conservative expiry (e.g., 1 hour) for frontend usage
expiry_time = datetime.now(timezone.utc) + timedelta(hours=1)

# Check if AZURE_STORAGE_CONNECTION_STRING is defined
if settings.AZURE_STORAGE_CONNECTION_STRING:
# Extract SAS token from connection string
image_sas_token = settings.AZURE_STORAGE_CONNECTION_STRING.split("SharedAccessSignature=")[1]
else:
# Fallback to generating a SAS token with account key
if not settings.AZURE_STORAGE_ACCOUNT_KEY:
raise ValueError("Either AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT_KEY must be provided")
image_sas_token = generate_container_sas(
account_name=settings.AZURE_STORAGE_ACCOUNT_NAME,
container_name=settings.AZURE_BLOB_IMAGE_CONTAINER,
account_key=settings.AZURE_STORAGE_ACCOUNT_KEY,
permission=ContainerSasPermissions(read=True), # Read-only for frontend
expiry=expiry_time,
)

return {
"success": True,
"message": "SAS token retrieved successfully",
"image_sas_token": image_sas_token,
"image_container_url": container_url,
"expiry": expiry_time.isoformat()
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to retrieve SAS token: {str(e)}")

frontend/next.config.ts (here, the config fails because the blob URL defined is at backend level).

Kudos to the team for providing these interfaces, also GPT-image1 works great!

Hope it helps.

Edu.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.