-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract_and_push_gcs.py
46 lines (36 loc) · 1.54 KB
/
extract_and_push_gcs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import requests
import csv
from google.cloud import storage
url = 'https://cricbuzz-cricket.p.rapidapi.com/stats/v1/rankings/batsmen'
headers = {
"x-rapidapi-key": "xxx",
"x-rapidapi-host": "xxx"
}
params = {
'formatType': 'odi'
}
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
data = response.json().get('rank', []) # Extracting the 'rank' data
csv_filename = 'batsmen_rankings.csv'
if data:
field_names = ['rank', 'name', 'country'] # Specify required field names
# Write data to CSV file with only specified field names
with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=field_names)
# writer.writeheader()
for entry in data:
writer.writerow({field: entry.get(field) for field in field_names})
print(f"Data fetched successfully and written to '{csv_filename}'")
# Upload the CSV file to GCS
bucket_name = 'bkt-cricket-game-ranking-data'
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
destination_blob_name = f'{csv_filename}' # The path to store in GCS
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(csv_filename)
print(f"File {csv_filename} uploaded to GCS bucket {bucket_name} as {destination_blob_name}")
else:
print("No data available from the API.")
else:
print("Failed to fetch data:", response.status_code)