File size: 4,550 Bytes
5f20dc6 4aa6fdf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | """
Storage adapter — transparent local-disk vs. GCS-backed file storage.
Local mode (default): reads/writes files in CWD.
Cloud mode (GCS_BUCKET env var set): reads/writes blobs in that bucket.
Usage:
from modules.storage import load_bytes, save_bytes, load_json, save_json
data = load_json("users.json", default={})
save_json("users.json", data)
"""
import os
import json
_BUCKET_NAME = os.environ.get("GCS_BUCKET", "").strip()
_client = None
_bucket = None
def _get_bucket():
global _client, _bucket
if _bucket is not None:
return _bucket
if not _BUCKET_NAME:
return None
from google.cloud import storage as gcs
_client = gcs.Client()
_bucket = _client.bucket(_BUCKET_NAME)
return _bucket
def _is_gcs():
return bool(_BUCKET_NAME)
def _normalize(name):
"""Strip leading ./ so GCS blob names match uploaded filenames."""
if isinstance(name, str) and name.startswith("./"):
return name[2:]
return name
def load_bytes(name):
"""Return bytes of file `name`, or None if missing."""
name = _normalize(name)
if _is_gcs():
try:
blob = _get_bucket().blob(name)
if not blob.exists():
return None
return blob.download_as_bytes()
except Exception as e:
print("STORAGE read failed for " + name + ": " + str(e))
return None
else:
if not os.path.isfile(name):
return None
try:
with open(name, "rb") as f:
return f.read()
except Exception as e:
print("STORAGE read failed for " + name + ": " + str(e))
return None
def save_bytes(name, data):
"""Write bytes `data` to file `name`. Returns True on success."""
name = _normalize(name)
if isinstance(data, str):
data = data.encode("utf-8")
if _is_gcs():
try:
blob = _get_bucket().blob(name)
blob.upload_from_string(data)
return True
except Exception as e:
print("STORAGE write failed for " + name + ": " + str(e))
return False
else:
try:
with open(name, "wb") as f:
f.write(data)
return True
except Exception as e:
print("STORAGE write failed for " + name + ": " + str(e))
return False
def load_json(name, default=None):
raw = load_bytes(name)
if raw is None:
return default
try:
return json.loads(raw.decode("utf-8"))
except Exception as e:
print("STORAGE json parse failed for " + name + ": " + str(e))
return default
def save_json(name, data):
try:
return save_bytes(name, json.dumps(data, indent=2).encode("utf-8"))
except Exception as e:
print("STORAGE json dump failed for " + name + ": " + str(e))
return False
def load_text(name, default=""):
raw = load_bytes(name)
if raw is None:
return default
try:
return raw.decode("utf-8")
except Exception:
return default
def save_text(name, text):
return save_bytes(name, text.encode("utf-8"))
def append_text(name, line):
"""Append a line to a text file (reads, appends, writes back)."""
existing = load_text(name, "")
return save_text(name, existing + line)
def delete_bytes(name):
"""Delete file/blob `name`. Returns True on success."""
name = _normalize(name)
if _is_gcs():
try:
_get_bucket().blob(name).delete()
return True
except Exception as e:
print("STORAGE delete failed for " + name + ": " + str(e))
return False
else:
try:
if os.path.isfile(name):
os.remove(name)
return True
except Exception as e:
print("STORAGE delete failed for " + name + ": " + str(e))
return False
def list_prefix(prefix):
"""Return all object names under `prefix` (GCS blobs or local files)."""
prefix = _normalize(prefix)
if _is_gcs():
try:
return [b.name for b in _get_bucket().list_blobs(prefix=prefix)]
except Exception as e:
print("STORAGE list failed for " + prefix + ": " + str(e))
return []
try:
out = []
for root, _dirs, files in os.walk(prefix):
for f in files:
out.append(os.path.join(root, f).replace(os.sep, "/"))
return out
except Exception:
return []
|