How to use the safrs.log.warning function in safrs

To help you get started, we’ve selected a few safrs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github thomaxxl / safrs / safrs / jsonapi.py View on Github external
# the SAFRSObject should've implemented a filter method or
    # overwritten the _s_filter method to implement custom filtering
    filter_args = get_request_param("filter")
    if filter_args:
        safrs_object_filter = getattr(safrs_object, "filter", None)
        if callable(safrs_object_filter):
            result = safrs_object_filter(filter_args)
        else:
            result = safrs_object._s_filter(filter_args)
        return result

    expressions = []
    filters = get_request_param("filters", {})
    for attr_name, val in filters.items():
        if not attr_name in safrs_object._s_jsonapi_attrs + ["id"]:
            safrs.log.warning("Invalid filter {}".format(attr_name))
            continue
        attr = getattr(safrs_object, attr_name)
        expressions.append((attr, val))

    if isinstance(safrs_object, (list, sqlalchemy.orm.collections.InstrumentedList)):
        # todo: filter properly
        result = safrs_object
    elif expressions:
        expressions_ = [column.in_(val.split(",")) for column, val in expressions]
        result = safrs_object._s_query.filter(*expressions_)
    else:
        result = safrs_object._s_query

    return result
github thomaxxl / safrs / safrs / jsonapi.py View on Github external
document MUST match the appropriate value for resource linkage.
            The top-level links object MAY contain self and related links,
            as described above for relationship objects.
        """
        parent, relation = self.parse_args(**kwargs)
        child_id = kwargs.get(self.child_object_id)
        errors = {}
        count = 1
        meta = {}
        data = None

        if relation is None:
            # child may have been deleted
            return "Not Found", HTTPStatus.NOT_FOUND
        if child_id:
            safrs.log.warning("Fetching relationship items by path id is deprecated and will be removed")
            child = self.target.get_instance(child_id)
            links = {"self": child._s_url}
            # If {ChildId} is passed in the url, return the child object
            # there's a difference between to-one and -to-many relationships:
            if isinstance(relation, SAFRSBase):
                if child != relation:
                    raise NotFoundError()
            elif child not in relation:
                raise NotFoundError()
            else:
                return jsonify({"data": child, "links": {"self": request.url, "related": child._s_url}})
        # elif type(relation) == self.target: # ==>
        elif self.SAFRSObject.relationship.direction == MANYTOONE:
            data = instance = relation
            links = {"self": request.url}
            if request.url != instance._s_url:
github thomaxxl / safrs / safrs / jsonapi.py View on Github external
raise ValidationError("Invalid data payload")
            for child in children:
                child_id = child.get("id", None)
                child_type = child.get("type", None)

                if not child_id or not child_type:
                    raise ValidationError("Invalid data payload", HTTPStatus.FORBIDDEN)

                if child_type != self.target._s_type:
                    raise ValidationError("Invalid type", HTTPStatus.FORBIDDEN)

                child = self.target.get_instance(child_id)
                if child in relation:
                    relation.remove(child)
                else:
                    safrs.log.warning("Item with id {} not in relation".format(child_id))

        return {}, HTTPStatus.NO_CONTENT
github thomaxxl / safrs / safrs / base.py View on Github external
"""
        result = {}
        if fields is None:
            # Check if fields have been provided in the request
            fields = self._s_jsonapi_attrs
            if request:
                fields = request.fields.get(self._s_class_name, fields)

        # filter the relationships, id & type from the data
        for attr in self._s_jsonapi_attrs:
            if attr not in fields:
                continue
            try:
                result[attr] = getattr(self, attr)
            except:
                safrs.log.warning("Failed to fetch {}".format(attr))
                # result[attr] = getattr(self, attr.lower())
        return result
github thomaxxl / safrs / safrs / jsonapi.py View on Github external
attr = getattr(safrs_object, sort_attr, None)
            if sort_attr == "id":
                if attr is None:
                    # => todo: parse the id
                    continue
            elif attr is None or sort_attr not in safrs_object._s_jsonapi_attrs:
                safrs.log.error("{} has no column {} in {}".format(safrs_object, sort_attr, safrs_object._s_jsonapi_attrs))
                continue
            if isinstance(object_query, (list, sqlalchemy.orm.collections.InstrumentedList)):
                object_query = sorted(list(object_query), key=lambda obj: getattr(obj, sort_attr), reverse=sort_attr.startswith("-"))
            else:
                try:
                    # This may fail on non-sqla objects, eg. properties
                    object_query = object_query.order_by(attr)
                except sqlalchemy.exc.ArgumentError as exc:
                    safrs.log.warning("Sort failed for {}.{}: {}".format(safrs_object, sort_attr, exc))
                except Exception as exc:
                    safrs.log.warning("Sort failed for {}.{}: {}".format(safrs_object, sort_attr, exc))

    return object_query
github thomaxxl / safrs / safrs / base.py View on Github external
def _s_get_jsonapi_rpc_methods(cls):
        """
            :return: a list of jsonapi_rpc methods for this class
            :rtype: list
        """
        result = []
        try:
            cls_members = inspect.getmembers(cls)
        except sqlalchemy.exc.InvalidRequestError as exc:
            # This may happen if there's no sqlalchemy superclass
            safrs.log.warning("Member inspection failed for {}: {}".format(cls, exc))
            return result

        for _, method in cls_members:  # [(name, method),..]
            rest_doc = get_doc(method)
            if rest_doc is not None:
                result.append(method)
        return result
github thomaxxl / safrs / safrs / safrs_types.py View on Github external
import datetime
import hashlib
import re
import json
import safrs
from sqlalchemy.types import PickleType, String
from sqlalchemy.types import TypeDecorator, BLOB
from .errors import ValidationError
from .util import classproperty

if sys.version_info[0] == 3:
    unicode = str
try:
    from validate_email import validate_email
except ModuleNotFoundError as exc:
    safrs.log.warning("validate_email module not imported {}".format(exc))
    pass


STRIP_SPECIAL = r"[^\w|%|:|/|-|_\-_\. ]"


class JSONType(PickleType):
    """
        JSON DB type is used to store JSON objects in the database
    """

    impl = BLOB

    def __init__(self, *args, **kwargs):

        # kwargs['pickler'] = json
github thomaxxl / safrs / safrs / jsonapi.py View on Github external
page_base = int(page_offset / limit) * limit

    # Counting may take > 1s for a table with millions of records, depending on the storage engine :|
    # Make it configurable
    # With mysql innodb we can use following to retrieve the count:
    # select TABLE_ROWS from information_schema.TABLES where TABLE_NAME = 'TableName';
    if isinstance(object_query, (list, sqlalchemy.orm.collections.InstrumentedList)):
        count = len(object_query)
    elif SAFRSObject is None:  # for backwards compatibility, ie. when not passed as an arg to paginate()
        count = object_query.count()
    else:
        count = SAFRSObject._s_count()
    if count is None:
        count = object_query.count()
        if count > get_config("MAX_TABLE_COUNT"):
            safrs.log.warning("Large table count detected, performance may be impacted, consider using '_s_count'")

    first_args = (0, limit)
    last_args = (int(int(count / limit) * limit), limit)  # round down
    self_args = (page_base if page_base <= last_args[0] else last_args[0], limit)
    next_args = (page_offset + limit, limit) if page_offset + limit <= last_args[0] else last_args
    prev_args = (page_offset - limit, limit) if page_offset > limit else first_args

    links = {
        "first": get_link(*first_args),
        "self": get_link(page_offset, limit),  # cfr. request.url
        "last": get_link(*last_args),
        "prev": get_link(*prev_args),
        "next": get_link(*next_args),
    }

    if last_args == self_args: