sf_population_polygons.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 json
  18. import pandas as pd
  19. from sqlalchemy import BigInteger, Float, Text
  20. from superset import db
  21. from superset.utils import core as utils
  22. from .helpers import get_example_data, TBL
  23. def load_sf_population_polygons(
  24. only_metadata: bool = False, force: bool = False
  25. ) -> None:
  26. tbl_name = "sf_population_polygons"
  27. database = utils.get_example_database()
  28. table_exists = database.has_table_by_name(tbl_name)
  29. if not only_metadata and (not table_exists or force):
  30. data = get_example_data("sf_population.json.gz")
  31. df = pd.read_json(data)
  32. df["contour"] = df.contour.map(json.dumps)
  33. df.to_sql(
  34. tbl_name,
  35. database.get_sqla_engine(),
  36. if_exists="replace",
  37. chunksize=500,
  38. dtype={
  39. "zipcode": BigInteger,
  40. "population": BigInteger,
  41. "contour": Text,
  42. "area": Float,
  43. },
  44. index=False,
  45. )
  46. print("Creating table {} reference".format(tbl_name))
  47. tbl = db.session.query(TBL).filter_by(table_name=tbl_name).first()
  48. if not tbl:
  49. tbl = TBL(table_name=tbl_name)
  50. tbl.description = "Population density of San Francisco"
  51. tbl.database = database
  52. db.session.merge(tbl)
  53. db.session.commit()
  54. tbl.fetch_metadata()