random_time_series.py 2.6 KB

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