Update readme

Add userinfo endpoint and asset backup script.

Fix s3 and add new DB fields

Add pyproject file

Cleanup
This commit is contained in:
Shaun Kruger
2026-11-22 15:13:14 -07:00
parent 323746c992
commit 9b08f5b858
47 changed files with 1029 additions and 234 deletions
+212
View File
@@ -0,0 +1,212 @@
#!/usr/bin/env python3
"""
Upload an asset to the Private Studio web API using boto3.
This script demonstrates how to use boto3 to upload files to the Private Studio
S3-compatible storage API.
Usage:
python upload_asset.py \\
--base-url http://localhost:8000 \\
--api-key <your-api-key> \\
--file /path/to/file.mp4 \\
--key assets/my-video.mp4
"""
import argparse
import sys
from pathlib import Path
import requests
from typing import Optional
try:
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
except ImportError:
print("Error: boto3 is required. Install it with: pip install boto3", file=sys.stderr)
sys.exit(1)
def upload_asset(
base_url: str,
api_key: str,
file_path: str,
key: str,
user_name: int = 1,
) -> dict:
"""
Upload an asset to the Private Studio API.
Args:
base_url: Base URL of the Private Studio API (e.g., http://localhost:8000)
api_key: API key for authentication
file_path: Path to the file to upload
key: S3 key/path for the file (e.g., assets/my-file.mp4)
user_name: User ID (defaults to 1)
Returns:
Response from the API containing object_id, key, size, and filename
Raises:
FileNotFoundError: If the file doesn't exist
ClientError: If the API returns an error
"""
# Enable boto3 debug logging to see request/response details
# import logging
# boto3.set_stream_logger('botocore', logging.DEBUG)
# logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
userinfo = requests.get(f"{base_url}/api/userinfo", headers={"Authorization": f"Bearer {api_key}"})
userinfo.raise_for_status()
user_data = userinfo.json()
s3creds = requests.post(f"{base_url}/api/s3keys", headers={"Authorization": f"Bearer {api_key}"})
s3creds.raise_for_status()
s3_creds = s3creds.json()
access_key = s3_creds.get("access_key")
secret_key = s3_creds.get("secret_key")
print(f"\nS3 Credentials obtained:")
print(f" Access Key: {access_key}")
print(f" Secret Key: {secret_key[:10]}...{secret_key[-10:]}") # Masked for security
print(f" Bucket: {user_data.get('bucket')}")
file_path_obj = Path(file_path)
if not file_path_obj.exists():
raise FileNotFoundError(f"File not found: {file_path}")
# Configure boto3 client for S3-compatible API
print(f"\nConfiguring boto3 client:")
print(f" Endpoint URL: {base_url}/s3")
print(f" Region: us-east-1")
print(f" Signature Version: s3v4")
print(f" Addressing Style: path")
s3_client = boto3.client(
"s3",
endpoint_url=f"{base_url}/s3",
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
region_name="us-east-1",
config=Config(
signature_version="s3v4",
s3={"addressing_style": "path"},
),
)
try:
# Upload the file
file_size = file_path_obj.stat().st_size
bucket = user_data['bucket']
# print(f"\n{'='*60}")
# print(f"Starting upload:")
# print(f" File: {file_path}")
# print(f" Size: {file_size} bytes ({file_size / (1024*1024):.2f} MB)")
# print(f" Bucket: {bucket}")
# print(f" Key: {key}")
# print(f" Endpoint: {base_url}/s3/{bucket}/{key}")
# print(f"{'='*60}\n")
with open(file_path, "rb") as f:
print(f"Opened file: {file_path}")
response = s3_client.put_object(
Bucket=bucket,
Key=key,
Body=f,
)
print("Upload successful!")
print(f"Response: {response}")
return {
"status": "success",
"key": key,
"size": file_size,
"etag": response.get("ETag"),
}
except ClientError as e:
error_code = e.response.get("Error", {}).get("Code")
error_message = e.response.get("Error", {}).get("Message")
# status_code = e.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
# headers = e.response.get("ResponseMetadata", {}).get("HTTPHeaders", {})
#
# print(f"\n{'='*60}", file=sys.stderr)
print(f"Error uploading file: {error_code} - {error_message}", file=sys.stderr)
# print(f"HTTP Status Code: {status_code}", file=sys.stderr)
# print(f"Response Headers: {headers}", file=sys.stderr)
# print(f"Full Response: {e.response}", file=sys.stderr)
# print(f"{'='*60}\n", file=sys.stderr)
raise
except Exception as e:
print(f"\n{'='*60}", file=sys.stderr)
print(f"Unexpected error: {e}", file=sys.stderr)
print(f"Error type: {type(e).__name__}", file=sys.stderr)
import traceback
traceback.print_exc(file=sys.stderr)
print(f"{'='*60}\n", file=sys.stderr)
raise
def main():
"""Parse arguments and execute upload."""
parser = argparse.ArgumentParser(
description="Upload an asset to the Private Studio web API",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python upload_asset.py --base-url http://localhost:8000 --api-key sk_test_123abc --file video.mp4 --key assets/video.mp4
python upload_asset.py --base-url https://api.example.com --api-key sk_prod_456def --file image.jpg --key media/image.jpg --user-id 2
""",
)
parser.add_argument(
"--base-url",
required=True,
help="Base URL of the Private Studio API (e.g., http://localhost:8000)",
)
parser.add_argument(
"--api-key",
required=True,
help="API key for authentication",
)
parser.add_argument(
"--file",
required=True,
help="Path to the file to upload",
)
parser.add_argument(
"--key",
required=True,
help="S3 key/path for the file (e.g., assets/my-file.mp4)",
)
parser.add_argument(
"--user-id",
type=int,
default=1,
help="User ID (defaults to 1)",
)
args = parser.parse_args()
try:
result = upload_asset(
base_url=args.base_url,
api_key=args.api_key,
file_path=args.file,
key=args.key,
user_name=args.user_id,
)
print(f"\nUpload completed: {result}")
return 0
except Exception as e:
print(f"Upload failed: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())