[text] V

Viewer

  1. import requests
  2.  
  3. # Function to download the file
  4. def download_file(url, filename, headers):
  5.     with open(filename, 'wb') as f:
  6.         response = requests.get(url, headers=headers)
  7.         f.write(response.content)
  8.  
  9. # URL to the endpoint that provides details of the file
  10. details_url = "https://toolkit.tesco.com/partner/reports/api/v1/generated-reports-v2?pageNumber=0&pageSize=18"
  11.  
  12. # Assuming you have a username and password for authentication
  13. username = "your_username"
  14. password = "your_password"
  15.  
  16. # Data to be passed in the POST request body
  17. data = {
  18.     "username": username,
  19.     "password": password
  20. }
  21.  
  22. # Headers for the POST request
  23. headers = {
  24.     "Content-Type": "application/json",
  25.     "Accept": "application/json"
  26. }
  27.  
  28. # Making a POST request to authenticate and get the report details
  29. response = requests.post(details_url, json=data, headers=headers)
  30.  
  31. # Check if the authentication was successful (status code 200)
  32. if response.status_code == 200:
  33.     # Obtain the session cookie from the response headers
  34.     session_cookie = response.cookies.get('session_cookie_name')
  35.  
  36.     # Include the session cookie in the headers of subsequent requests
  37.     headers_with_cookie = {
  38.         **headers,
  39.         'Cookie': f'session_cookie_name={session_cookie}'
  40.     }
  41.  
  42.     # Assuming the response contains the 'reports' key
  43.     if 'reports' in response.json():
  44.         # Extracting the URLs of the files from the response JSON
  45.         report_details = response.json()
  46.  
  47.         # Find the report with the latest createdOn timestamp
  48.         latest_report = max(report_details['reports'], key=lambda x: x['createdOn'])
  49.  
  50.         # Extract the URL and filename of the CSV file with the latest createdOn timestamp
  51.         csv_url = latest_report['reportName']
  52.         csv_filename = latest_report['reportData']['reportName']
  53.  
  54.         # Download the CSV file
  55.         download_file(csv_url, f"/dbfs/path/to/save/{csv_filename}", headers_with_cookie)
  56.  
  57.         print("Latest file saved to DBFS successfully!")
  58.     else:
  59.         print("Error: No 'reports' key found in the response.")
  60. else:
  61.     print(f"Authentication failed with status code: {response.status_code}")

Editor

You can edit this paste and save as new: