Adds generic way of adding extra projections to Pillar queries

This commit is contained in:
2016-03-09 14:00:33 +01:00
parent 949f140981
commit 8c34f04bc6
3 changed files with 28 additions and 18 deletions

View File

@@ -19,23 +19,7 @@ class File(List, Find, Create, Post, Update, Delete, Replace):
path = "files"
file_server_path = "file_storage/file"
build_previews_server_path = "file_storage/build_previews"
@classmethod
def find(cls, resource_id, params=None, api=None):
"""Adds required fields to the projection, if needed.
Only works when `params['projection']` is a dict.
"""
try:
if isinstance(params['projection'], dict):
# These fields are required by Pillar, so they shouldn't be missing from our query.
params['projection'].update({'backend': 1, 'file_path': 1, 'project': 1})
except (TypeError, KeyError):
# Either params is None or params['projection'] doesn't exist.
pass
return super(File, cls).find(resource_id, params=params, api=api)
ensure_query_projections = {'backend': 1, 'file_path': 1, 'project': 1, 'content_type': 1}
def post_file(self, file_path, name=None, api=None):
"""Stores a file on the database or static folder.

View File

@@ -25,6 +25,7 @@ class Node(List, Find, Create, Post, Update, Delete, Replace):
# Force delivery of only 1 result
params['max_results'] = 1
cls._ensure_projections(params, cls.ensure_query_projections)
url = utils.join_url_params(cls.path, params)
response = api.get(url)

View File

@@ -106,6 +106,29 @@ class Resource(object):
class Find(Resource):
ensure_query_projections = {}
@classmethod
def _ensure_projections(cls, params, extra_projections):
"""Ensures that if projections are given in the params, they contain the given ones.
Only works when `params['projection']` exists and is a dict.
@param params: URL parameters
@type params: dict
@param extra_projections: extra projections to add
@type extra_projections: dict
"""
if not extra_projections:
return
try:
if isinstance(params['projection'], dict):
params['projection'].update(extra_projections)
except (TypeError, KeyError):
# Either params is None or params['projection'] doesn't exist.
pass
@classmethod
def find(cls, resource_id, params=None, api=None):
@@ -119,7 +142,8 @@ class Find(Resource):
api = api or Api.Default()
url = utils.join_url(cls.path, str(resource_id))
if params:
if params is not None:
cls._ensure_projections(params, cls.ensure_query_projections)
url = utils.join_url_params(url, params)
item = utils.convert_datetime(api.get(url))
@@ -141,6 +165,7 @@ class Find(Resource):
# Force delivery of only 1 result
params['max_results'] = 1
cls._ensure_projections(params, cls.ensure_query_projections)
url = utils.join_url_params(cls.path, params)
response = api.get(url)