utkarsh134 commited on
Commit
80eb39b
·
verified ·
1 Parent(s): deac221

Upload reach_upload.py

Browse files
Files changed (1) hide show
  1. app/utils/reach_upload.py +99 -0
app/utils/reach_upload.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ from typing import Dict
4
+ import requests
5
+ from io import BytesIO
6
+ import logging
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ def upload_to_reach(
11
+ image_data: bytes,
12
+ brand_name: str,
13
+ image_format: str,
14
+ index: int,
15
+ max_retries: int = 3,
16
+ retry_delay: float = 2.0
17
+ ) -> Dict[str, str]:
18
+ """
19
+ Upload image to Reach Mobile Platform storage with retry logic.
20
+
21
+ Args:
22
+ image_data (bytes): Raw image bytes
23
+ brand_name (str): Brand name for reference
24
+ image_format (str): Image format/extension
25
+ index (int): Index to differentiate multiple uploads
26
+ max_retries (int): Maximum number of retry attempts
27
+ retry_delay (float): Delay between retries in seconds
28
+
29
+ Returns:
30
+ Dict[str, str]: Metadata dictionary containing URL from Reach API
31
+
32
+ Raises:
33
+ requests.RequestException: If upload fails after all retries
34
+ EnvironmentError: If required environment variables are missing
35
+ """
36
+ url = os.getenv('REACH_UPLOAD_ENDPOINT')
37
+ auth_key = os.getenv('REACH_AUTH_KEY')
38
+
39
+ if not url:
40
+ raise EnvironmentError("REACH_UPLOAD_ENDPOINT is not defined in environment variables.")
41
+ if not auth_key:
42
+ raise EnvironmentError("REACH_AUTH_KEY is not defined in environment variables.")
43
+
44
+ last_exception = None
45
+
46
+ for attempt in range(max_retries):
47
+ try:
48
+ # Create file-like object from bytes
49
+ file_obj = BytesIO(image_data)
50
+
51
+ # Create filename
52
+ filename = f"{brand_name.replace(' ', '')}_{index}.{image_format.lower()}"
53
+
54
+ # Prepare the file for upload
55
+ files = {
56
+ 'file': (filename, file_obj, f'image/{image_format.lower()}')
57
+ }
58
+
59
+ headers = {
60
+ 'accept': 'application/json',
61
+ 'accept-language': 'en-US,en;q=0.9',
62
+ 'authorization': auth_key,
63
+ 'sec-ch-ua-platform': 'Windows',
64
+ 'x-partner-tenant-id': 'REACH@skyhawk'
65
+ }
66
+
67
+ logger.info(f"Attempting upload of {filename} (attempt {attempt + 1}/{max_retries})")
68
+
69
+ response = requests.post(
70
+ f"{url}?fileType=LOGO",
71
+ files=files,
72
+ headers=headers,
73
+ timeout=30 # Add timeout parameter
74
+ )
75
+
76
+ if response.status_code != 200:
77
+ raise requests.HTTPError(f"Upload failed: {response.status_code} {response.text}")
78
+
79
+ response_data = response.json()
80
+
81
+ if response_data.get('status') != 'SUCCESS':
82
+ raise requests.HTTPError(f"Upload failed: {response_data}")
83
+
84
+ logger.info(f"Successfully uploaded {filename}")
85
+ return {
86
+ "url": response_data.get('data')
87
+ }
88
+
89
+ except (requests.RequestException, requests.Timeout) as e:
90
+ last_exception = e
91
+ logger.warning(f"Upload attempt {attempt + 1} failed: {str(e)}")
92
+ if attempt < max_retries - 1:
93
+ time.sleep(retry_delay * (attempt + 1)) # Exponential backoff
94
+ continue
95
+ break
96
+
97
+ error_msg = f"❌ Error uploading to Reach platform after {max_retries} attempts: {str(last_exception)}"
98
+ logger.error(error_msg)
99
+ raise requests.RequestException(error_msg)