Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
_links["collection"] = document_link(resource, document_id)
elif version:
_links["parent"] = document_link(resource, document_id)
_links["collection"] = {
"title": resource_title,
"href": "%s?version=all" % _links["parent"]["href"],
}
# modify the self link to add query params or version number
if document_count:
_links["self"]["href"] = "%s%s" % (_links["self"]["href"], q)
elif not document_count and version and version not in ("all", "diffs"):
_links["self"] = document_link(resource, document_id, version)
# create pagination links
if config.DOMAIN[resource]["pagination"]:
# strip any queries from the self link if present
_pagination_link = _links["self"]["href"].split("?")[0]
if (
req.page * req.max_results < (document_count or 0)
or config.OPTIMIZE_PAGINATION_FOR_SPEED
):
q = querydef(
req.max_results,
req.where,
req.sort,
version,
req.page + 1,
other_params,
)
_links["next"] = {
.. versionchanged:: 0.1.0
Support for optional HATEOAS.
"""
response = {}
if config.INFO:
info = {}
info["server"] = "Eve"
info["version"] = eve.__version__
if config.API_VERSION:
info["api_version"] = config.API_VERSION
response[config.INFO] = info
if config.HATEOAS:
links = []
for resource in config.DOMAIN.keys():
internal = config.DOMAIN[resource]["internal_resource"]
if not resource.endswith(config.VERSIONS):
if not bool(internal):
links.append(
{
"href": "%s" % config.URLS[resource],
"title": "%s" % config.DOMAIN[resource]["resource_title"],
}
)
if config.SCHEMA_ENDPOINT is not None:
links.append(
{
"href": "%s" % config.SCHEMA_ENDPOINT,
"title": "%s" % config.SCHEMA_ENDPOINT,
}
)
def get_collection_with_write_concern(self, datasource, resource):
""" Returns a pymongo Collection with the desired write_concern
setting.
PyMongo 3.0+ collections are immutable, yet we still want to allow the
maintainer to change the write concern setting on the fly, hence the
clone.
.. versionadded:: 0.6.1
"""
wc = WriteConcern(config.DOMAIN[resource]["mongo_write_concern"]["w"])
return self.pymongo(resource).db[datasource].with_options(write_concern=wc)
def find_one_raw(self, resource, _id):
""" Retrieves a single raw document.
:param resource: resource name.
:param id: unique id.
.. versionchanged:: 0.6
Support for multiple databases.
.. versionadded:: 0.4
"""
id_field = config.DOMAIN[resource]['id_field']
datasource, filter_, _, _ = self._datasource_ex(resource,
{id_field: _id},
None)
document = self.pymongo(resource).db[datasource].find_one(_id)
return document
def _get_id(obj):
resource = _get_resource(obj)
return getattr(obj, config.DOMAIN[resource]['id_field'])
def _get_resource(model_or_obj):
if isinstance(model_or_obj.__class__, DeclarativeMeta):
model = model_or_obj.__class__
else:
model = model_or_obj
for resource, settings in config.DOMAIN.items():
if settings['datasource']['source'] == model.__name__:
return resource
"""Embeds entities of a given (eventually multilevel) relation into
the document.
:param resource: resource of the document
:param path: dot separated chain of relation names
:param document: document to embed into
:param ancestors: list of entities on the current 'path' of embedding
List in the `ancestors` parameter containing tuples of resource
name and entity id is used to prevent embedding of an entity into
itself and to limit the depth of nested embedding.
"""
# Extract the topmost relation from the chain of relations and check
# if there is a reference to a related entity in the actual document
rel_name, _, tail = path.partition('.')
relation = config.DOMAIN[resource]['relations'].get(rel_name)
if not relation or relation['field'] not in document: return
# Embed unless the entity is already embedded
if rel_name not in document:
# Retrieve the related entities
related_resource = current_app.data.driver.db[relation['resource']]
value = document[relation['field']]
results = related_resource.find({relation['fkey']: value})
entities = []
for result in results:
# Prevent embedding of an entity into itself
if (relation['resource'], result['id']) in ancestors:
continue
result.pop('_id')
# Omit xxx_id property in embedded entity - it is redundant with id it references
if relation['fkey'] != 'id':
# build the main wsgi response object
resp = make_response(rendered, status)
resp.mimetype = mime
# extra headers
if headers:
for header, value in headers:
if header != 'Content-Type':
resp.headers.add(header, value)
# cache directives
if request.method in ('GET', 'HEAD'):
if resource:
cache_control = config.DOMAIN[resource]['cache_control']
expires = config.DOMAIN[resource]['cache_expires']
else:
cache_control = config.CACHE_CONTROL
expires = config.CACHE_EXPIRES
if cache_control:
resp.headers.add('Cache-Control', cache_control)
if expires:
resp.expires = time.time() + expires
# etag and last-modified
if etag:
resp.headers.add('ETag', '"' + etag + '"')
if last_modified:
resp.headers.add('Last-Modified', date_to_rfc1123(last_modified))
# CORS
origin = request.headers.get('Origin')
'version': {'type': 'boolean', 'default': False}
}} """
if not value and self.schema[field].get("nullable"):
return
if "version" in data_relation and data_relation["version"] is True:
value_field = data_relation["field"]
version_field = app.config["VERSION"]
# check value format
if (
isinstance(value, dict)
and value_field in value
and version_field in value
):
resource_def = config.DOMAIN[data_relation["resource"]]
if resource_def["versioning"] is False:
self._error(
field,
"can't save a version with"
" data_relation if '%s' isn't versioned"
% data_relation["resource"],
)
else:
search = get_data_version_relation_document(data_relation, value)
if not search:
self._error(
field,
"value '%s' must exist in resource"
" '%s', field '%s' at version '%s'."
% (
def _validate_unique(self, unique, field, value):
if unique:
id_field = config.DOMAIN[self.resource]['id_field']
if field == id_field and value == self._id:
return
elif field != id_field and self._id is not None:
query = {field: value, id_field: '!= \'%s\'' % self._id}
else:
query = {field: value}
if app.data.find_one(self.resource, None, **query):
self._error(field, "value '%s' is not unique" % value)