You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by GitBox <gi...@apache.org> on 2019/12/11 10:15:06 UTC

[GitHub] [incubator-superset] dpgaspar commented on a change in pull request #8694: [dashboard] feat: REST API

dpgaspar commented on a change in pull request #8694: [dashboard] feat: REST API
URL: https://github.com/apache/incubator-superset/pull/8694#discussion_r356509549
 
 

 ##########
 File path: superset/views/dashboard/api.py
 ##########
 @@ -0,0 +1,281 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import re
+
+from flask import current_app, g, request
+from flask_appbuilder import ModelRestApi
+from flask_appbuilder.api import expose, protect, safe
+from flask_appbuilder.models.sqla.interface import SQLAInterface
+from marshmallow import fields, post_load, pre_load, ValidationError
+from marshmallow.validate import Length
+from sqlalchemy.exc import SQLAlchemyError
+
+import superset.models.core as models
+from superset import appbuilder
+from superset.exceptions import SupersetException
+from superset.utils import core as utils
+from superset.views.base import BaseSupersetSchema
+
+from .mixin import DashboardMixin
+
+
+def validate_json(value):
+    try:
+        utils.validate_json(value)
+    except SupersetException:
+        raise ValidationError("JSON not valid")
+
+
+def validate_slug_uniqueness(value):
+    # slug is not required but must be unique
+    if value:
+        item = (
+            current_app.appbuilder.get_session.query(models.Dashboard.id)
+            .filter_by(slug=value)
+            .one_or_none()
+        )
+        if item:
+            raise ValidationError("Must be unique")
+
+
+def validate_owners(value):
+    owner = (
+        current_app.appbuilder.get_session.query(
+            current_app.appbuilder.sm.user_model.id
+        )
+        .filter_by(id=value)
+        .one_or_none()
+    )
+    if not owner:
+        raise ValidationError(f"User {value} does not exist")
+
+
+class BaseDashboardSchema(BaseSupersetSchema):
+    @staticmethod
+    def set_owners(instance, owners):
+        owner_objs = list()
+        if g.user.id not in owners:
+            owners.append(g.user.id)
+        for owner_id in owners:
+            user = current_app.appbuilder.get_session.query(
+                current_app.appbuilder.sm.user_model
+            ).get(owner_id)
+            owner_objs.append(user)
+        instance.owners = owner_objs
+
+    @pre_load
+    def pre_load(self, data):  # pylint: disable=no-self-use
+        data["slug"] = data.get("slug")
+        data["owners"] = data.get("owners", [])
+        if data["slug"]:
+            data["slug"] = data["slug"].strip()
+            data["slug"] = data["slug"].replace(" ", "-")
+            data["slug"] = re.sub(r"[^\w\-]+", "", data["slug"])
+
+
+class DashboardPostSchema(BaseDashboardSchema):
+    dashboard_title = fields.String(allow_none=True, validate=Length(0, 500))
+    slug = fields.String(
+        allow_none=True, validate=[Length(1, 255), validate_slug_uniqueness]
+    )
+    owners = fields.List(fields.Integer(validate=validate_owners))
+    position_json = fields.String(validate=validate_json)
+    css = fields.String()
+    json_metadata = fields.String(validate=validate_json)
+    published = fields.Boolean()
+
+    @post_load
+    def make_object(self, data):  # pylint: disable=no-self-use
+        instance = models.Dashboard()
+        self.set_owners(instance, data["owners"])
+        for field in data:
+            if field == "owners":
+                self.set_owners(instance, data["owners"])
+            else:
+                setattr(instance, field, data.get(field))
+        return instance
+
+
+class DashboardPutSchema(BaseDashboardSchema):
+    dashboard_title = fields.String(allow_none=True, validate=Length(0, 500))
+    slug = fields.String(allow_none=True, validate=Length(0, 255))
+    owners = fields.List(fields.Integer(validate=validate_owners))
+    position_json = fields.String(validate=validate_json)
+    css = fields.String()
+    json_metadata = fields.String(validate=validate_json)
+    published = fields.Boolean()
+
+    @post_load
+    def make_object(self, data):  # pylint: disable=no-self-use
+        if "owners" not in data and g.user not in self.instance.owners:
+            self.instance.owners.append(g.user)
+        for field in data:
+            if field == "owners":
+                self.set_owners(self.instance, data["owners"])
+            else:
+                setattr(self.instance, field, data.get(field))
+        for slc in self.instance.slices:
+            slc.owners = list(set(self.instance.owners) | set(slc.owners))
+        return self.instance
+
+
+class DashboardRestApi(DashboardMixin, ModelRestApi):
+    datamodel = SQLAInterface(models.Dashboard)
+
+    resource_name = "dashboard"
+    allow_browser_login = True
+
+    class_permission_name = "DashboardRestApi"
 
 Review comment:
   Not really, but note that we currently have a bunch of view class permissions, `DashboardModelViewAsync`, `DashboardModelView`, `DashboardAddView` and `Dashboard`. I would say that, eventually they will all disappear. 
   
   `Dashboard` is a good choice for the long run, yet we still need to run `superset init`. 
   Another choice would be to tie it to `DashboardModelView` and we would have a direct map to the current create permissions.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org