flights.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. import pandas as pd
  18. from sqlalchemy import DateTime
  19. from superset import db
  20. from superset.utils import core as utils
  21. from .helpers import get_example_data, TBL
  22. def load_flights(only_metadata: bool = False, force: bool = False) -> None:
  23. """Loading random time series data from a zip file in the repo"""
  24. tbl_name = "flights"
  25. database = utils.get_example_database()
  26. table_exists = database.has_table_by_name(tbl_name)
  27. if not only_metadata and (not table_exists or force):
  28. data = get_example_data("flight_data.csv.gz", make_bytes=True)
  29. pdf = pd.read_csv(data, encoding="latin-1")
  30. # Loading airports info to join and get lat/long
  31. airports_bytes = get_example_data("airports.csv.gz", make_bytes=True)
  32. airports = pd.read_csv(airports_bytes, encoding="latin-1")
  33. airports = airports.set_index("IATA_CODE")
  34. pdf["ds"] = (
  35. pdf.YEAR.map(str) + "-0" + pdf.MONTH.map(str) + "-0" + pdf.DAY.map(str)
  36. )
  37. pdf.ds = pd.to_datetime(pdf.ds)
  38. del pdf["YEAR"]
  39. del pdf["MONTH"]
  40. del pdf["DAY"]
  41. pdf = pdf.join(airports, on="ORIGIN_AIRPORT", rsuffix="_ORIG")
  42. pdf = pdf.join(airports, on="DESTINATION_AIRPORT", rsuffix="_DEST")
  43. pdf.to_sql(
  44. tbl_name,
  45. database.get_sqla_engine(),
  46. if_exists="replace",
  47. chunksize=500,
  48. dtype={"ds": DateTime},
  49. index=False,
  50. )
  51. tbl = db.session.query(TBL).filter_by(table_name=tbl_name).first()
  52. if not tbl:
  53. tbl = TBL(table_name=tbl_name)
  54. tbl.description = "Random set of flights in the US"
  55. tbl.database = database
  56. db.session.merge(tbl)
  57. db.session.commit()
  58. tbl.fetch_metadata()
  59. print("Done loading table!")