Skip to content
Draft
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
49 changes: 49 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,52 @@
## 1.5.0 (unreleased)
---------------------

- Add `flask_jsonapi.ViewSet`, `DetailView` and `ListView`: a layered way to declare a resource. A ViewSet declares
`allowed_actions`, `guards`, `object_permissions`, `middlewares` and one `data_service`, which run in a fixed
order: allowed actions and guards before the request body is parsed, then object permissions, middlewares and
the data service. `flask_jsonapi.guards` and `flask_jsonapi.middlewares` (`Middleware`, `build_pipeline`,
`CheckRequiredListFilters`) are new.
- Add `flask_jsonapi.permissions.ObjectPermissions` and `CheckObjectPermission` for the `object_permissions` slot.
`CheckObjectPermission` plugs an existing `PermissionChecker` into a ViewSet. Its `apply_permission_filter`
returns filters that restrict a list to the objects the client may list, and may raise `PermissionException`
(403) when the client's own filters ask for objects it may not list. `check_list_permission` runs on the listed
objects as a safety net: if it drops any, a warning is logged and the total is left out of the response.
- Add `flask_jsonapi.data_services`: HTTP-agnostic data services that raise their own exceptions
(`ResourceNotFound`, `PermissionDenied`, `InvalidData`, `Conflict`, ...), which a view translates to JSON:API
errors. Data services, middlewares and object permissions name their methods after the actions: `create`,
`read`, `list`, `update` and `destroy`. It includes a new `SqlAlchemyModelRepository` and
`LegacyRepositoryAdapter`, which lets a new ViewSet use a legacy repository (`PATCH` then answers 200 with a body
instead of 204).
- Add `flask_jsonapi.data_services.ListResult(items, total)`, which `list` returns: the items, and the number of
objects matching the filters before pagination, or `None`. A data service sets the total when the request asks
for a page. `ListView` calls `list` once per request and builds the pagination links from the total. Without a
total, `last` is `null` and `next` is present only for a full page. `SqlAlchemyModelRepository.list` counts and
slices one filtered query. `LegacyRepositoryAdapter.list` calls `get_count` only when the request asks for a page.
- Add `flask_jsonapi.resources.ListResourceBase`, the base class of `ResourceList` and `ListView`, and
`SizeNumberPagination.get_links_without_total`. A custom pagination class used by `ListView` must implement
`get_links` and `get_links_without_total`.
- Add `Actions.list`. `Actions.read_many` stays as an alias with the same value.
- Deprecate `ResourceRepositoryViewSet`, `ResourceRepositoryDetailView`, `ResourceRepositoryListView`,
`ProtectedViewSet`, `ProtectedDetailView`, `ProtectedListView`, the `AllowedActions*` mixins, `ResourceRepository`
and the legacy `SqlAlchemyModelRepository` (documented only, there are no runtime warnings). See the migration guide.
- Every error from a view is now a JSON:API error document, for legacy views too. Unexpected exceptions are logged and
rendered as a generic 500 without internal details, and `flask.abort()` keeps its status, title and headers (for
example `WWW-Authenticate`). An `abort()` carrying an explicit response returns that response unchanged.
- Flask app error handlers (`@app.errorhandler`) no longer run for exceptions raised inside flask-jsonapi views:
those become JSON:API errors, unexpected ones a generic 500. In testing mode such exceptions no longer reach the
test client either.
- Errors while dumping a GET response (`AttributeError`, `KeyError`, `ValueError` from a schema) are a generic 500
without details instead of a 500 whose `detail` is the exception message.
- `HEAD` is served by the `GET` handler instead of failing with a 500.
- `PATCH` with a wrong resource `type` answers 409 Conflict instead of 500.
- JSON:API exception classes accept keyword arguments (`status`, `title`, `detail`, `source`). The old positional
forms still work. New exceptions: `Unauthorized`, `UnprocessableEntity` and `ServiceUnavailable`.
- `str(exc)` of a JSON:API exception is now its `detail`. Without a `source` argument, `ForbiddenError(...).source`
and `MethodNotAllowed(...).source` are now `None` instead of `{}`; `to_dict()` is unaffected.
- Empty `detail` and `source` are omitted from error objects. Tests that compare a whole error body to one with
`'source': {}` need updating.


## 1.4.2 (unreleased)
---------------------

Expand Down
28 changes: 21 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ from sqlalchemy.ext.declarative import declarative_base
from marshmallow_jsonapi import Schema, fields

import flask_jsonapi
from flask_jsonapi.resource_repositories import sqlalchemy_repositories
from flask_jsonapi.data_services import sqlalchemy_repositories

db_engine = sqlalchemy.create_engine('sqlite:///')
session = scoped_session(sessionmaker(bind=db_engine))
Expand All @@ -51,7 +51,6 @@ Base.metadata.create_all(db_engine)

class ArticleRepository(sqlalchemy_repositories.SqlAlchemyModelRepository):
model = Article
instance_name = 'articles'
session = session

class ArticleSchema(Schema):
Expand All @@ -60,18 +59,33 @@ class ArticleSchema(Schema):

class Meta:
type_ = 'articles'
strict = True

class ArticleRepositoryViewSet(flask_jsonapi.resource_repository_views.ResourceRepositoryViewSet):
schema = ArticleSchema
repository = ArticleRepository()
class ArticleViewSet(flask_jsonapi.ViewSet):
schema_class = ArticleSchema
data_service = ArticleRepository()
allowed_actions = {
flask_jsonapi.Actions.create,
flask_jsonapi.Actions.read,
flask_jsonapi.Actions.list,
flask_jsonapi.Actions.update,
flask_jsonapi.Actions.destroy,
}

app = flask.Flask(__name__)
api = flask_jsonapi.Api(app)
api.repository(ArticleRepositoryViewSet(), 'articles', '/articles/')
api.repository(ArticleViewSet(), 'articles', '/articles/')
app.run(host='127.0.0.1', port=5000)
```

`allowed_actions` lists what the endpoint serves; a ViewSet that does not declare it serves nothing. A ViewSet can
also declare `guards` (request checks such as authentication), `object_permissions` (row-level permissions, for
example a `flask_jsonapi.permissions.CheckObjectPermission`) and `middlewares` around its `data_service`. The data
service has one method per action: `create`, `read`, `list`, `update` and `destroy`. `list` returns a
`flask_jsonapi.data_services.ListResult` with the items and, when the client asks for a page, their total.
The [documentation](https://flask-jsonapi.readthedocs.io/) describes every layer, and the
[guide](https://flask-jsonapi.readthedocs.io/en/latest/guide.html) shows how to add authentication, permissions and
business logic, and builds a complete application.

### Usage

Create a new `Article` with title “First article”:
Expand Down
157 changes: 157 additions & 0 deletions docs/examples/full_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import flask
import sqlalchemy
import sqlalchemy.orm

from marshmallow_jsonapi import Schema
from marshmallow_jsonapi import fields

import flask_jsonapi

from flask_jsonapi import exceptions
from flask_jsonapi import guards
from flask_jsonapi import permissions
from flask_jsonapi.data_services import sqlalchemy_repositories

# One in-memory database shared by every thread of the development server.
engine = sqlalchemy.create_engine(
'sqlite://', poolclass=sqlalchemy.pool.StaticPool, connect_args={'check_same_thread': False},
)
session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker(bind=engine))
Base = sqlalchemy.orm.declarative_base()


class Author(Base):
__tablename__ = 'authors'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
name = sqlalchemy.Column(sqlalchemy.String, nullable=False)


class Article(Base):
__tablename__ = 'articles'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
title = sqlalchemy.Column(sqlalchemy.String, nullable=False)
body = sqlalchemy.Column(sqlalchemy.String, nullable=False, default='')
author_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey('authors.id'), nullable=False)
author = sqlalchemy.orm.relationship(Author)


class AuthorSchema(Schema):
id = fields.Int(as_string=True)
name = fields.Str(required=True)

class Meta:
type_ = 'authors'


class ArticleSchema(Schema):
id = fields.Int(as_string=True)
title = fields.Str(required=True)
body = fields.Str()
author = fields.Relationship(
type_='authors', include_resource_linkage=True, schema='AuthorSchema', dump_only=True,
)

class Meta:
type_ = 'articles'


class AuthorRepository(sqlalchemy_repositories.SqlAlchemyModelRepository):
model = Author
session = session


class ArticleRepository(sqlalchemy_repositories.SqlAlchemyModelRepository):
model = Article
session = session


# Fixed tokens for the example only. A real application checks a token against its identity provider.
DEMO_TOKENS = {
'alice-token': 1,
'bob-token': 2,
}


def current_author_id():
scheme, _, token = flask.request.headers.get('Authorization', '').partition(' ')
if scheme != 'Bearer':
return None
return DEMO_TOKENS.get(token)


class RequireToken(guards.Guard):
def check(self, action):
if current_author_id() is None:
raise exceptions.Unauthorized(detail='A valid bearer token is required.')


class AuthorCanChange(permissions.PermissionChecker):
def check_create_permission(self, *, data):
return {**data, 'author_id': current_author_id()}

def check_read_permission(self, *, resource):
return resource

def check_update_permission(self, *, resource, data):
return self._check_author(resource), data

def check_destroy_permission(self, *, resource):
return self._check_author(resource)

@staticmethod
def _check_author(article):
if article.author_id != current_author_id():
raise permissions.PermissionException(detail='Only the author can change an article.')
return article


class AuthorPermissions(permissions.CheckObjectPermission):
permission_checker = AuthorCanChange()

def apply_permission_filter(self, filters):
return dict(filters)


class AuthorViewSet(flask_jsonapi.ViewSet):
schema_class = AuthorSchema
data_service = AuthorRepository()
allowed_actions = {
flask_jsonapi.Actions.read,
flask_jsonapi.Actions.list,
}
guards = [RequireToken()]


class ArticleViewSet(flask_jsonapi.ViewSet):
schema_class = ArticleSchema
data_service = ArticleRepository()
allowed_actions = {
flask_jsonapi.Actions.create,
flask_jsonapi.Actions.read,
flask_jsonapi.Actions.list,
flask_jsonapi.Actions.update,
}
guards = [RequireToken()]
object_permissions = AuthorPermissions()


app = flask.Flask(__name__)
api = flask_jsonapi.Api(app)
api.repository(AuthorViewSet(), 'authors', '/authors/')
api.repository(ArticleViewSet(), 'articles', '/articles/')


@app.teardown_appcontext
def remove_session(exception):
session.remove()


def create_database():
Base.metadata.create_all(engine)
session.add_all([Author(id=1, name='Alice'), Author(id=2, name='Bob')])
session.commit()


if __name__ == '__main__':
create_database()
app.run(host='127.0.0.1', port=5000)
3 changes: 2 additions & 1 deletion docs/filtering.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ Flask-jsonapi supports resource filtering.

**Note:**

All results of examples are ``filters`` parameter passed to ``read_many`` method of ``ResourceList`` or ``get_list`` method of ``ResourceRepositoryViewSet``.
All results of examples are the ``filters`` parameter passed to the ``list`` method of a data
service, to ``read_many`` of ``ResourceList`` or to ``get_list`` of a legacy repository.


Simple Usage
Expand Down
Loading