Spaces:
Running
Running
Create Data_Fetching_&_Rendering.py
Browse files- Data_Fetching_&_Rendering.py +71 -0
Data_Fetching_&_Rendering.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
def fetch_org_urn(comm_client_id, comm_token_dict):
|
2 |
+
"""
|
3 |
+
Fetches the user's administrated organization URN and name using the Marketing token.
|
4 |
+
Expects comm_token_dict to be the full token dictionary.
|
5 |
+
Raises ValueError on failure.
|
6 |
+
"""
|
7 |
+
print("--- Fetching Organization URN ---")
|
8 |
+
if not comm_token_dict or 'access_token' not in comm_token_dict:
|
9 |
+
print("ERROR: Invalid or missing Marketing token dictionary for fetching Org URN.")
|
10 |
+
raise ValueError("Marketing token is missing or invalid.")
|
11 |
+
|
12 |
+
ln_mkt = create_session(comm_client_id, token=comm_token_dict)
|
13 |
+
|
14 |
+
# Fetch organizational roles directly using the V2 API
|
15 |
+
url = (
|
16 |
+
f"{API_V2_BASE}/organizationalEntityAcls"
|
17 |
+
"?q=roleAssignee&role=ADMINISTRATOR&state=APPROVED" # Find orgs where user is ADMIN
|
18 |
+
"&projection=(elements*(*,organizationalTarget~(id,localizedName)))" # Get URN and name
|
19 |
+
)
|
20 |
+
print(f"Fetching Org URN details from: {url}")
|
21 |
+
try:
|
22 |
+
r = ln_mkt.get(url)
|
23 |
+
r.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
|
24 |
+
except requests.exceptions.RequestException as e:
|
25 |
+
print(f"ERROR: Failed to fetch organizationalEntityAcls with Marketing token.")
|
26 |
+
# Provide specific feedback based on status code if possible
|
27 |
+
status = e.response.status_code if e.response is not None else "N/A"
|
28 |
+
details = ""
|
29 |
+
if e.response is not None:
|
30 |
+
try:
|
31 |
+
details = f" Details: {e.response.json()}"
|
32 |
+
except json.JSONDecodeError:
|
33 |
+
details = f" Response: {e.response.text[:200]}..." # Show partial text
|
34 |
+
raise ValueError(f"Failed to fetch Organization details (Status: {status}). Check Marketing App permissions (r_organization_admin) and ensure the user is an admin of an org page.{details}") from e
|
35 |
+
|
36 |
+
data = r.json()
|
37 |
+
print(f"Org URN Response Data: {json.dumps(data, indent=2)}")
|
38 |
+
elements = data.get('elements')
|
39 |
+
|
40 |
+
if not elements:
|
41 |
+
print("WARNING: No organizations found where the user is an ADMINISTRATOR.")
|
42 |
+
# Try fetching with MEMBER role as a fallback? Might require different scope.
|
43 |
+
# For now, stick to ADMINISTRATOR as per scope.
|
44 |
+
raise ValueError("No organizations found for this user where they have the ADMINISTRATOR role. Ensure the Marketing App has 'r_organization_admin' permission and the user is an admin of an organization page.")
|
45 |
+
|
46 |
+
# Assuming the first organization found is the target
|
47 |
+
# In a real app, you might let the user choose if they admin multiple orgs.
|
48 |
+
org_element = elements[0]
|
49 |
+
|
50 |
+
# Extract Full URN ('organizationalTarget' field contains the URN string)
|
51 |
+
org_urn_full = org_element.get('organizationalTarget')
|
52 |
+
if not org_urn_full or not isinstance(org_urn_full, str) or not org_urn_full.startswith("urn:li:organization:"):
|
53 |
+
print(f"ERROR: Could not extract valid Organization URN ('organizationalTarget') from API response element: {org_element}")
|
54 |
+
raise ValueError("Could not extract a valid Organization URN from the API response.")
|
55 |
+
|
56 |
+
# Extract Name (from the projected 'organizationalTarget~' field)
|
57 |
+
org_name = None
|
58 |
+
# The key might be exactly 'organizationalTarget~' or something similar depending on projection syntax variations
|
59 |
+
org_target_details_key = next((k for k in org_element if k.endswith('organizationalTarget~')), None)
|
60 |
+
|
61 |
+
if org_target_details_key and isinstance(org_element.get(org_target_details_key), dict):
|
62 |
+
org_name = org_element[org_target_details_key].get('localizedName')
|
63 |
+
|
64 |
+
if not org_name:
|
65 |
+
# Fallback name using the ID part of the URN
|
66 |
+
org_id = org_urn_full.split(':')[-1]
|
67 |
+
org_name = f"Organization ({org_id})"
|
68 |
+
print(f"WARN: Could not find localizedName, using fallback: {org_name}")
|
69 |
+
|
70 |
+
print(f"Found Org: {org_name} ({org_urn_full})")
|
71 |
+
return org_urn_full, org_name
|