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

[dashboard] Refactor API using SIP-35 #9315

Merged
merged 11 commits into from
Mar 20, 2020
2 changes: 1 addition & 1 deletion superset/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def init_views(self) -> None:
)
from superset.views.chart.api import ChartRestApi
from superset.views.chart.views import SliceModelView, SliceAsync
from superset.views.dashboard.api import DashboardRestApi
from superset.dashboards.api import DashboardRestApi
from superset.views.dashboard.views import (
DashboardModelView,
Dashboard,
Expand Down
6 changes: 6 additions & 0 deletions superset/commands/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# under the License.
from typing import List, Optional

from flask_babel import lazy_gettext as _
from marshmallow import ValidationError


Expand Down Expand Up @@ -69,3 +70,8 @@ class DeleteFailedError(CommandException):

class ForbiddenError(CommandException):
message = "Action is forbidden"


class OwnersNotFoundValidationError(ValidationError):
def __init__(self):
super().__init__(_("Owners are invalid"), field_names=["owners"])
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,14 @@

from flask_appbuilder.security.sqla.models import User

from superset.datasets.commands.exceptions import OwnersNotFoundValidationError
from superset.datasets.dao import DatasetDAO
from superset.commands.exceptions import OwnersNotFoundValidationError
from superset.extensions import security_manager


def populate_owners(user: User, owners_ids: Optional[List[int]] = None) -> List[User]:
"""
Helper function for commands, will fetch all users from owners id's
Can raise ValidationError

:param user: The current user
:param owners_ids: A List of owners by id's
"""
Expand All @@ -36,7 +35,7 @@ def populate_owners(user: User, owners_ids: Optional[List[int]] = None) -> List[
if user.id not in owners_ids:
owners.append(user)
for owner_id in owners_ids:
owner = DatasetDAO.get_owner_by_id(owner_id)
owner = security_manager.get_user_by_id(owner_id)
if not owner:
raise OwnersNotFoundValidationError()
owners.append(owner)
Expand Down
16 changes: 16 additions & 0 deletions superset/dao/__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.
71 changes: 71 additions & 0 deletions superset/dao/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# 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 Dict, Optional

from flask_appbuilder.models.sqla import Model
from sqlalchemy.exc import SQLAlchemyError

from superset.commands.exceptions import (
CreateFailedError,
DeleteFailedError,
UpdateFailedError,
)
from superset.extensions import db


def generic_create(model_cls: Model, properties: Dict, commit=True) -> Optional[Model]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't pass in the class here. Instead, the caller will have created whatever instance he wants and then should pass it in. You can then combine your create / update into a single upsert method. Also, you can call this something like def upsert(model, commit=True)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can do that and end up with less code. Yet I tend to think it's more readable this way (and easier to reason), DAO create methods call generic_create, update methods call generic_update, also Exceptions follow the same pattern.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we shouldn't combine create and update. If I'm trying to update a pre-existing record and someone deletes it in the interim from another process, I want that to error. Upsert would hide the race condition.

"""
Generic for creating models
"""
model = model_cls()
for key, value in properties.items():
setattr(model, key, value)
try:
db.session.add(model)
if commit:
db.session.commit()
except SQLAlchemyError as e: # pragma: no cover
db.session.rollback()
raise CreateFailedError(exception=e)
return model


def generic_update(model: Model, properties: Dict, commit=True) -> Optional[Model]:
"""
Generic update a model
"""
for key, value in properties.items():
setattr(model, key, value)
try:
db.session.merge(model)
if commit:
db.session.commit()
except SQLAlchemyError as e: # pragma: no cover
db.session.rollback()
raise UpdateFailedError(exception=e)
return model


def generic_delete(model: Model, commit=True):
try:
db.session.delete(model)
if commit:
db.session.commit()
except SQLAlchemyError as e: # pragma: no cover
db.session.rollback()
raise DeleteFailedError(exception=e)
return model
16 changes: 16 additions & 0 deletions superset/dashboards/__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.
Loading