random_time_series.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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.models.slice import Slice
  21. from superset.utils import core as utils
  22. from .helpers import config, get_example_data, get_slice_json, merge_slice, TBL
  23. def load_random_time_series_data(
  24. only_metadata: bool = False, force: bool = False
  25. ) -> None:
  26. """Loading random time series data from a zip file in the repo"""
  27. tbl_name = "random_time_series"
  28. database = utils.get_example_database()
  29. table_exists = database.has_table_by_name(tbl_name)
  30. if not only_metadata and (not table_exists or force):
  31. data = get_example_data("random_time_series.json.gz")
  32. pdf = pd.read_json(data)
  33. pdf.ds = pd.to_datetime(pdf.ds, unit="s")
  34. pdf.to_sql(
  35. tbl_name,
  36. database.get_sqla_engine(),
  37. if_exists="replace",
  38. chunksize=500,
  39. dtype={"ds": DateTime},
  40. index=False,
  41. )
  42. print("Done loading table!")
  43. print("-" * 80)
  44. print(f"Creating table [{tbl_name}] reference")
  45. obj = db.session.query(TBL).filter_by(table_name=tbl_name).first()
  46. if not obj:
  47. obj = TBL(table_name=tbl_name)
  48. obj.main_dttm_col = "ds"
  49. obj.database = database
  50. db.session.merge(obj)
  51. db.session.commit()
  52. obj.fetch_metadata()
  53. tbl = obj
  54. slice_data = {
  55. "granularity_sqla": "day",
  56. "row_limit": config["ROW_LIMIT"],
  57. "since": "2019-01-01",
  58. "until": "2019-02-01",
  59. "metric": "count",
  60. "viz_type": "cal_heatmap",
  61. "domain_granularity": "month",
  62. "subdomain_granularity": "day",
  63. }
  64. print("Creating a slice")
  65. slc = Slice(
  66. slice_name="Calendar Heatmap",
  67. viz_type="cal_heatmap",
  68. datasource_type="table",
  69. datasource_id=tbl.id,
  70. params=get_slice_json(slice_data),
  71. )
  72. merge_slice(slc)