Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: CRUD REST API for CSS Templates #11114

Merged
merged 4 commits into from
Oct 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions superset/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ def init_views(self) -> None:
TableColumnInlineView,
TableModelView,
)
from superset.css_templates.api import CssTemplateRestApi
from superset.dashboards.api import DashboardRestApi
from superset.databases.api import DatabaseRestApi
from superset.datasets.api import DatasetRestApi
Expand Down Expand Up @@ -197,6 +198,7 @@ def init_views(self) -> None:
#
appbuilder.add_api(CacheRestApi)
appbuilder.add_api(ChartRestApi)
appbuilder.add_api(CssTemplateRestApi)
appbuilder.add_api(DashboardRestApi)
appbuilder.add_api(DatabaseRestApi)
appbuilder.add_api(DatasetRestApi)
Expand Down
16 changes: 16 additions & 0 deletions superset/css_templates/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 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.
133 changes: 133 additions & 0 deletions superset/css_templates/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# 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 logging
from typing import Any

from flask import g, Response
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import ngettext

from superset.constants import RouteMethod
from superset.css_templates.commands.bulk_delete import BulkDeleteCssTemplateCommand
from superset.css_templates.commands.exceptions import (
CssTemplateBulkDeleteFailedError,
CssTemplateNotFoundError,
)
from superset.css_templates.filters import CssTemplateAllTextFilter
from superset.css_templates.schemas import (
get_delete_ids_schema,
openapi_spec_methods_override,
)
from superset.models.core import CssTemplate
from superset.views.base_api import BaseSupersetModelRestApi, statsd_metrics

logger = logging.getLogger(__name__)


class CssTemplateRestApi(BaseSupersetModelRestApi):
datamodel = SQLAInterface(CssTemplate)

include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
"bulk_delete", # not using RouteMethod since locally defined
}
class_permission_name = "CssTemplateModelView"
resource_name = "css_template"
allow_browser_login = True

show_columns = [
"created_by.first_name",
"created_by.id",
"created_by.last_name",
"css",
"id",
"template_name",
]
list_columns = [
"changed_on_delta_humanized",
"created_on",
"created_by.first_name",
"created_by.id",
"created_by.last_name",
"css",
"id",
"template_name",
]
add_columns = ["css", "template_name"]
edit_columns = add_columns
order_columns = ["template_name"]

search_filters = {"template_name": [CssTemplateAllTextFilter]}

apispec_parameter_schemas = {
"get_delete_ids_schema": get_delete_ids_schema,
}
openapi_spec_tag = "CSS Templates"
openapi_spec_methods = openapi_spec_methods_override

@expose("/", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
@rison(get_delete_ids_schema)
def bulk_delete(self, **kwargs: Any) -> Response:
"""Delete bulk CSS Templates
---
delete:
description: >-
Deletes multiple css templates in a bulk operation.
parameters:
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_delete_ids_schema'
responses:
200:
description: CSS templates bulk delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
item_ids = kwargs["rison"]
try:
BulkDeleteCssTemplateCommand(g.user, item_ids).run()
return self.response(
200,
message=ngettext(
"Deleted %(num)d css template",
"Deleted %(num)d css templates",
num=len(item_ids),
),
)
except CssTemplateNotFoundError:
return self.response_404()
except CssTemplateBulkDeleteFailedError as ex:
return self.response_422(message=str(ex))
16 changes: 16 additions & 0 deletions superset/css_templates/commands/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 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.
53 changes: 53 additions & 0 deletions superset/css_templates/commands/bulk_delete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# 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 logging
from typing import List, Optional

from flask_appbuilder.security.sqla.models import User

from superset.commands.base import BaseCommand
from superset.css_templates.commands.exceptions import (
CssTemplateBulkDeleteFailedError,
CssTemplateNotFoundError,
)
from superset.css_templates.dao import CssTemplateDAO
from superset.dao.exceptions import DAODeleteFailedError
from superset.models.core import CssTemplate

logger = logging.getLogger(__name__)


class BulkDeleteCssTemplateCommand(BaseCommand):
def __init__(self, user: User, model_ids: List[int]):
self._actor = user
self._model_ids = model_ids
self._models: Optional[List[CssTemplate]] = None

def run(self) -> None:
self.validate()
try:
CssTemplateDAO.bulk_delete(self._models)
return None
except DAODeleteFailedError as ex:
logger.exception(ex.exception)
raise CssTemplateBulkDeleteFailedError()

def validate(self) -> None:
# Validate/populate model exists
self._models = CssTemplateDAO.find_by_ids(self._model_ids)
if not self._models or len(self._models) != len(self._model_ids):
raise CssTemplateNotFoundError()
27 changes: 27 additions & 0 deletions superset/css_templates/commands/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# 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.
from flask_babel import lazy_gettext as _

from superset.commands.exceptions import CommandException, DeleteFailedError


class CssTemplateBulkDeleteFailedError(DeleteFailedError):
message = _("CSS template could not be deleted.")


class CssTemplateNotFoundError(CommandException):
message = _("CSS template not found.")
45 changes: 45 additions & 0 deletions superset/css_templates/dao.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# 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 logging
from typing import List, Optional

from sqlalchemy.exc import SQLAlchemyError

from superset.dao.base import BaseDAO
from superset.dao.exceptions import DAODeleteFailedError
from superset.extensions import db
from superset.models.core import CssTemplate

logger = logging.getLogger(__name__)


class CssTemplateDAO(BaseDAO):
model_cls = CssTemplate

@staticmethod
def bulk_delete(models: Optional[List[CssTemplate]], commit: bool = True) -> None:
item_ids = [model.id for model in models] if models else []
try:
db.session.query(CssTemplate).filter(CssTemplate.id.in_(item_ids)).delete(
synchronize_session="fetch"
)
if commit:
db.session.commit()
except SQLAlchemyError:
if commit:
db.session.rollback()
raise DAODeleteFailedError()
40 changes: 40 additions & 0 deletions superset/css_templates/filters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# 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.
from typing import Any

from flask_babel import lazy_gettext as _
from sqlalchemy import or_
from sqlalchemy.orm.query import Query

from superset.models.core import CssTemplate
from superset.views.base import BaseFilter


class CssTemplateAllTextFilter(BaseFilter): # pylint: disable=too-few-public-methods
name = _("All Text")
arg_name = "css_template_all_text"

def apply(self, query: Query, value: Any) -> Query:
if not value:
return query
ilike_value = f"%{value}%"
return query.filter(
or_(
CssTemplate.template_name.ilike(ilike_value),
CssTemplate.css.ilike(ilike_value),
)
)
33 changes: 33 additions & 0 deletions superset/css_templates/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# 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.

openapi_spec_methods_override = {
"get": {"get": {"description": "Get a CSS template"}},
"get_list": {
"get": {
"description": "Get a list of CSS templates, use Rison or JSON "
"query parameters for filtering, sorting,"
" pagination and for selecting specific"
" columns and metadata.",
}
},
"post": {"post": {"description": "Create a CSS template"}},
"put": {"put": {"description": "Update a CSS template"}},
"delete": {"delete": {"description": "Delete CSS template"}},
}

get_delete_ids_schema = {"type": "array", "items": {"type": "integer"}}
Loading