api.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. from typing import Dict, List, Optional
  18. from flask import current_app
  19. from flask_appbuilder.models.sqla.interface import SQLAInterface
  20. from marshmallow import fields, post_load, validates_schema, ValidationError
  21. from marshmallow.validate import Length
  22. from sqlalchemy.orm.exc import NoResultFound
  23. from superset.connectors.connector_registry import ConnectorRegistry
  24. from superset.exceptions import SupersetException
  25. from superset.models.dashboard import Dashboard
  26. from superset.models.slice import Slice
  27. from superset.utils import core as utils
  28. from superset.views.base_api import BaseOwnedModelRestApi
  29. from superset.views.base_schemas import BaseOwnedSchema, validate_owner
  30. from superset.views.chart.mixin import SliceMixin
  31. def validate_json(value):
  32. try:
  33. utils.validate_json(value)
  34. except SupersetException:
  35. raise ValidationError("JSON not valid")
  36. def validate_dashboard(value):
  37. try:
  38. (current_app.appbuilder.get_session.query(Dashboard).filter_by(id=value).one())
  39. except NoResultFound:
  40. raise ValidationError(f"Dashboard {value} does not exist")
  41. def validate_update_datasource(data: Dict):
  42. if not ("datasource_type" in data and "datasource_id" in data):
  43. return
  44. datasource_type = data["datasource_type"]
  45. datasource_id = data["datasource_id"]
  46. try:
  47. datasource = ConnectorRegistry.get_datasource(
  48. datasource_type, datasource_id, current_app.appbuilder.get_session
  49. )
  50. except (NoResultFound, KeyError):
  51. raise ValidationError(
  52. f"Datasource [{datasource_type}].{datasource_id} does not exist"
  53. )
  54. data["datasource_name"] = datasource.name
  55. def populate_dashboards(instance: Slice, dashboards: List[int]):
  56. """
  57. Mutates a Slice with the dashboards SQLA Models
  58. """
  59. dashboards_tmp = []
  60. for dashboard_id in dashboards:
  61. dashboards_tmp.append(
  62. current_app.appbuilder.get_session.query(Dashboard)
  63. .filter_by(id=dashboard_id)
  64. .one()
  65. )
  66. instance.dashboards = dashboards_tmp
  67. class ChartPostSchema(BaseOwnedSchema):
  68. __class_model__ = Slice
  69. slice_name = fields.String(required=True, validate=Length(1, 250))
  70. description = fields.String(allow_none=True)
  71. viz_type = fields.String(allow_none=True, validate=Length(0, 250))
  72. owners = fields.List(fields.Integer(validate=validate_owner))
  73. params = fields.String(allow_none=True, validate=validate_json)
  74. cache_timeout = fields.Integer(allow_none=True)
  75. datasource_id = fields.Integer(required=True)
  76. datasource_type = fields.String(required=True)
  77. datasource_name = fields.String(allow_none=True)
  78. dashboards = fields.List(fields.Integer(validate=validate_dashboard))
  79. @validates_schema
  80. def validate_schema(self, data: Dict): # pylint: disable=no-self-use
  81. validate_update_datasource(data)
  82. @post_load
  83. def make_object(self, data: Dict, discard: Optional[List[str]] = None) -> Slice:
  84. instance = super().make_object(data, discard=["dashboards"])
  85. populate_dashboards(instance, data.get("dashboards", []))
  86. return instance
  87. class ChartPutSchema(BaseOwnedSchema):
  88. instance: Slice
  89. slice_name = fields.String(allow_none=True, validate=Length(0, 250))
  90. description = fields.String(allow_none=True)
  91. viz_type = fields.String(allow_none=True, validate=Length(0, 250))
  92. owners = fields.List(fields.Integer(validate=validate_owner))
  93. params = fields.String(allow_none=True)
  94. cache_timeout = fields.Integer(allow_none=True)
  95. datasource_id = fields.Integer(allow_none=True)
  96. datasource_type = fields.String(allow_none=True)
  97. dashboards = fields.List(fields.Integer(validate=validate_dashboard))
  98. @validates_schema
  99. def validate_schema(self, data: Dict): # pylint: disable=no-self-use
  100. validate_update_datasource(data)
  101. @post_load
  102. def make_object(self, data: Dict, discard: Optional[List[str]] = None) -> Slice:
  103. self.instance = super().make_object(data, ["dashboards"])
  104. if "dashboards" in data:
  105. populate_dashboards(self.instance, data["dashboards"])
  106. return self.instance
  107. class ChartRestApi(SliceMixin, BaseOwnedModelRestApi):
  108. datamodel = SQLAInterface(Slice)
  109. resource_name = "chart"
  110. allow_browser_login = True
  111. class_permission_name = "SliceModelView"
  112. show_columns = [
  113. "slice_name",
  114. "description",
  115. "owners.id",
  116. "owners.username",
  117. "dashboards.id",
  118. "dashboards.dashboard_title",
  119. "viz_type",
  120. "params",
  121. "cache_timeout",
  122. ]
  123. list_columns = [
  124. "id",
  125. "slice_name",
  126. "url",
  127. "description",
  128. "changed_by.username",
  129. "changed_by_name",
  130. "changed_by_url",
  131. "changed_on",
  132. "datasource_name_text",
  133. "datasource_link",
  134. "viz_type",
  135. "params",
  136. "cache_timeout",
  137. ]
  138. # Will just affect _info endpoint
  139. edit_columns = ["slice_name"]
  140. add_columns = edit_columns
  141. # exclude_route_methods = ("info",)
  142. add_model_schema = ChartPostSchema()
  143. edit_model_schema = ChartPutSchema()
  144. order_rel_fields = {
  145. "slices": ("slice_name", "asc"),
  146. "owners": ("first_name", "asc"),
  147. }
  148. filter_rel_fields_field = {"owners": "first_name", "dashboards": "dashboard_title"}