2424
2525from packaging .version import Version
2626from functools import reduce
27-
27+ from google . cloud import storage
2828from geoalchemy2 .shape import to_shape
2929
3030from shared .database_gen .sqlacodegen_models import Gtfsfeed , Gtfsrealtimefeed
@@ -68,7 +68,13 @@ def get_dataframe(self) -> pd:
6868
6969
7070@functions_framework .http
71- def export_csv (request = None ):
71+ def export_and_upload_csv (request = None ):
72+ response = export_csv ()
73+ upload_file_to_storage (csv_file_path , "001_csv/sources_v2.csv" )
74+ return response
75+
76+
77+ def export_csv ():
7278 """
7379 HTTP Function entry point Reads the DB and outputs a csv file with feeds data.
7480 This function requires the following environment variables to be set:
@@ -78,7 +84,7 @@ def export_csv(request=None):
7884 """
7985 data_collector = collect_data ()
8086 data_collector .write_csv_to_file (csv_file_path )
81- return f"Export of database feeds to CSV file { csv_file_path } ."
87+ return f"Exported { len ( data_collector . rows ) } feeds to CSV file { csv_file_path } ."
8288
8389
8490def collect_data () -> DataCollector :
@@ -87,6 +93,7 @@ def collect_data() -> DataCollector:
8793 :return: A filled DataCollector
8894 """
8995 db = Database (database_url = os .getenv ("FEEDS_DATABASE_URL" ))
96+ print (f"Using database { db .database_url } " )
9097 try :
9198 with db .start_db_session () as session :
9299 gtfs_feeds_query = get_all_gtfs_feeds_query (
@@ -116,7 +123,7 @@ def collect_data() -> DataCollector:
116123 for key , value in data .items ():
117124 data_collector .add_data (key , value )
118125 data_collector .finalize_row ()
119- print (f"Procewssed { len (gtfs_feeds )} GTFS feeds." )
126+ print (f"Processed { len (gtfs_feeds )} GTFS feeds." )
120127
121128 for feed in gtfs_rt_feeds :
122129 # print(f"Processing rt feed {feed.stable_id}")
@@ -312,11 +319,27 @@ def get_gtfs_rt_feed_csv_data(feed: Gtfsrealtimefeed):
312319 return data
313320
314321
322+ def upload_file_to_storage (source_file_path , target_path ):
323+ """
324+ Uploads a file to the GCP bucket
325+ """
326+ bucket_name = os .getenv ("DATASETS_BUCKET_NAME" )
327+ bucket = storage .Client ().get_bucket (bucket_name )
328+ blob = bucket .blob (target_path )
329+ with open (source_file_path , "rb" ) as file :
330+ blob .upload_from_file (file )
331+ blob .make_public ()
332+ return blob
333+
334+
315335if __name__ == "__main__" :
316336 parser = argparse .ArgumentParser (description = "Export DB feed contents to csv." )
317337 parser .add_argument (
318338 "--outpath" , help = "Path to the output csv file. Default is ./output.csv"
319339 )
340+ os .environ [
341+ "FEEDS_DATABASE_URL"
342+ ] = "postgresql://postgres:postgres@localhost:54320/MobilityDatabaseTest"
320343 args = parser .parse_args ()
321344 csv_file_path = args .outpath if args .outpath else csv_default_file_path
322345 export_csv ()
0 commit comments