Skip to content

Instantly share code, notes, and snippets.

@AndrewBarba
Created May 11, 2023 21:20
Show Gist options
  • Save AndrewBarba/b21305cab238ed892d8c58c0ed270ab6 to your computer and use it in GitHub Desktop.
Save AndrewBarba/b21305cab238ed892d8c58c0ed270ab6 to your computer and use it in GitHub Desktop.
Vercel EdgeConfig for Python Runtime
import os
import json
from urllib.parse import urlparse
edge_config_id_prefix = "ecfg_"
class EdgeConfigError(Exception):
pass
class EdgeConfig:
def __init__(self, input):
self.id = self.parse_config_id(input)
try:
with open(f"/opt/edge-config/{self.id}.json", "r") as file:
self.config = json.load(file)
except FileNotFoundError:
raise EdgeConfigError("embeddedConfigNotFound")
@property
def digest(self):
return self.config["digest"]
@property
def items(self):
return self.config["items"]
def get(self, key):
return self.items.get(key)
def has(self, key):
return key in self.items
def __getitem__(self, key):
return self.get(key)
@staticmethod
def parse_config_id(input):
if input.startswith(edge_config_id_prefix):
return input
if input.startswith("https://"):
url = urlparse(input)
path_components = url.path.split("/")
for component in path_components:
if component.startswith(edge_config_id_prefix):
return component
raise EdgeConfigError("invalidConnection")
value = os.environ.get(input)
if value:
return EdgeConfig.parse_config_id(value)
raise EdgeConfigError("invalidConnection")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment