randomisedbackend2 / env_test.py
akiko19191's picture
Upload folder using huggingface_hub
85354fe verified
raw
history blame
8.64 kB
VERCEL_TOKEN = "azm0JC5lyPwah6qPGhbN5DL5"
PROJECT_ID = "prj_4RemrVT2H255cTcdXxkLqFJUD6Dq"
# Vercel Team ID is optional. Only include it if your project is under a team.
TEAM_ID = False
PROJECT_NAME = "matax-express"
# update_vercel_env.py
import os
import json
import requests
import sys
# --- Configuration ---
# --- Data to be Set ---
# This data will be converted to a JSON string and sent to Vercel.
# You can modify this data directly in the script before running it.
WHY_US_FEATURES_DATA = [
{ "icon": "EnergySavingsLeafIcon", "title": "Peak Freshness", "description": "Guaranteed farm-to-door freshness in every order." },
{ "icon": "YardIcon", "title": "Local Sourcing", "description": "Partnering with local farms to support the community." },
{ "icon": "CategoryIcon", "title": "Wide Selection", "description": "A diverse range of produce, dairy, and pantry staples." },
{ "icon": "LocalShippingIcon", "title": "Reliable Delivery", "description": "On-time, refrigerated delivery you can count on." },
]
FAQS_DATA = [
{ "question": "What regions do you deliver to?", "answer": "We currently deliver to all major metropolitan areas within the state. We are actively expanding our delivery network, so please check back for updates on new regions." },
{ "question": "How do I place an order?", "answer": "Once you register for an account and are approved, you can log in to our customer portal. From there, you can browse our product catalog, select quantities, and schedule your delivery." },
{ "question": "What are your quality standards?", "answer": "We pride ourselves on sourcing only the freshest, Grade A produce from trusted local and national farms. Every item is inspected for quality and freshness before it leaves our facility." },
{ "question": "Is there a minimum order requirement?", "answer": "Yes, there is a minimum order value for delivery. This amount varies by region. You can find the specific minimum for your area in your customer portal after logging in." },
]
def get_existing_env_var(key, headers, params):
"""Fetches all environment variables and returns the one matching the key."""
api_url = f"https://api.vercel.com/v9/projects/{PROJECT_ID}/env"
try:
response = requests.get(api_url, headers=headers, params=params)
response.raise_for_status()
all_vars = response.json().get('envs', [])
for var in all_vars:
if var['key'] == key:
print(f"Found existing variable '{key}' with ID: {var['id']}")
return var
return None
except requests.exceptions.RequestException as err:
print(f"❌ Error fetching environment variables: {err}")
return None
def delete_env_var(var_id, headers, params):
"""Deletes an environment variable by its ID."""
print(f"Attempting to delete variable with ID: {var_id}")
api_url = f"https://api.vercel.com/v9/projects/{PROJECT_ID}/env/{var_id}"
try:
response = requests.delete(api_url, headers=headers, params=params)
response.raise_for_status()
print(f"✅ Successfully deleted variable.")
return True
except requests.exceptions.RequestException as err:
print(f"❌ Error deleting environment variable: {err}")
return False
def create_env_var(key, value_obj, target_environments, headers, params):
"""Creates a new environment variable."""
print(f"Creating new environment variable '{key}'...")
api_url = f"https://api.vercel.com/v9/projects/{PROJECT_ID}/env"
payload = {
"key": key,
"value": json.dumps(value_obj),
"type": "encrypted",
"target": target_environments,
}
try:
response = requests.post(api_url, headers=headers, json=payload, params=params)
response.raise_for_status()
print(f"✅ Successfully created environment variable '{key}'.")
return True
except requests.exceptions.RequestException as err:
print(f"❌ HTTP Error creating '{key}': {err}")
if err.response:
print(f" Response Body: {err.response.text}")
return False
def set_vercel_env_var(key, value_obj, target_environments):
"""
Main function to set an environment variable.
It deletes the variable if it exists, then creates it.
"""
print(f"--- Processing environment variable: {key} ---")
headers = {"Authorization": f"Bearer {VERCEL_TOKEN}"}
params = {"teamId": TEAM_ID} if TEAM_ID else {}
existing_var = get_existing_env_var(key, headers, params)
if existing_var:
if not delete_env_var(existing_var['id'], headers, params):
print(f"Aborting update for '{key}' due to deletion failure.")
return False
return create_env_var(key, value_obj, target_environments, headers, params)
def get_project_git_info(headers, params):
"""Fetches project details to get the linked Git repository ID and type."""
print("Fetching project details to find Git repo ID...")
api_url = f"https://api.vercel.com/v9/projects/{PROJECT_ID}"
try:
response = requests.get(api_url, headers=headers, params=params)
response.raise_for_status()
project_data = response.json()
link_info = project_data.get('link')
if not link_info or 'repoId' not in link_info or 'type' not in link_info:
print("❌ Error: Could not find linked Git repository information (repoId).")
print(" Please ensure your Vercel project is connected to a Git repository.")
return None, None
repo_id = link_info['repoId']
git_type = link_info['type']
print(f"✅ Found Git repo ID: {repo_id} (type: {git_type})")
return repo_id, git_type
except requests.exceptions.RequestException as err:
print(f"❌ Error fetching project details: {err}")
return None, None
def trigger_vercel_deployment():
"""Triggers a new Vercel deployment for the project."""
print("\n--- Triggering new Vercel deployment ---")
headers = {"Authorization": f"Bearer {VERCEL_TOKEN}", "Content-Type": "application/json"}
params = {"teamId": TEAM_ID} if TEAM_ID else {}
# Dynamically get the Git repo ID and type required for the deployment payload
repo_id, git_type = get_project_git_info(headers, params)
if not repo_id:
print("Aborting deployment trigger due to missing Git info.")
return
api_url = "https://api.vercel.com/v13/deployments"
# The payload now correctly includes the repoId
payload = {
"name": PROJECT_NAME,
"target": "production",
"gitSource": {
"type": git_type,
"repoId": repo_id,
"ref": "main" # Change 'main' to your default branch if it's different
}
}
try:
response = requests.post(api_url, headers=headers, json=payload, params=params)
response.raise_for_status()
deployment_url = response.json().get('url')
print(f"✅ Successfully triggered new deployment.")
print(f" Inspect deployment: https://{deployment_url}")
except requests.exceptions.HTTPError as err:
print(f"❌ HTTP Error triggering deployment: {err}")
print(f" Response Body: {err.response.text}")
except Exception as err:
print(f"❌ An unexpected error occurred while triggering deployment: {err}")
def main():
"""Main function to run the script."""
print("Starting Vercel environment variable update process...")
if not all([VERCEL_TOKEN, PROJECT_ID, PROJECT_NAME]):
print("❌ Error: Missing required environment variables.")
print(" Please set VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_PROJECT_NAME.")
sys.exit(1)
target_environments = ["production", "preview", "development"]
success1 = set_vercel_env_var(
key="REACT_APP_WHY_US_FEATURES",
value_obj=WHY_US_FEATURES_DATA,
target_environments=target_environments
)
print("\n")
success2 = set_vercel_env_var(
key="REACT_APP_FAQS",
value_obj=FAQS_DATA,
target_environments=target_environments
)
if success1 and success2:
trigger_vercel_deployment()
else:
print("\nSkipping deployment due to errors in updating environment variables.")
print("\nScript finished.")
if __name__ == "__main__":
main()