repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
thisfred/val | val/_val.py | _determine_keys | python | def _determine_keys(dictionary):
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults | Determine the different kinds of keys. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L93-L112 | null | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator
def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys."""
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors
def _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key."""
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return []
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)]
def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
"""Validate the rest of the keys present in the data."""
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary."""
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator
def parse_schema(schema):
"""Parse a val schema definition."""
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema)
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/_val.py | _validate_mandatory_keys | python | def _validate_mandatory_keys(mandatory, validated, data, to_validate):
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors | Validate the manditory keys. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L115-L127 | null | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator
def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator
def _determine_keys(dictionary):
"""Determine the different kinds of keys."""
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults
def _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key."""
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return []
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)]
def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
"""Validate the rest of the keys present in the data."""
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary."""
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator
def parse_schema(schema):
"""Parse a val schema definition."""
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema)
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/_val.py | _validate_optional_key | python | def _validate_optional_key(key, missing, value, validated, optional):
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return [] | Validate an optional key. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L130-L138 | null | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator
def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator
def _determine_keys(dictionary):
"""Determine the different kinds of keys."""
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys."""
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)]
def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
"""Validate the rest of the keys present in the data."""
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary."""
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator
def parse_schema(schema):
"""Parse a val schema definition."""
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema)
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/_val.py | _validate_type_key | python | def _validate_type_key(key, value, types, validated):
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)] | Validate a key's value by type. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L141-L153 | null | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator
def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator
def _determine_keys(dictionary):
"""Determine the different kinds of keys."""
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys."""
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors
def _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key."""
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return []
def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
"""Validate the rest of the keys present in the data."""
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary."""
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator
def parse_schema(schema):
"""Parse a val schema definition."""
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema)
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/_val.py | _validate_other_keys | python | def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors | Validate the rest of the keys present in the data. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L156-L168 | [
"def _validate_optional_key(key, missing, value, validated, optional):\n \"\"\"Validate an optional key.\"\"\"\n try:\n validated[key] = optional[key](value)\n except NotValid as ex:\n return ['%r: %s' % (key, arg) for arg in ex.args]\n if key in missing:\n missing.remove(key)\n ... | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator
def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator
def _determine_keys(dictionary):
"""Determine the different kinds of keys."""
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys."""
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors
def _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key."""
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return []
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)]
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary."""
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator
def parse_schema(schema):
"""Parse a val schema definition."""
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema)
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/_val.py | _build_dict_validator | python | def _build_dict_validator(dictionary):
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator | Build a validator from a dictionary. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L171-L195 | [
"def _determine_keys(dictionary):\n \"\"\"Determine the different kinds of keys.\"\"\"\n optional = {}\n defaults = {}\n mandatory = {}\n types = {}\n for key, value in dictionary.items():\n if isinstance(key, Optional):\n optional[key.value] = parse_schema(value)\n if... | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator
def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator
def _determine_keys(dictionary):
"""Determine the different kinds of keys."""
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys."""
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors
def _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key."""
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return []
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)]
def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
"""Validate the rest of the keys present in the data."""
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors
def parse_schema(schema):
"""Parse a val schema definition."""
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema)
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/_val.py | parse_schema | python | def parse_schema(schema):
if isinstance(schema, BaseSchema):
return schema.validate
if type(schema) is type:
return _build_type_validator(schema)
if isinstance(schema, dict):
return _build_dict_validator(schema)
if type(schema) in (list, tuple, set):
return _build_iterable_validator(schema)
if callable(schema):
return _build_callable_validator(schema)
return _build_static_validator(schema) | Parse a val schema definition. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L198-L216 | [
"def _build_type_validator(value_type):\n \"\"\"Build a validator that only checks the type of a value.\"\"\"\n\n def type_validator(data):\n \"\"\"Validate instances of a particular type.\"\"\"\n if isinstance(data, value_type):\n return data\n\n raise NotValid('%r is not of t... | """
val: A validator for arbitrary python objects.
Copyright (c) 2013-2015
Eric Casteleijn, <thisfred@gmail.com>
"""
from val.exceptions import NotValid
__all__ = [
'And', 'BaseSchema', 'Convert', 'Optional', 'Or', 'Ordered',
'Schema', 'nullable', 'parse_schema']
UNSPECIFIED = object()
def _get_repr(thing):
"""Get sensible string representation for validator."""
return (
getattr(thing, '__doc__') or
getattr(thing, '__name__') or
repr(thing))
def _build_type_validator(value_type):
"""Build a validator that only checks the type of a value."""
def type_validator(data):
"""Validate instances of a particular type."""
if isinstance(data, value_type):
return data
raise NotValid('%r is not of type %r' % (data, value_type))
return type_validator
def _build_static_validator(exact_value):
"""Build a validator that checks if the data is equal to an exact value."""
def static_validator(data):
"""Validate by equality."""
if data == exact_value:
return data
raise NotValid('%r is not equal to %r' % (data, exact_value))
return static_validator
def _build_callable_validator(function):
"""Build a validator that checks the return value of function(data)."""
def callable_validator(data):
"""Validate by checking the return value of function(data)."""
try:
if function(data):
return data
except (TypeError, ValueError, NotValid) as ex:
raise NotValid(ex.args)
raise NotValid("%r invalidated by '%s'" % (data, _get_repr(function)))
return callable_validator
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except NotValid:
pass
raise NotValid('%r invalidated by anything in %s.' % (value, iterable))
def iterable_validator(data):
"""Validate an iterable."""
if not type(data) is type(iterable):
raise NotValid('%r is not of type %s' % (data, type(iterable)))
return type(iterable)(item_validator(value) for value in data)
return iterable_validator
def _determine_keys(dictionary):
"""Determine the different kinds of keys."""
optional = {}
defaults = {}
mandatory = {}
types = {}
for key, value in dictionary.items():
if isinstance(key, Optional):
optional[key.value] = parse_schema(value)
if isinstance(value, BaseSchema) and\
value.default is not UNSPECIFIED:
defaults[key.value] = (value.default, value.null_values)
continue # pragma: nocover
if type(key) is type:
types[key] = parse_schema(value)
continue
mandatory[key] = parse_schema(value)
return mandatory, optional, types, defaults
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
"""Validate the manditory keys."""
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotValid as ex:
errors.extend(['%r: %s' % (key, arg) for arg in ex.args])
to_validate.remove(key)
return errors
def _validate_optional_key(key, missing, value, validated, optional):
"""Validate an optional key."""
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return []
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
else:
return []
return ['%r: %r not matched' % (key, value)]
def _validate_other_keys(optional, types, missing, validated, data,
to_validate):
"""Validate the rest of the keys present in the data."""
errors = []
for key in to_validate:
value = data[key]
if key in optional:
errors.extend(
_validate_optional_key(
key, missing, value, validated, optional))
continue
errors.extend(_validate_type_key(key, value, types, validated))
return errors
def _build_dict_validator(dictionary):
"""Build a validator from a dictionary."""
mandatory, optional, types, defaults = _determine_keys(dictionary)
def dict_validator(data):
"""Validate dictionaries."""
missing = list(defaults.keys())
if not isinstance(data, dict):
raise NotValid('%r is not of type dict' % (data,))
validated = {}
to_validate = list(data.keys())
errors = _validate_mandatory_keys(
mandatory, validated, data, to_validate)
errors.extend(
_validate_other_keys(
optional, types, missing, validated, data, to_validate))
if errors:
raise NotValid(*errors)
for key in missing:
validated[key] = defaults[key][0]
return validated
return dict_validator
class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
def validate(self, data):
"""Validate data. Raise NotValid error for invalid data."""
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated
class Schema(BaseSchema):
"""A val schema."""
def __init__(self, schema, **kwargs):
super(Schema, self).__init__(**kwargs)
self._definition = schema
self.schema = parse_schema(schema)
@property
def definition(self):
"""Definition with which this schema was initialized."""
return self._definition
def __repr__(self):
return repr(self.definition)
def _validated(self, data):
return self.schema(data)
class Optional(object):
"""Optional key in a dictionary."""
def __init__(self, value):
"""Optional key in a dictionary."""
self.value = value
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.value)
class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if any subschema validates it."""
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors))
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
def nullable(schema, default=UNSPECIFIED):
"""Create a nullable version of schema."""
return Or(None, schema, default=default)
class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def _validated(self, data):
"""Convert data or die trying."""
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def _validated(self, values):
"""Validate if the values are validated one by one in order."""
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values))
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/_val.py | BaseSchema.validate | python | def validate(self, data):
validated = self._validated(data)
errors = []
for validator in self.additional_validators:
if not validator(validated):
errors.append(
"%s invalidated by '%s'" % (
validated, _get_repr(validator)))
if errors:
raise NotValid(*errors)
if self.default is UNSPECIFIED:
return validated
if self.null_values is not UNSPECIFIED\
and validated in self.null_values:
return self.default
if validated is None:
return self.default
return validated | Validate data. Raise NotValid error for invalid data. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L243-L265 | [
"def _get_repr(thing):\n \"\"\"Get sensible string representation for validator.\"\"\"\n return (\n getattr(thing, '__doc__') or\n getattr(thing, '__name__') or\n repr(thing))\n",
"def _validated(self, data):\n \"\"\"Return validated data.\"\"\"\n raise NotImplementedError\n",
"... | class BaseSchema(object):
"""Base class for all Schema objects."""
def __init__(self, additional_validators=None, default=UNSPECIFIED,
null_values=UNSPECIFIED):
"""Fallback constructor."""
self.additional_validators = additional_validators or []
self.default = default
self.null_values = null_values
self.annotations = {}
def validates(self, data):
"""Return True if schema validates data, False otherwise."""
try:
self.validate(data)
return True
except NotValid:
return False
def _validated(self, data):
"""Return validated data."""
raise NotImplementedError
|
thisfred/val | val/_val.py | Or._validated | python | def _validated(self, data):
errors = []
for sub in self.schemas:
try:
return sub(data)
except NotValid as ex:
errors.extend(ex.args)
raise NotValid(' and '.join(errors)) | Validate data if any subschema validates it. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L310-L319 | null | class Or(BaseSchema):
"""Validates if any of the subschemas do."""
def __init__(self, *values, **kwargs):
super(Or, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def __repr__(self):
return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),)
|
thisfred/val | val/_val.py | And._validated | python | def _validated(self, data):
for sub in self.schemas:
data = sub(data)
return data | Validate data if all subschemas validate it. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L339-L343 | null | class And(BaseSchema):
"""Validates if all of the subschemas do."""
def __init__(self, *values, **kwargs):
super(And, self).__init__(**kwargs)
self.values = values
self.schemas = tuple(parse_schema(s) for s in values)
def __repr__(self):
return "<%s>" % (" and ".join(["%r" % (v,) for v in self.values]),)
|
thisfred/val | val/_val.py | Convert._validated | python | def _validated(self, data):
try:
return self.convert(data)
except (TypeError, ValueError) as ex:
raise NotValid(*ex.args) | Convert data or die trying. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L358-L363 | null | class Convert(BaseSchema):
"""Convert a value."""
def __init__(self, converter, **kwargs):
"""Create schema from a conversion function."""
super(Convert, self).__init__(kwargs)
self.convert = converter
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.convert)
|
thisfred/val | val/_val.py | Ordered._validated | python | def _validated(self, values):
if self.length != len(values):
raise NotValid(
"%r does not have exactly %d values. (Got %d.)" % (
values, self.length, len(values)))
return type(self.schemas)(
self.schemas[i].validate(v) for i, v in enumerate(values)) | Validate if the values are validated one by one in order. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L380-L387 | null | class Ordered(BaseSchema):
"""Validates an ordered iterable."""
def __init__(self, schemas, **kwargs):
"""Create schema from an ordered iterable."""
super(Ordered, self).__init__(**kwargs)
self._definition = schemas
self.schemas = type(schemas)(Schema(s) for s in schemas)
self.length = len(self.schemas)
def __repr__(self):
return "<%s: %r>" % (self.__class__.__name__, self.schemas)
|
thisfred/val | val/tp.py | _translate_struct | python | def _translate_struct(inner_dict):
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeError as ex:
raise DeserializationError(
"Invalid Structure: {}".format(inner_dict))
val_dict = {k: _translate(v) for k, v in required}
val_dict.update({Optional(k): _translate(v) for k, v in optional})
return val_dict | Translate a teleport Struct into a val subschema. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L76-L89 | null | """Convert teleport schemas into val schemas and vice versa."""
import json
from decimal import Decimal
from val import BaseSchema, Optional, Or, Schema
from sys import version_info
from pyrfc3339 import parse as rfc3339
PYTHON_VERSION = version_info[0]
INTEGER = int if PYTHON_VERSION == 3 else Or(int, long) # noqa
STRING = str if PYTHON_VERSION == 3 else Or(str, unicode) # noqa
TeleportDecimal = Or(float, Decimal, int)
def is_jsonable(value):
"""Detect if the value can be converted to JSON."""
try:
json.dumps(value)
except TypeError:
return False
return True
def is_valid_teleport(value):
"""Detect if the value is a valid teleport schema."""
try:
_translate(value)
except DeserializationError:
return False
return True
# XXX: this is pretty icky and error prone. (for instance schemas that use
# their own logically equivalent definitions won't be exportable this way.)
VAL_PRIMITIVES = {
Decimal: "Decimal",
INTEGER: "Integer",
STRING: "String",
TeleportDecimal: "Decimal",
bool: "Boolean",
float: "Decimal",
int: "Integer",
is_jsonable: "JSON",
is_valid_teleport: "Schema",
str: "String",
rfc3339: "DateTime"}
class SerializationError(Exception):
"""Value cannot be serialized."""
pass
class DeserializationError(Exception):
"""Value cannot be deserialized."""
pass
PRIMITIVES = {
'Integer': INTEGER,
'Decimal': TeleportDecimal,
'Boolean': bool,
'String': STRING,
'JSON': is_jsonable,
'DateTime': rfc3339,
'Schema': is_valid_teleport}
COMPOSITES = {
"Array": lambda value: [_translate(value)],
"Map": lambda value: {str: _translate(value)},
"Struct": _translate_struct}
def _translate_composite(teleport_value):
"""Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def _translate(teleport_value):
"""Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def to_val(teleport_schema):
"""Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated)
def _dict_to_teleport(dict_value):
"""Convert a val schema dictionary to teleport."""
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
if isinstance(key, Optional):
optional[key.value] = from_val(value)
else:
required[key] = from_val(value)
return {"Struct": {
"required": required,
"optional": optional}}
def from_val(val_schema):
"""Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
# teleport only supports a single type by default
if len(definition) == 1:
return {"Array": from_val(definition[0])}
if definition in VAL_PRIMITIVES:
return VAL_PRIMITIVES[definition]
raise SerializationError(
"Serializing %r not (yet) supported." % definition)
def document(schema):
"""Print a documented teleport version of the schema."""
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2)
|
thisfred/val | val/tp.py | _translate_composite | python | def _translate_composite(teleport_value):
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value) | Translate a composite teleport value into a val subschema. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L98-L107 | null | """Convert teleport schemas into val schemas and vice versa."""
import json
from decimal import Decimal
from val import BaseSchema, Optional, Or, Schema
from sys import version_info
from pyrfc3339 import parse as rfc3339
PYTHON_VERSION = version_info[0]
INTEGER = int if PYTHON_VERSION == 3 else Or(int, long) # noqa
STRING = str if PYTHON_VERSION == 3 else Or(str, unicode) # noqa
TeleportDecimal = Or(float, Decimal, int)
def is_jsonable(value):
"""Detect if the value can be converted to JSON."""
try:
json.dumps(value)
except TypeError:
return False
return True
def is_valid_teleport(value):
"""Detect if the value is a valid teleport schema."""
try:
_translate(value)
except DeserializationError:
return False
return True
# XXX: this is pretty icky and error prone. (for instance schemas that use
# their own logically equivalent definitions won't be exportable this way.)
VAL_PRIMITIVES = {
Decimal: "Decimal",
INTEGER: "Integer",
STRING: "String",
TeleportDecimal: "Decimal",
bool: "Boolean",
float: "Decimal",
int: "Integer",
is_jsonable: "JSON",
is_valid_teleport: "Schema",
str: "String",
rfc3339: "DateTime"}
class SerializationError(Exception):
"""Value cannot be serialized."""
pass
class DeserializationError(Exception):
"""Value cannot be deserialized."""
pass
PRIMITIVES = {
'Integer': INTEGER,
'Decimal': TeleportDecimal,
'Boolean': bool,
'String': STRING,
'JSON': is_jsonable,
'DateTime': rfc3339,
'Schema': is_valid_teleport}
def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeError as ex:
raise DeserializationError(
"Invalid Structure: {}".format(inner_dict))
val_dict = {k: _translate(v) for k, v in required}
val_dict.update({Optional(k): _translate(v) for k, v in optional})
return val_dict
COMPOSITES = {
"Array": lambda value: [_translate(value)],
"Map": lambda value: {str: _translate(value)},
"Struct": _translate_struct}
def _translate(teleport_value):
"""Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def to_val(teleport_schema):
"""Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated)
def _dict_to_teleport(dict_value):
"""Convert a val schema dictionary to teleport."""
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
if isinstance(key, Optional):
optional[key.value] = from_val(value)
else:
required[key] = from_val(value)
return {"Struct": {
"required": required,
"optional": optional}}
def from_val(val_schema):
"""Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
# teleport only supports a single type by default
if len(definition) == 1:
return {"Array": from_val(definition[0])}
if definition in VAL_PRIMITIVES:
return VAL_PRIMITIVES[definition]
raise SerializationError(
"Serializing %r not (yet) supported." % definition)
def document(schema):
"""Print a documented teleport version of the schema."""
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2)
|
thisfred/val | val/tp.py | _translate | python | def _translate(teleport_value):
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value) | Translate a teleport value in to a val subschema. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L110-L119 | [
"def _translate_composite(teleport_value):\n \"\"\"Translate a composite teleport value into a val subschema.\"\"\"\n for key in (\"Array\", \"Map\", \"Struct\"):\n value = teleport_value.get(key)\n if value is None:\n continue\n return COMPOSITES[key](value)\n\n raise Deser... | """Convert teleport schemas into val schemas and vice versa."""
import json
from decimal import Decimal
from val import BaseSchema, Optional, Or, Schema
from sys import version_info
from pyrfc3339 import parse as rfc3339
PYTHON_VERSION = version_info[0]
INTEGER = int if PYTHON_VERSION == 3 else Or(int, long) # noqa
STRING = str if PYTHON_VERSION == 3 else Or(str, unicode) # noqa
TeleportDecimal = Or(float, Decimal, int)
def is_jsonable(value):
"""Detect if the value can be converted to JSON."""
try:
json.dumps(value)
except TypeError:
return False
return True
def is_valid_teleport(value):
"""Detect if the value is a valid teleport schema."""
try:
_translate(value)
except DeserializationError:
return False
return True
# XXX: this is pretty icky and error prone. (for instance schemas that use
# their own logically equivalent definitions won't be exportable this way.)
VAL_PRIMITIVES = {
Decimal: "Decimal",
INTEGER: "Integer",
STRING: "String",
TeleportDecimal: "Decimal",
bool: "Boolean",
float: "Decimal",
int: "Integer",
is_jsonable: "JSON",
is_valid_teleport: "Schema",
str: "String",
rfc3339: "DateTime"}
class SerializationError(Exception):
"""Value cannot be serialized."""
pass
class DeserializationError(Exception):
"""Value cannot be deserialized."""
pass
PRIMITIVES = {
'Integer': INTEGER,
'Decimal': TeleportDecimal,
'Boolean': bool,
'String': STRING,
'JSON': is_jsonable,
'DateTime': rfc3339,
'Schema': is_valid_teleport}
def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeError as ex:
raise DeserializationError(
"Invalid Structure: {}".format(inner_dict))
val_dict = {k: _translate(v) for k, v in required}
val_dict.update({Optional(k): _translate(v) for k, v in optional})
return val_dict
COMPOSITES = {
"Array": lambda value: [_translate(value)],
"Map": lambda value: {str: _translate(value)},
"Struct": _translate_struct}
def _translate_composite(teleport_value):
"""Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def to_val(teleport_schema):
"""Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated)
def _dict_to_teleport(dict_value):
"""Convert a val schema dictionary to teleport."""
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
if isinstance(key, Optional):
optional[key.value] = from_val(value)
else:
required[key] = from_val(value)
return {"Struct": {
"required": required,
"optional": optional}}
def from_val(val_schema):
"""Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
# teleport only supports a single type by default
if len(definition) == 1:
return {"Array": from_val(definition[0])}
if definition in VAL_PRIMITIVES:
return VAL_PRIMITIVES[definition]
raise SerializationError(
"Serializing %r not (yet) supported." % definition)
def document(schema):
"""Print a documented teleport version of the schema."""
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2)
|
thisfred/val | val/tp.py | to_val | python | def to_val(teleport_schema):
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated) | Convert a parsed teleport schema to a val schema. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L122-L128 | [
"def _translate(teleport_value):\n \"\"\"Translate a teleport value in to a val subschema.\"\"\"\n if isinstance(teleport_value, dict):\n return _translate_composite(teleport_value)\n\n if teleport_value in PRIMITIVES:\n return PRIMITIVES[teleport_value]\n\n raise DeserializationError(\n ... | """Convert teleport schemas into val schemas and vice versa."""
import json
from decimal import Decimal
from val import BaseSchema, Optional, Or, Schema
from sys import version_info
from pyrfc3339 import parse as rfc3339
PYTHON_VERSION = version_info[0]
INTEGER = int if PYTHON_VERSION == 3 else Or(int, long) # noqa
STRING = str if PYTHON_VERSION == 3 else Or(str, unicode) # noqa
TeleportDecimal = Or(float, Decimal, int)
def is_jsonable(value):
"""Detect if the value can be converted to JSON."""
try:
json.dumps(value)
except TypeError:
return False
return True
def is_valid_teleport(value):
"""Detect if the value is a valid teleport schema."""
try:
_translate(value)
except DeserializationError:
return False
return True
# XXX: this is pretty icky and error prone. (for instance schemas that use
# their own logically equivalent definitions won't be exportable this way.)
VAL_PRIMITIVES = {
Decimal: "Decimal",
INTEGER: "Integer",
STRING: "String",
TeleportDecimal: "Decimal",
bool: "Boolean",
float: "Decimal",
int: "Integer",
is_jsonable: "JSON",
is_valid_teleport: "Schema",
str: "String",
rfc3339: "DateTime"}
class SerializationError(Exception):
"""Value cannot be serialized."""
pass
class DeserializationError(Exception):
"""Value cannot be deserialized."""
pass
PRIMITIVES = {
'Integer': INTEGER,
'Decimal': TeleportDecimal,
'Boolean': bool,
'String': STRING,
'JSON': is_jsonable,
'DateTime': rfc3339,
'Schema': is_valid_teleport}
def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeError as ex:
raise DeserializationError(
"Invalid Structure: {}".format(inner_dict))
val_dict = {k: _translate(v) for k, v in required}
val_dict.update({Optional(k): _translate(v) for k, v in optional})
return val_dict
COMPOSITES = {
"Array": lambda value: [_translate(value)],
"Map": lambda value: {str: _translate(value)},
"Struct": _translate_struct}
def _translate_composite(teleport_value):
"""Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def _translate(teleport_value):
"""Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def _dict_to_teleport(dict_value):
"""Convert a val schema dictionary to teleport."""
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
if isinstance(key, Optional):
optional[key.value] = from_val(value)
else:
required[key] = from_val(value)
return {"Struct": {
"required": required,
"optional": optional}}
def from_val(val_schema):
"""Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
# teleport only supports a single type by default
if len(definition) == 1:
return {"Array": from_val(definition[0])}
if definition in VAL_PRIMITIVES:
return VAL_PRIMITIVES[definition]
raise SerializationError(
"Serializing %r not (yet) supported." % definition)
def document(schema):
"""Print a documented teleport version of the schema."""
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2)
|
thisfred/val | val/tp.py | _dict_to_teleport | python | def _dict_to_teleport(dict_value):
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
if isinstance(key, Optional):
optional[key.value] = from_val(value)
else:
required[key] = from_val(value)
return {"Struct": {
"required": required,
"optional": optional}} | Convert a val schema dictionary to teleport. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L131-L148 | [
"def from_val(val_schema):\n \"\"\"Serialize a val schema to teleport.\"\"\"\n definition = getattr(val_schema, \"definition\", val_schema) if isinstance(\n val_schema, BaseSchema) else val_schema\n if isinstance(definition, dict):\n return _dict_to_teleport(definition)\n\n if isinstance(d... | """Convert teleport schemas into val schemas and vice versa."""
import json
from decimal import Decimal
from val import BaseSchema, Optional, Or, Schema
from sys import version_info
from pyrfc3339 import parse as rfc3339
PYTHON_VERSION = version_info[0]
INTEGER = int if PYTHON_VERSION == 3 else Or(int, long) # noqa
STRING = str if PYTHON_VERSION == 3 else Or(str, unicode) # noqa
TeleportDecimal = Or(float, Decimal, int)
def is_jsonable(value):
"""Detect if the value can be converted to JSON."""
try:
json.dumps(value)
except TypeError:
return False
return True
def is_valid_teleport(value):
"""Detect if the value is a valid teleport schema."""
try:
_translate(value)
except DeserializationError:
return False
return True
# XXX: this is pretty icky and error prone. (for instance schemas that use
# their own logically equivalent definitions won't be exportable this way.)
VAL_PRIMITIVES = {
Decimal: "Decimal",
INTEGER: "Integer",
STRING: "String",
TeleportDecimal: "Decimal",
bool: "Boolean",
float: "Decimal",
int: "Integer",
is_jsonable: "JSON",
is_valid_teleport: "Schema",
str: "String",
rfc3339: "DateTime"}
class SerializationError(Exception):
"""Value cannot be serialized."""
pass
class DeserializationError(Exception):
"""Value cannot be deserialized."""
pass
PRIMITIVES = {
'Integer': INTEGER,
'Decimal': TeleportDecimal,
'Boolean': bool,
'String': STRING,
'JSON': is_jsonable,
'DateTime': rfc3339,
'Schema': is_valid_teleport}
def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeError as ex:
raise DeserializationError(
"Invalid Structure: {}".format(inner_dict))
val_dict = {k: _translate(v) for k, v in required}
val_dict.update({Optional(k): _translate(v) for k, v in optional})
return val_dict
COMPOSITES = {
"Array": lambda value: [_translate(value)],
"Map": lambda value: {str: _translate(value)},
"Struct": _translate_struct}
def _translate_composite(teleport_value):
"""Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def _translate(teleport_value):
"""Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def to_val(teleport_schema):
"""Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated)
def from_val(val_schema):
"""Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
# teleport only supports a single type by default
if len(definition) == 1:
return {"Array": from_val(definition[0])}
if definition in VAL_PRIMITIVES:
return VAL_PRIMITIVES[definition]
raise SerializationError(
"Serializing %r not (yet) supported." % definition)
def document(schema):
"""Print a documented teleport version of the schema."""
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2)
|
thisfred/val | val/tp.py | from_val | python | def from_val(val_schema):
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
# teleport only supports a single type by default
if len(definition) == 1:
return {"Array": from_val(definition[0])}
if definition in VAL_PRIMITIVES:
return VAL_PRIMITIVES[definition]
raise SerializationError(
"Serializing %r not (yet) supported." % definition) | Serialize a val schema to teleport. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L151-L167 | [
"def from_val(val_schema):\n \"\"\"Serialize a val schema to teleport.\"\"\"\n definition = getattr(val_schema, \"definition\", val_schema) if isinstance(\n val_schema, BaseSchema) else val_schema\n if isinstance(definition, dict):\n return _dict_to_teleport(definition)\n\n if isinstance(d... | """Convert teleport schemas into val schemas and vice versa."""
import json
from decimal import Decimal
from val import BaseSchema, Optional, Or, Schema
from sys import version_info
from pyrfc3339 import parse as rfc3339
PYTHON_VERSION = version_info[0]
INTEGER = int if PYTHON_VERSION == 3 else Or(int, long) # noqa
STRING = str if PYTHON_VERSION == 3 else Or(str, unicode) # noqa
TeleportDecimal = Or(float, Decimal, int)
def is_jsonable(value):
"""Detect if the value can be converted to JSON."""
try:
json.dumps(value)
except TypeError:
return False
return True
def is_valid_teleport(value):
"""Detect if the value is a valid teleport schema."""
try:
_translate(value)
except DeserializationError:
return False
return True
# XXX: this is pretty icky and error prone. (for instance schemas that use
# their own logically equivalent definitions won't be exportable this way.)
VAL_PRIMITIVES = {
Decimal: "Decimal",
INTEGER: "Integer",
STRING: "String",
TeleportDecimal: "Decimal",
bool: "Boolean",
float: "Decimal",
int: "Integer",
is_jsonable: "JSON",
is_valid_teleport: "Schema",
str: "String",
rfc3339: "DateTime"}
class SerializationError(Exception):
"""Value cannot be serialized."""
pass
class DeserializationError(Exception):
"""Value cannot be deserialized."""
pass
PRIMITIVES = {
'Integer': INTEGER,
'Decimal': TeleportDecimal,
'Boolean': bool,
'String': STRING,
'JSON': is_jsonable,
'DateTime': rfc3339,
'Schema': is_valid_teleport}
def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeError as ex:
raise DeserializationError(
"Invalid Structure: {}".format(inner_dict))
val_dict = {k: _translate(v) for k, v in required}
val_dict.update({Optional(k): _translate(v) for k, v in optional})
return val_dict
COMPOSITES = {
"Array": lambda value: [_translate(value)],
"Map": lambda value: {str: _translate(value)},
"Struct": _translate_struct}
def _translate_composite(teleport_value):
"""Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def _translate(teleport_value):
"""Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def to_val(teleport_schema):
"""Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated)
def _dict_to_teleport(dict_value):
"""Convert a val schema dictionary to teleport."""
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
if isinstance(key, Optional):
optional[key.value] = from_val(value)
else:
required[key] = from_val(value)
return {"Struct": {
"required": required,
"optional": optional}}
def document(schema):
"""Print a documented teleport version of the schema."""
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2)
|
thisfred/val | val/tp.py | document | python | def document(schema):
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2) | Print a documented teleport version of the schema. | train | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L170-L173 | [
"def from_val(val_schema):\n \"\"\"Serialize a val schema to teleport.\"\"\"\n definition = getattr(val_schema, \"definition\", val_schema) if isinstance(\n val_schema, BaseSchema) else val_schema\n if isinstance(definition, dict):\n return _dict_to_teleport(definition)\n\n if isinstance(d... | """Convert teleport schemas into val schemas and vice versa."""
import json
from decimal import Decimal
from val import BaseSchema, Optional, Or, Schema
from sys import version_info
from pyrfc3339 import parse as rfc3339
PYTHON_VERSION = version_info[0]
INTEGER = int if PYTHON_VERSION == 3 else Or(int, long) # noqa
STRING = str if PYTHON_VERSION == 3 else Or(str, unicode) # noqa
TeleportDecimal = Or(float, Decimal, int)
def is_jsonable(value):
"""Detect if the value can be converted to JSON."""
try:
json.dumps(value)
except TypeError:
return False
return True
def is_valid_teleport(value):
"""Detect if the value is a valid teleport schema."""
try:
_translate(value)
except DeserializationError:
return False
return True
# XXX: this is pretty icky and error prone. (for instance schemas that use
# their own logically equivalent definitions won't be exportable this way.)
VAL_PRIMITIVES = {
Decimal: "Decimal",
INTEGER: "Integer",
STRING: "String",
TeleportDecimal: "Decimal",
bool: "Boolean",
float: "Decimal",
int: "Integer",
is_jsonable: "JSON",
is_valid_teleport: "Schema",
str: "String",
rfc3339: "DateTime"}
class SerializationError(Exception):
"""Value cannot be serialized."""
pass
class DeserializationError(Exception):
"""Value cannot be deserialized."""
pass
PRIMITIVES = {
'Integer': INTEGER,
'Decimal': TeleportDecimal,
'Boolean': bool,
'String': STRING,
'JSON': is_jsonable,
'DateTime': rfc3339,
'Schema': is_valid_teleport}
def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeError as ex:
raise DeserializationError(
"Invalid Structure: {}".format(inner_dict))
val_dict = {k: _translate(v) for k, v in required}
val_dict.update({Optional(k): _translate(v) for k, v in optional})
return val_dict
COMPOSITES = {
"Array": lambda value: [_translate(value)],
"Map": lambda value: {str: _translate(value)},
"Struct": _translate_struct}
def _translate_composite(teleport_value):
"""Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def _translate(teleport_value):
"""Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not interpret %r as a teleport schema." % teleport_value)
def to_val(teleport_schema):
"""Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated)
def _dict_to_teleport(dict_value):
"""Convert a val schema dictionary to teleport."""
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
if isinstance(key, Optional):
optional[key.value] = from_val(value)
else:
required[key] = from_val(value)
return {"Struct": {
"required": required,
"optional": optional}}
def from_val(val_schema):
"""Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
# teleport only supports a single type by default
if len(definition) == 1:
return {"Array": from_val(definition[0])}
if definition in VAL_PRIMITIVES:
return VAL_PRIMITIVES[definition]
raise SerializationError(
"Serializing %r not (yet) supported." % definition)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/handlers.py | AlkiviEmailHandler.generate_mail | python | def generate_mail(self):
# Script info
msg = "Script info : \r\n"
msg = msg + "%-9s: %s" % ('Script', SOURCEDIR) + "\r\n"
msg = msg + "%-9s: %s" % ('User', USER) + "\r\n"
msg = msg + "%-9s: %s" % ('Host', HOST) + "\r\n"
msg = msg + "%-9s: %s" % ('PID', PID) + "\r\n"
# Current trace
msg = msg + "\r\nCurrent trace : \r\n"
for record in self.current_buffer:
msg = msg + record + "\r\n"
# Now add stack trace
msg = msg + "\r\nFull trace : \r\n"
for record in self.complete_buffer:
msg = msg + record + "\r\n"
# Dump ENV
msg = msg + "\r\nEnvironment:" + "\r\n"
environ = OrderedDict(sorted(os.environ.items()))
for name, value in environ.items():
msg = msg + "%-10s = %s\r\n" % (name, value)
if USE_MIME:
real_msg = MIMEText(msg, _charset='utf-8')
real_msg['Subject'] = self.get_subject()
real_msg['To'] = ','.join(self.toaddrs)
real_msg['From'] = self.fromaddr
else:
real_msg = EmailMessage()
real_msg['Subject'] = self.get_subject()
real_msg['To'] = ','.join(self.toaddrs)
real_msg['From'] = self.fromaddr
real_msg.set_content(msg)
return real_msg | Generate the email as MIMEText | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/handlers.py#L57-L100 | [
"def get_subject(self):\n \"\"\"Generate the subject.\"\"\"\n level = logging.getLevelName(self.flush_level)\n message = self.current_buffer[0].split(\"\\n\")[0]\n message = message.split(']')[-1]\n return '{0} : {1}{2}'.format(level, SOURCE, message)\n"
] | class AlkiviEmailHandler(logging.Handler):
"""Custom class that will handle email sending
When log level reach a certains level and receive flush :
- flush the logger with the current message
- send the full trace of the current logger (all level)
"""
def __init__(self, mailhost, fromaddr, toaddrs, level):
logging.Handler.__init__(self)
self.mailhost = mailhost
self.mailport = None
self.fromaddr = fromaddr
self.toaddrs = toaddrs
self.flush_level = level
# Init another buffer which will store everything
self.complete_buffer = []
# Buffer is an array that contains formatted messages
self.current_buffer = []
def emit(self, record):
msg = self.format(record)
if(record.levelno >= self.flush_level):
self.current_buffer.append(msg)
# Add to all buffer in any case
self.complete_buffer.append(msg)
def get_subject(self):
"""Generate the subject."""
level = logging.getLevelName(self.flush_level)
message = self.current_buffer[0].split("\n")[0]
message = message.split(']')[-1]
return '{0} : {1}{2}'.format(level, SOURCE, message)
def flush(self):
if len(self.current_buffer) > 0:
try:
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port)
msg = self.generate_mail()
if USE_MIME:
smtp.sendmail(self.fromaddr, self.toaddrs, msg.__str__())
else:
smtp.send_message(msg)
smtp.quit()
except Exception as exception:
self.handleError(None) # no particular record
self.current_buffer = []
self.complete_buffer = []
|
alkivi-sas/python-alkivi-logger | alkivi/logger/handlers.py | AlkiviEmailHandler.get_subject | python | def get_subject(self):
level = logging.getLevelName(self.flush_level)
message = self.current_buffer[0].split("\n")[0]
message = message.split(']')[-1]
return '{0} : {1}{2}'.format(level, SOURCE, message) | Generate the subject. | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/handlers.py#L102-L107 | null | class AlkiviEmailHandler(logging.Handler):
"""Custom class that will handle email sending
When log level reach a certains level and receive flush :
- flush the logger with the current message
- send the full trace of the current logger (all level)
"""
def __init__(self, mailhost, fromaddr, toaddrs, level):
logging.Handler.__init__(self)
self.mailhost = mailhost
self.mailport = None
self.fromaddr = fromaddr
self.toaddrs = toaddrs
self.flush_level = level
# Init another buffer which will store everything
self.complete_buffer = []
# Buffer is an array that contains formatted messages
self.current_buffer = []
def emit(self, record):
msg = self.format(record)
if(record.levelno >= self.flush_level):
self.current_buffer.append(msg)
# Add to all buffer in any case
self.complete_buffer.append(msg)
def generate_mail(self):
"""Generate the email as MIMEText
"""
# Script info
msg = "Script info : \r\n"
msg = msg + "%-9s: %s" % ('Script', SOURCEDIR) + "\r\n"
msg = msg + "%-9s: %s" % ('User', USER) + "\r\n"
msg = msg + "%-9s: %s" % ('Host', HOST) + "\r\n"
msg = msg + "%-9s: %s" % ('PID', PID) + "\r\n"
# Current trace
msg = msg + "\r\nCurrent trace : \r\n"
for record in self.current_buffer:
msg = msg + record + "\r\n"
# Now add stack trace
msg = msg + "\r\nFull trace : \r\n"
for record in self.complete_buffer:
msg = msg + record + "\r\n"
# Dump ENV
msg = msg + "\r\nEnvironment:" + "\r\n"
environ = OrderedDict(sorted(os.environ.items()))
for name, value in environ.items():
msg = msg + "%-10s = %s\r\n" % (name, value)
if USE_MIME:
real_msg = MIMEText(msg, _charset='utf-8')
real_msg['Subject'] = self.get_subject()
real_msg['To'] = ','.join(self.toaddrs)
real_msg['From'] = self.fromaddr
else:
real_msg = EmailMessage()
real_msg['Subject'] = self.get_subject()
real_msg['To'] = ','.join(self.toaddrs)
real_msg['From'] = self.fromaddr
real_msg.set_content(msg)
return real_msg
def flush(self):
if len(self.current_buffer) > 0:
try:
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port)
msg = self.generate_mail()
if USE_MIME:
smtp.sendmail(self.fromaddr, self.toaddrs, msg.__str__())
else:
smtp.send_message(msg)
smtp.quit()
except Exception as exception:
self.handleError(None) # no particular record
self.current_buffer = []
self.complete_buffer = []
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger._log | python | def _log(self, priority, message, *args, **kwargs):
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message) | Generic log functions | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L70-L76 | null | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.debug | python | def debug(self, message, *args, **kwargs):
self._log(logging.DEBUG, message, *args, **kwargs) | Debug level to use and abuse when coding | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L78-L81 | [
"def _log(self, priority, message, *args, **kwargs):\n \"\"\"Generic log functions\n \"\"\"\n for arg in args:\n message = message + \"\\n\" + self.pretty_printer.pformat(arg)\n\n self.logger.log(priority, message)\n"
] | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.info | python | def info(self, message, *args, **kwargs):
self._log(logging.INFO, message, *args, **kwargs) | More important level : default for print and save | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L83-L86 | [
"def _log(self, priority, message, *args, **kwargs):\n \"\"\"Generic log functions\n \"\"\"\n for arg in args:\n message = message + \"\\n\" + self.pretty_printer.pformat(arg)\n\n self.logger.log(priority, message)\n"
] | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.warn | python | def warn(self, message, *args, **kwargs):
self._log(logging.WARNING, message, *args, **kwargs) | Send email and syslog by default ... | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L88-L91 | [
"def _log(self, priority, message, *args, **kwargs):\n \"\"\"Generic log functions\n \"\"\"\n for arg in args:\n message = message + \"\\n\" + self.pretty_printer.pformat(arg)\n\n self.logger.log(priority, message)\n"
] | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.warning | python | def warning(self, message, *args, **kwargs):
self._log(logging.WARNING, message, *args, **kwargs) | Alias to warn | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L93-L96 | [
"def _log(self, priority, message, *args, **kwargs):\n \"\"\"Generic log functions\n \"\"\"\n for arg in args:\n message = message + \"\\n\" + self.pretty_printer.pformat(arg)\n\n self.logger.log(priority, message)\n"
] | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.error | python | def error(self, message, *args, **kwargs):
self._log(logging.ERROR, message, *args, **kwargs) | Should not happen ... | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L98-L101 | [
"def _log(self, priority, message, *args, **kwargs):\n \"\"\"Generic log functions\n \"\"\"\n for arg in args:\n message = message + \"\\n\" + self.pretty_printer.pformat(arg)\n\n self.logger.log(priority, message)\n"
] | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.critical | python | def critical(self, message, *args, **kwargs):
self._log(logging.CRITICAL, message, *args, **kwargs) | Highest level | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L103-L106 | [
"def _log(self, priority, message, *args, **kwargs):\n \"\"\"Generic log functions\n \"\"\"\n for arg in args:\n message = message + \"\\n\" + self.pretty_printer.pformat(arg)\n\n self.logger.log(priority, message)\n"
] | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.exception | python | def exception(self, message, *args, **kwargs):
self.logger.exception(message, *args, **kwargs) | Handle exception | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L108-L111 | null | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.init_logger | python | def init_logger(self):
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return | Create configuration for the root logger. | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L113-L143 | [
"def _create_handler(self, handler_class, level):\n \"\"\"Create an handler for at specific level.\"\"\"\n if handler_class == logging.StreamHandler:\n handler = handler_class()\n handler.setLevel(level)\n elif handler_class == logging.handlers.SysLogHandler:\n handler = handler_class(... | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.new_iteration | python | def new_iteration(self, prefix):
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter() | When inside a loop logger, created a new iteration | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L168-L176 | [
"def reset_formatter(self):\n \"\"\"Rebuild formatter for all handlers.\"\"\"\n for handler in self.handlers:\n formatter = self.get_formatter(handler)\n handler.setFormatter(formatter)\n",
"def flush(self):\n \"\"\"Flush data when dealing with iteration.\"\"\"\n for handler in self.hand... | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.reset_formatter | python | def reset_formatter(self):
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter) | Rebuild formatter for all handlers. | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L178-L182 | [
"def get_formatter(self, handler):\n \"\"\"\n Return formatters according to handler.\n\n All handlers are the same format, except syslog.\n We omit time when syslogging.\n \"\"\"\n if isinstance(handler, logging.handlers.SysLogHandler):\n formatter = '[%(levelname)-9s]'\n else:\n ... | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger._set_min_level | python | def _set_min_level(self, handler_class, level):
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level) | Generic method to setLevel for handlers. | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L189-L197 | [
"def _exist_handler(self, handler_class):\n \"\"\"Return True or False is the class exists.\"\"\"\n return self._get_handler(handler_class) is not None\n"
] | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.set_min_level_to_print | python | def set_min_level_to_print(self, level):
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level) | Allow to change print level after creation | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L199-L204 | [
"def _set_min_level(self, handler_class, level):\n \"\"\"Generic method to setLevel for handlers.\"\"\"\n if self._exist_handler(handler_class):\n if not level:\n self._delete_handler(handler_class)\n else:\n self._update_handler(handler_class, level=level)\n elif level:... | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.set_min_level_to_save | python | def set_min_level_to_save(self, level):
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level) | Allow to change save level after creation | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L206-L211 | [
"def _set_min_level(self, handler_class, level):\n \"\"\"Generic method to setLevel for handlers.\"\"\"\n if self._exist_handler(handler_class):\n if not level:\n self._delete_handler(handler_class)\n else:\n self._update_handler(handler_class, level=level)\n elif level:... | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.set_min_level_to_mail | python | def set_min_level_to_mail(self, level):
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level) | Allow to change mail level after creation | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L213-L218 | [
"def _set_min_level(self, handler_class, level):\n \"\"\"Generic method to setLevel for handlers.\"\"\"\n if self._exist_handler(handler_class):\n if not level:\n self._delete_handler(handler_class)\n else:\n self._update_handler(handler_class, level=level)\n elif level:... | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.set_min_level_to_syslog | python | def set_min_level_to_syslog(self, level):
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level) | Allow to change syslog level after creation | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L220-L225 | [
"def _set_min_level(self, handler_class, level):\n \"\"\"Generic method to setLevel for handlers.\"\"\"\n if self._exist_handler(handler_class):\n if not level:\n self._delete_handler(handler_class)\n else:\n self._update_handler(handler_class, level=level)\n elif level:... | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger._get_handler | python | def _get_handler(self, handler_class):
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element | Return an existing class of handler. | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L227-L234 | null | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger._delete_handler | python | def _delete_handler(self, handler_class):
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove) | Delete a specific handler from our logger. | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L240-L247 | null | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger._update_handler | python | def _update_handler(self, handler_class, level):
handler = self._get_handler(handler_class)
handler.setLevel(level) | Update the level of an handler. | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L249-L252 | null | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger._create_handler | python | def _create_handler(self, handler_class, level):
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler) | Create an handler for at specific level. | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L254-L276 | [
"def get_formatter(self, handler):\n \"\"\"\n Return formatters according to handler.\n\n All handlers are the same format, except syslog.\n We omit time when syslogging.\n \"\"\"\n if isinstance(handler, logging.handlers.SysLogHandler):\n formatter = '[%(levelname)-9s]'\n else:\n ... | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def get_formatter(self, handler):
"""
Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging.
"""
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter)
|
alkivi-sas/python-alkivi-logger | alkivi/logger/logger.py | Logger.get_formatter | python | def get_formatter(self, handler):
if isinstance(handler, logging.handlers.SysLogHandler):
formatter = '[%(levelname)-9s]'
else:
formatter = '[%(asctime)s] [%(levelname)-9s]'
for p in self.prefix:
formatter += ' [%s]' % (p)
formatter = formatter + ' %(message)s'
return logging.Formatter(formatter) | Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging. | train | https://github.com/alkivi-sas/python-alkivi-logger/blob/e96d5a987a5c8789c51d4fa7541709e05b1f51e1/alkivi/logger/logger.py#L278-L293 | null | class Logger(object):
"""
This class defines a custom Logger class.
This main property is iteration which allow to perform loop iteration
easily
"""
def __init__(self, min_log_level_to_print=logging.INFO,
min_log_level_to_mail=logging.WARNING,
min_log_level_to_save=logging.INFO,
min_log_level_to_syslog=logging.WARNING,
filename=None,
emails=None,
use_root_logger=False):
"""
Create a Logger object, that can be used to log.
Will set several handlers according to what we want.
"""
if filename is None:
filename = '%s.log' % SOURCE
if emails is None:
emails = []
# Default Attributes
self.filename = filename
self.emails = emails
self.prefix = []
# Default level
self.min_log_level_to_print = min_log_level_to_print
self.min_log_level_to_save = min_log_level_to_save
self.min_log_level_to_mail = min_log_level_to_mail
self.min_log_level_to_syslog = min_log_level_to_syslog
# Set and tracks all handlers
self.handlers = []
# Create object Dumper
self.pretty_printer = pprint.PrettyPrinter(indent=4)
# Init our logger
if use_root_logger:
self.logger = logging.getLogger()
else:
self.logger = logging.getLogger(SOURCE)
self.init_logger()
def _log(self, priority, message, *args, **kwargs):
"""Generic log functions
"""
for arg in args:
message = message + "\n" + self.pretty_printer.pformat(arg)
self.logger.log(priority, message)
def debug(self, message, *args, **kwargs):
"""Debug level to use and abuse when coding
"""
self._log(logging.DEBUG, message, *args, **kwargs)
def info(self, message, *args, **kwargs):
"""More important level : default for print and save
"""
self._log(logging.INFO, message, *args, **kwargs)
def warn(self, message, *args, **kwargs):
"""Send email and syslog by default ...
"""
self._log(logging.WARNING, message, *args, **kwargs)
def warning(self, message, *args, **kwargs):
"""Alias to warn
"""
self._log(logging.WARNING, message, *args, **kwargs)
def error(self, message, *args, **kwargs):
"""Should not happen ...
"""
self._log(logging.ERROR, message, *args, **kwargs)
def critical(self, message, *args, **kwargs):
"""Highest level
"""
self._log(logging.CRITICAL, message, *args, **kwargs)
def exception(self, message, *args, **kwargs):
"""Handle exception
"""
self.logger.exception(message, *args, **kwargs)
def init_logger(self):
"""Create configuration for the root logger."""
# All logs are comming to this logger
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = False
# Logging to console
if self.min_log_level_to_print:
level = self.min_log_level_to_print
handler_class = logging.StreamHandler
self._create_handler(handler_class, level)
# Logging to file
if self.min_log_level_to_save:
level = self.min_log_level_to_save
handler_class = logging.handlers.TimedRotatingFileHandler
self._create_handler(handler_class, level)
# Logging to syslog
if self.min_log_level_to_syslog:
level = self.min_log_level_to_syslog
handler_class = logging.handlers.SysLogHandler
self._create_handler(handler_class, level)
# Logging to email
if self.min_log_level_to_mail:
level = self.min_log_level_to_mail
handler_class = AlkiviEmailHandler
self._create_handler(handler_class, level)
return
def new_loop_logger(self):
"""
Add a prefix to the correct logger
"""
# Add a prefix but dont refresh formatter
# This will happen in new_iteration
self.prefix.append('')
# Flush data (i.e send email if needed)
self.flush()
return
def del_loop_logger(self):
"""Delete the loop previsouly created and continues
"""
# Pop a prefix
self.prefix.pop()
self.reset_formatter()
# Flush data (i.e send email if needed)
self.flush()
return
def new_iteration(self, prefix):
"""When inside a loop logger, created a new iteration
"""
# Flush data for the current iteration
self.flush()
# Fix prefix
self.prefix[-1] = prefix
self.reset_formatter()
def reset_formatter(self):
"""Rebuild formatter for all handlers."""
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
def flush(self):
"""Flush data when dealing with iteration."""
for handler in self.handlers:
handler.flush()
def _set_min_level(self, handler_class, level):
"""Generic method to setLevel for handlers."""
if self._exist_handler(handler_class):
if not level:
self._delete_handler(handler_class)
else:
self._update_handler(handler_class, level=level)
elif level:
self._create_handler(handler_class, level)
def set_min_level_to_print(self, level):
"""Allow to change print level after creation
"""
self.min_log_level_to_print = level
handler_class = logging.StreamHandler
self._set_min_level(handler_class, level)
def set_min_level_to_save(self, level):
"""Allow to change save level after creation
"""
self.min_log_level_to_save = level
handler_class = logging.handlers.TimedRotatingFileHandler
self._set_min_level(handler_class, level)
def set_min_level_to_mail(self, level):
"""Allow to change mail level after creation
"""
self.min_log_level_to_mail = level
handler_class = AlkiviEmailHandler
self._set_min_level(handler_class, level)
def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level)
def _get_handler(self, handler_class):
"""Return an existing class of handler."""
element = None
for handler in self.handlers:
if isinstance(handler, handler_class):
element = handler
break
return element
def _exist_handler(self, handler_class):
"""Return True or False is the class exists."""
return self._get_handler(handler_class) is not None
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove)
def _update_handler(self, handler_class, level):
"""Update the level of an handler."""
handler = self._get_handler(handler_class)
handler.setLevel(level)
def _create_handler(self, handler_class, level):
"""Create an handler for at specific level."""
if handler_class == logging.StreamHandler:
handler = handler_class()
handler.setLevel(level)
elif handler_class == logging.handlers.SysLogHandler:
handler = handler_class(address='/dev/log')
handler.setLevel(level)
elif handler_class == logging.handlers.TimedRotatingFileHandler:
handler = handler_class(self.filename, when='midnight')
handler.setLevel(level)
elif handler_class == AlkiviEmailHandler:
handler = handler_class(mailhost='127.0.0.1',
fromaddr="%s@%s" % (USER, HOST),
toaddrs=self.emails,
level=self.min_log_level_to_mail)
# Needed, we want all logs to go there
handler.setLevel(0)
formatter = self.get_formatter(handler)
handler.setFormatter(formatter)
self.handlers.append(handler)
self.logger.addHandler(handler)
|
IntegralDefense/critsapi | critsapi/critsdbapi.py | CRITsDBAPI.connect | python | def connect(self):
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name] | Starts the mongodb connection. Must be called before anything else
will work. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L68-L74 | null | class CRITsDBAPI():
"""
Interface to the raw CRITs mongodb backend. This is typically much faster
than using the provided web API.
Most queries require a "collection" variable. The is a string of the
mongodb collection for the TLO in CRITs. It must follow the specific mongo
collection name for the corresponding TLO. The following are acceptable:
- indicators
- sample
- events
- backdoors
- exploits
- domains
- ips
"""
def __init__(self,
mongo_uri='',
mongo_host='localhost',
mongo_port=27017,
mongo_user='',
mongo_pass='',
db_name='crits'):
"""
Create our CRITsDBAPI object. You may specify a full mongodb uri or
the arguments individually.
Args:
mongo_uri: A full mongo uri in the form of:
mongodb://user:pass@mongo_server:port
mongo_host: The server name/ip where the mongo db is hosted
mongo_port: The port listening for connections
mongo_user: Mongo username (if using)
mongo_pass: Password for the user (if using)
db_name: The name of the CRITs database.
"""
# If the user provided a URI, we will use that. Otherwise we will build
# a URI from the other arguments.
if mongo_uri != '':
self.mongo_uri = mongo_uri
else:
# Build the authentication portion. Simple authentication only for
# now.
auth_str = ''
if mongo_user != '':
auth_str = mongo_user
if mongo_pass != '' and mongo_user != '':
auth_str = auth_str + ':' + mongo_pass
if auth_str != '':
auth_str = auth_str + '@'
# Build the URI
self.mongo_uri = 'mongodb://{}{}:{}'.format(auth_str, mongo_host,
mongo_port)
self.db_name = db_name
self.client = None
self.db = None
def find(self, collection, query):
"""
Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find(query)
return result
def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result = obj.find()
return result
def find_one(self, collection, query):
"""
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find_one(query)
return result
def find_distinct(self, collection, key):
"""
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
"""
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result
def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
"""
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
"""
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result
def remove_bucket_list_item(self, id, collection, item):
"""
Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$pull': {'bucket_list': item}}
)
return result
def add_bucket_list_item(self, id, collection, item):
"""
Adds an item to the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to add
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$addToSet': {'bucket_list': item}}
)
return result
def get_campaign_name_list(self):
"""
Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names
"""
campaigns = self.find('campaigns', {})
campaign_names = []
for campaign in campaigns:
if 'name' in campaign:
campaign_names.append(campaign['name'])
return campaign_names
|
IntegralDefense/critsapi | critsapi/critsdbapi.py | CRITsDBAPI.find | python | def find(self, collection, query):
obj = getattr(self.db, collection)
result = obj.find(query)
return result | Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L76-L89 | null | class CRITsDBAPI():
"""
Interface to the raw CRITs mongodb backend. This is typically much faster
than using the provided web API.
Most queries require a "collection" variable. The is a string of the
mongodb collection for the TLO in CRITs. It must follow the specific mongo
collection name for the corresponding TLO. The following are acceptable:
- indicators
- sample
- events
- backdoors
- exploits
- domains
- ips
"""
def __init__(self,
mongo_uri='',
mongo_host='localhost',
mongo_port=27017,
mongo_user='',
mongo_pass='',
db_name='crits'):
"""
Create our CRITsDBAPI object. You may specify a full mongodb uri or
the arguments individually.
Args:
mongo_uri: A full mongo uri in the form of:
mongodb://user:pass@mongo_server:port
mongo_host: The server name/ip where the mongo db is hosted
mongo_port: The port listening for connections
mongo_user: Mongo username (if using)
mongo_pass: Password for the user (if using)
db_name: The name of the CRITs database.
"""
# If the user provided a URI, we will use that. Otherwise we will build
# a URI from the other arguments.
if mongo_uri != '':
self.mongo_uri = mongo_uri
else:
# Build the authentication portion. Simple authentication only for
# now.
auth_str = ''
if mongo_user != '':
auth_str = mongo_user
if mongo_pass != '' and mongo_user != '':
auth_str = auth_str + ':' + mongo_pass
if auth_str != '':
auth_str = auth_str + '@'
# Build the URI
self.mongo_uri = 'mongodb://{}{}:{}'.format(auth_str, mongo_host,
mongo_port)
self.db_name = db_name
self.client = None
self.db = None
def connect(self):
"""
Starts the mongodb connection. Must be called before anything else
will work.
"""
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name]
def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result = obj.find()
return result
def find_one(self, collection, query):
"""
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find_one(query)
return result
def find_distinct(self, collection, key):
"""
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
"""
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result
def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
"""
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
"""
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result
def remove_bucket_list_item(self, id, collection, item):
"""
Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$pull': {'bucket_list': item}}
)
return result
def add_bucket_list_item(self, id, collection, item):
"""
Adds an item to the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to add
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$addToSet': {'bucket_list': item}}
)
return result
def get_campaign_name_list(self):
"""
Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names
"""
campaigns = self.find('campaigns', {})
campaign_names = []
for campaign in campaigns:
if 'name' in campaign:
campaign_names.append(campaign['name'])
return campaign_names
|
IntegralDefense/critsapi | critsapi/critsdbapi.py | CRITsDBAPI.find_all | python | def find_all(self, collection):
obj = getattr(self.db, collection)
result = obj.find()
return result | Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L91-L102 | null | class CRITsDBAPI():
"""
Interface to the raw CRITs mongodb backend. This is typically much faster
than using the provided web API.
Most queries require a "collection" variable. The is a string of the
mongodb collection for the TLO in CRITs. It must follow the specific mongo
collection name for the corresponding TLO. The following are acceptable:
- indicators
- sample
- events
- backdoors
- exploits
- domains
- ips
"""
def __init__(self,
mongo_uri='',
mongo_host='localhost',
mongo_port=27017,
mongo_user='',
mongo_pass='',
db_name='crits'):
"""
Create our CRITsDBAPI object. You may specify a full mongodb uri or
the arguments individually.
Args:
mongo_uri: A full mongo uri in the form of:
mongodb://user:pass@mongo_server:port
mongo_host: The server name/ip where the mongo db is hosted
mongo_port: The port listening for connections
mongo_user: Mongo username (if using)
mongo_pass: Password for the user (if using)
db_name: The name of the CRITs database.
"""
# If the user provided a URI, we will use that. Otherwise we will build
# a URI from the other arguments.
if mongo_uri != '':
self.mongo_uri = mongo_uri
else:
# Build the authentication portion. Simple authentication only for
# now.
auth_str = ''
if mongo_user != '':
auth_str = mongo_user
if mongo_pass != '' and mongo_user != '':
auth_str = auth_str + ':' + mongo_pass
if auth_str != '':
auth_str = auth_str + '@'
# Build the URI
self.mongo_uri = 'mongodb://{}{}:{}'.format(auth_str, mongo_host,
mongo_port)
self.db_name = db_name
self.client = None
self.db = None
def connect(self):
"""
Starts the mongodb connection. Must be called before anything else
will work.
"""
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name]
def find(self, collection, query):
"""
Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find(query)
return result
def find_one(self, collection, query):
"""
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find_one(query)
return result
def find_distinct(self, collection, key):
"""
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
"""
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result
def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
"""
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
"""
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result
def remove_bucket_list_item(self, id, collection, item):
"""
Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$pull': {'bucket_list': item}}
)
return result
def add_bucket_list_item(self, id, collection, item):
"""
Adds an item to the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to add
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$addToSet': {'bucket_list': item}}
)
return result
def get_campaign_name_list(self):
"""
Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names
"""
campaigns = self.find('campaigns', {})
campaign_names = []
for campaign in campaigns:
if 'name' in campaign:
campaign_names.append(campaign['name'])
return campaign_names
|
IntegralDefense/critsapi | critsapi/critsdbapi.py | CRITsDBAPI.find_one | python | def find_one(self, collection, query):
obj = getattr(self.db, collection)
result = obj.find_one(query)
return result | Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L104-L117 | null | class CRITsDBAPI():
"""
Interface to the raw CRITs mongodb backend. This is typically much faster
than using the provided web API.
Most queries require a "collection" variable. The is a string of the
mongodb collection for the TLO in CRITs. It must follow the specific mongo
collection name for the corresponding TLO. The following are acceptable:
- indicators
- sample
- events
- backdoors
- exploits
- domains
- ips
"""
def __init__(self,
mongo_uri='',
mongo_host='localhost',
mongo_port=27017,
mongo_user='',
mongo_pass='',
db_name='crits'):
"""
Create our CRITsDBAPI object. You may specify a full mongodb uri or
the arguments individually.
Args:
mongo_uri: A full mongo uri in the form of:
mongodb://user:pass@mongo_server:port
mongo_host: The server name/ip where the mongo db is hosted
mongo_port: The port listening for connections
mongo_user: Mongo username (if using)
mongo_pass: Password for the user (if using)
db_name: The name of the CRITs database.
"""
# If the user provided a URI, we will use that. Otherwise we will build
# a URI from the other arguments.
if mongo_uri != '':
self.mongo_uri = mongo_uri
else:
# Build the authentication portion. Simple authentication only for
# now.
auth_str = ''
if mongo_user != '':
auth_str = mongo_user
if mongo_pass != '' and mongo_user != '':
auth_str = auth_str + ':' + mongo_pass
if auth_str != '':
auth_str = auth_str + '@'
# Build the URI
self.mongo_uri = 'mongodb://{}{}:{}'.format(auth_str, mongo_host,
mongo_port)
self.db_name = db_name
self.client = None
self.db = None
def connect(self):
"""
Starts the mongodb connection. Must be called before anything else
will work.
"""
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name]
def find(self, collection, query):
"""
Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find(query)
return result
def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result = obj.find()
return result
def find_distinct(self, collection, key):
"""
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
"""
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result
def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
"""
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
"""
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result
def remove_bucket_list_item(self, id, collection, item):
"""
Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$pull': {'bucket_list': item}}
)
return result
def add_bucket_list_item(self, id, collection, item):
"""
Adds an item to the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to add
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$addToSet': {'bucket_list': item}}
)
return result
def get_campaign_name_list(self):
"""
Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names
"""
campaigns = self.find('campaigns', {})
campaign_names = []
for campaign in campaigns:
if 'name' in campaign:
campaign_names.append(campaign['name'])
return campaign_names
|
IntegralDefense/critsapi | critsapi/critsdbapi.py | CRITsDBAPI.find_distinct | python | def find_distinct(self, collection, key):
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result | Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L119-L132 | null | class CRITsDBAPI():
"""
Interface to the raw CRITs mongodb backend. This is typically much faster
than using the provided web API.
Most queries require a "collection" variable. The is a string of the
mongodb collection for the TLO in CRITs. It must follow the specific mongo
collection name for the corresponding TLO. The following are acceptable:
- indicators
- sample
- events
- backdoors
- exploits
- domains
- ips
"""
def __init__(self,
mongo_uri='',
mongo_host='localhost',
mongo_port=27017,
mongo_user='',
mongo_pass='',
db_name='crits'):
"""
Create our CRITsDBAPI object. You may specify a full mongodb uri or
the arguments individually.
Args:
mongo_uri: A full mongo uri in the form of:
mongodb://user:pass@mongo_server:port
mongo_host: The server name/ip where the mongo db is hosted
mongo_port: The port listening for connections
mongo_user: Mongo username (if using)
mongo_pass: Password for the user (if using)
db_name: The name of the CRITs database.
"""
# If the user provided a URI, we will use that. Otherwise we will build
# a URI from the other arguments.
if mongo_uri != '':
self.mongo_uri = mongo_uri
else:
# Build the authentication portion. Simple authentication only for
# now.
auth_str = ''
if mongo_user != '':
auth_str = mongo_user
if mongo_pass != '' and mongo_user != '':
auth_str = auth_str + ':' + mongo_pass
if auth_str != '':
auth_str = auth_str + '@'
# Build the URI
self.mongo_uri = 'mongodb://{}{}:{}'.format(auth_str, mongo_host,
mongo_port)
self.db_name = db_name
self.client = None
self.db = None
def connect(self):
"""
Starts the mongodb connection. Must be called before anything else
will work.
"""
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name]
def find(self, collection, query):
"""
Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find(query)
return result
def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result = obj.find()
return result
def find_one(self, collection, query):
"""
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find_one(query)
return result
def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
"""
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
"""
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result
def remove_bucket_list_item(self, id, collection, item):
"""
Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$pull': {'bucket_list': item}}
)
return result
def add_bucket_list_item(self, id, collection, item):
"""
Adds an item to the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to add
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$addToSet': {'bucket_list': item}}
)
return result
def get_campaign_name_list(self):
"""
Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names
"""
campaigns = self.find('campaigns', {})
campaign_names = []
for campaign in campaigns:
if 'name' in campaign:
campaign_names.append(campaign['name'])
return campaign_names
|
IntegralDefense/critsapi | critsapi/critsdbapi.py | CRITsDBAPI.add_embedded_campaign | python | def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result | Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L134-L171 | null | class CRITsDBAPI():
"""
Interface to the raw CRITs mongodb backend. This is typically much faster
than using the provided web API.
Most queries require a "collection" variable. The is a string of the
mongodb collection for the TLO in CRITs. It must follow the specific mongo
collection name for the corresponding TLO. The following are acceptable:
- indicators
- sample
- events
- backdoors
- exploits
- domains
- ips
"""
def __init__(self,
mongo_uri='',
mongo_host='localhost',
mongo_port=27017,
mongo_user='',
mongo_pass='',
db_name='crits'):
"""
Create our CRITsDBAPI object. You may specify a full mongodb uri or
the arguments individually.
Args:
mongo_uri: A full mongo uri in the form of:
mongodb://user:pass@mongo_server:port
mongo_host: The server name/ip where the mongo db is hosted
mongo_port: The port listening for connections
mongo_user: Mongo username (if using)
mongo_pass: Password for the user (if using)
db_name: The name of the CRITs database.
"""
# If the user provided a URI, we will use that. Otherwise we will build
# a URI from the other arguments.
if mongo_uri != '':
self.mongo_uri = mongo_uri
else:
# Build the authentication portion. Simple authentication only for
# now.
auth_str = ''
if mongo_user != '':
auth_str = mongo_user
if mongo_pass != '' and mongo_user != '':
auth_str = auth_str + ':' + mongo_pass
if auth_str != '':
auth_str = auth_str + '@'
# Build the URI
self.mongo_uri = 'mongodb://{}{}:{}'.format(auth_str, mongo_host,
mongo_port)
self.db_name = db_name
self.client = None
self.db = None
def connect(self):
"""
Starts the mongodb connection. Must be called before anything else
will work.
"""
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name]
def find(self, collection, query):
"""
Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find(query)
return result
def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result = obj.find()
return result
def find_one(self, collection, query):
"""
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find_one(query)
return result
def find_distinct(self, collection, key):
"""
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
"""
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result
def remove_bucket_list_item(self, id, collection, item):
"""
Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$pull': {'bucket_list': item}}
)
return result
def add_bucket_list_item(self, id, collection, item):
"""
Adds an item to the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to add
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$addToSet': {'bucket_list': item}}
)
return result
def get_campaign_name_list(self):
"""
Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names
"""
campaigns = self.find('campaigns', {})
campaign_names = []
for campaign in campaigns:
if 'name' in campaign:
campaign_names.append(campaign['name'])
return campaign_names
|
IntegralDefense/critsapi | critsapi/critsdbapi.py | CRITsDBAPI.remove_bucket_list_item | python | def remove_bucket_list_item(self, id, collection, item):
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$pull': {'bucket_list': item}}
)
return result | Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L173-L191 | null | class CRITsDBAPI():
"""
Interface to the raw CRITs mongodb backend. This is typically much faster
than using the provided web API.
Most queries require a "collection" variable. The is a string of the
mongodb collection for the TLO in CRITs. It must follow the specific mongo
collection name for the corresponding TLO. The following are acceptable:
- indicators
- sample
- events
- backdoors
- exploits
- domains
- ips
"""
def __init__(self,
mongo_uri='',
mongo_host='localhost',
mongo_port=27017,
mongo_user='',
mongo_pass='',
db_name='crits'):
"""
Create our CRITsDBAPI object. You may specify a full mongodb uri or
the arguments individually.
Args:
mongo_uri: A full mongo uri in the form of:
mongodb://user:pass@mongo_server:port
mongo_host: The server name/ip where the mongo db is hosted
mongo_port: The port listening for connections
mongo_user: Mongo username (if using)
mongo_pass: Password for the user (if using)
db_name: The name of the CRITs database.
"""
# If the user provided a URI, we will use that. Otherwise we will build
# a URI from the other arguments.
if mongo_uri != '':
self.mongo_uri = mongo_uri
else:
# Build the authentication portion. Simple authentication only for
# now.
auth_str = ''
if mongo_user != '':
auth_str = mongo_user
if mongo_pass != '' and mongo_user != '':
auth_str = auth_str + ':' + mongo_pass
if auth_str != '':
auth_str = auth_str + '@'
# Build the URI
self.mongo_uri = 'mongodb://{}{}:{}'.format(auth_str, mongo_host,
mongo_port)
self.db_name = db_name
self.client = None
self.db = None
def connect(self):
"""
Starts the mongodb connection. Must be called before anything else
will work.
"""
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name]
def find(self, collection, query):
"""
Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find(query)
return result
def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result = obj.find()
return result
def find_one(self, collection, query):
"""
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find_one(query)
return result
def find_distinct(self, collection, key):
"""
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
"""
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result
def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
"""
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
"""
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result
def add_bucket_list_item(self, id, collection, item):
"""
Adds an item to the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to add
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$addToSet': {'bucket_list': item}}
)
return result
def get_campaign_name_list(self):
"""
Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names
"""
campaigns = self.find('campaigns', {})
campaign_names = []
for campaign in campaigns:
if 'name' in campaign:
campaign_names.append(campaign['name'])
return campaign_names
|
IntegralDefense/critsapi | critsapi/critsdbapi.py | CRITsDBAPI.get_campaign_name_list | python | def get_campaign_name_list(self):
campaigns = self.find('campaigns', {})
campaign_names = []
for campaign in campaigns:
if 'name' in campaign:
campaign_names.append(campaign['name'])
return campaign_names | Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L213-L225 | [
"def find(self, collection, query):\n \"\"\"\n Search a collection for the query provided. Just a raw interface to\n mongo to do any query you want.\n\n Args:\n collection: The db collection. See main class documentation.\n query: A mongo find query.\n Returns:\n pymongo Cursor o... | class CRITsDBAPI():
"""
Interface to the raw CRITs mongodb backend. This is typically much faster
than using the provided web API.
Most queries require a "collection" variable. The is a string of the
mongodb collection for the TLO in CRITs. It must follow the specific mongo
collection name for the corresponding TLO. The following are acceptable:
- indicators
- sample
- events
- backdoors
- exploits
- domains
- ips
"""
def __init__(self,
mongo_uri='',
mongo_host='localhost',
mongo_port=27017,
mongo_user='',
mongo_pass='',
db_name='crits'):
"""
Create our CRITsDBAPI object. You may specify a full mongodb uri or
the arguments individually.
Args:
mongo_uri: A full mongo uri in the form of:
mongodb://user:pass@mongo_server:port
mongo_host: The server name/ip where the mongo db is hosted
mongo_port: The port listening for connections
mongo_user: Mongo username (if using)
mongo_pass: Password for the user (if using)
db_name: The name of the CRITs database.
"""
# If the user provided a URI, we will use that. Otherwise we will build
# a URI from the other arguments.
if mongo_uri != '':
self.mongo_uri = mongo_uri
else:
# Build the authentication portion. Simple authentication only for
# now.
auth_str = ''
if mongo_user != '':
auth_str = mongo_user
if mongo_pass != '' and mongo_user != '':
auth_str = auth_str + ':' + mongo_pass
if auth_str != '':
auth_str = auth_str + '@'
# Build the URI
self.mongo_uri = 'mongodb://{}{}:{}'.format(auth_str, mongo_host,
mongo_port)
self.db_name = db_name
self.client = None
self.db = None
def connect(self):
"""
Starts the mongodb connection. Must be called before anything else
will work.
"""
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name]
def find(self, collection, query):
"""
Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find(query)
return result
def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result = obj.find()
return result
def find_one(self, collection, query):
"""
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find_one(query)
return result
def find_distinct(self, collection, key):
"""
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
"""
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result
def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
"""
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
"""
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result
def remove_bucket_list_item(self, id, collection, item):
"""
Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$pull': {'bucket_list': item}}
)
return result
def add_bucket_list_item(self, id, collection, item):
"""
Adds an item to the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to add
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$addToSet': {'bucket_list': item}}
)
return result
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.add_indicator | python | def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None | Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L43-L115 | null | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.add_event | python | def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None | Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L117-L183 | [
"def get_events(self, event_title, regex=False):\n \"\"\"\n Search for events with the provided title\n\n Args:\n event_title: The title of the event\n Returns:\n An event JSON object returned from the server with the following:\n {\n \"meta\":{\n ... | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.add_sample_file | python | def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None | Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L185-L246 | null | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.add_sample_meta | python | def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None | Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L248-L309 | null | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.add_email | python | def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None | Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L311-L369 | null | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.add_backdoor | python | def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None | Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L371-L421 | null | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.add_profile_point | python | def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None | Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L423-L469 | null | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.get_events | python | def get_events(self, event_title, regex=False):
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None | Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L471-L501 | null | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.get_samples | python | def get_samples(self, md5='', sha1='', sha256=''):
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None | Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L503-L533 | null | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.get_backdoor | python | def get_backdoor(self, name, version=''):
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None | Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L563-L598 | null | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.has_relationship | python | def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False | Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L600-L629 | [
"def get_object(self, obj_id, obj_type):\n type_trans = self._type_translation(obj_type)\n get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)\n params = {\n 'username': self.username,\n 'api_key': self.api_key,\n }\n r = requests.get(get_url, params=params, proxies=self.proxies,... | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.forge_relationship | python | def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False | Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L631-L680 | [
"def _type_translation(self, str_type):\n \"\"\"\n Internal method to translate the named CRITs TLO type to a URL\n specific string.\n \"\"\"\n if str_type == 'Indicator':\n return 'indicators'\n if str_type == 'Domain':\n return 'domains'\n if str_type == 'IP':\n return 'i... | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.status_update | python | def status_update(self, crits_id, crits_type, status):
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False | Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L682-L721 | [
"def _type_translation(self, str_type):\n \"\"\"\n Internal method to translate the named CRITs TLO type to a URL\n specific string.\n \"\"\"\n if str_type == 'Indicator':\n return 'indicators'\n if str_type == 'Domain':\n return 'domains'\n if str_type == 'IP':\n return 'i... | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI.source_add_update | python | def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False | date must be in the format "%Y-%m-%d %H:%M:%S.%f" | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L723-L761 | [
"def _type_translation(self, str_type):\n \"\"\"\n Internal method to translate the named CRITs TLO type to a URL\n specific string.\n \"\"\"\n if str_type == 'Indicator':\n return 'indicators'\n if str_type == 'Domain':\n return 'domains'\n if str_type == 'IP':\n return 'i... | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def _type_translation(self, str_type):
"""
Internal method to translate the named CRITs TLO type to a URL
specific string.
"""
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type))
|
IntegralDefense/critsapi | critsapi/critsapi.py | CRITsAPI._type_translation | python | def _type_translation(self, str_type):
if str_type == 'Indicator':
return 'indicators'
if str_type == 'Domain':
return 'domains'
if str_type == 'IP':
return 'ips'
if str_type == 'Sample':
return 'samples'
if str_type == 'Event':
return 'events'
if str_type == 'Actor':
return 'actors'
if str_type == 'Email':
return 'emails'
if str_type == 'Backdoor':
return 'backdoors'
raise CRITsInvalidTypeError('Invalid object type specified: '
'{}'.format(str_type)) | Internal method to translate the named CRITs TLO type to a URL
specific string. | train | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsapi.py#L763-L786 | null | class CRITsAPI():
def __init__(self, api_url='', api_key='', username='', verify=True,
proxies={}):
self.url = api_url
if self.url[-1] == '/':
self.url = self.url[:-1]
self.api_key = api_key
self.username = username
self.verify = verify
self.proxies = proxies
def get_object(self, obj_id, obj_type):
type_trans = self._type_translation(obj_type)
get_url = '{}/{}/{}/'.format(self.url, type_trans, obj_id)
params = {
'username': self.username,
'api_key': self.api_key,
}
r = requests.get(get_url, params=params, proxies=self.proxies,
verify=self.verify)
if r.status_code == 200:
return json.loads(r.text)
else:
print('Status code returned for query {}, '
'was: {}'.format(get_url, r.status_code))
return None
def add_indicator(self,
value,
itype,
source='',
reference='',
method='',
campaign=None,
confidence=None,
bucket_list=[],
ticket='',
add_domain=True,
add_relationship=True,
indicator_confidence='unknown',
indicator_impact='unknown',
threat_type=itt.UNKNOWN,
attack_type=iat.UNKNOWN,
description=''):
"""
Add an indicator to CRITs
Args:
value: The indicator itself
itype: The overall indicator type. See your CRITs vocabulary
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
add_domain: If the indicator is a domain, it will automatically
add a domain TLO object.
add_relationship: If add_domain is True, this will create a
relationship between the indicator and domain TLOs
indicator_confidence: The confidence of the indicator
indicator_impact: The impact of the indicator
threat_type: The threat type of the indicator
attack_type: the attack type of the indicator
description: A description of this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'add_domain': True,
'add_relationship': True,
'indicator_confidence': indicator_confidence,
'indicator_impact': indicator_impact,
'type': itype,
'threat_type': threat_type,
'attack_type': attack_type,
'value': value,
'description': description,
}
r = requests.post("{0}/indicators/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Indicator uploaded successfully - {}".format(value))
ind = json.loads(r.text)
return ind
return None
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=None):
"""
Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See your CRITs vocabulary.
method: The method for obtaining the event.
description: A text description of the event.
bucket_list: A list of bucket list items to add
campaign: An associated campaign
confidence: The campaign confidence
date: A datetime.datetime object of when the event occurred.
Returns:
A JSON event object or None if there was an error.
"""
# Check to see if the event already exists
events = self.get_events(event_title)
if events is not None:
if events['meta']['total_count'] == 1:
return events['objects'][0]
if events['meta']['total_count'] > 1:
log.error('Multiple events found while trying to add the event'
': {}'.format(event_title))
return None
# Now we can create the event
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'campaign': campaign,
'confidence': confidence,
'description': description,
'event_type': event_type,
'date': date,
'title': event_title,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{}/events/'.format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Event created: {}'.format(event_title))
json_obj = json.loads(r.text)
if 'id' not in json_obj:
log.error('Error adding event. id not returned.')
return None
return json_obj
else:
log.error('Event creation failed with status code: '
'{}'.format(r.status_code))
return None
def add_sample_file(self,
sample_path,
source,
reference,
method='',
file_format='raw',
file_password='',
sample_name='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a file sample. For meta data only use add_sample_meta.
Args:
sample_path: The path on disk of the sample to upload
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
file_format: Must be raw, zip, or rar.
file_password: The password of a zip or rar archived sample
sample_name: Specify a filename for the sample rather than using
the name on disk
campaign: An associated campaign
confidence: The campaign confidence
description: A text description of the sample
bucket_list: A list of bucket list items to add
Returns:
A JSON sample object or None if there was an error.
"""
if os.path.isfile(sample_path):
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filetype': file_format,
'upload_type': 'file',
'campaign': campaign,
'confidence': confidence,
'description': description,
'bucket_list': ','.join(bucket_list),
}
if sample_name != '':
data['filename'] = sample_name
with open(sample_path, 'rb') as fdata:
if file_password:
data['password'] = file_password
r = requests.post('{0}/samples/'.format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_sample_meta(self,
source,
reference,
method='',
filename='',
md5='',
sha1='',
sha256='',
size='',
mimetype='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Adds a metadata sample. To add an actual file, use add_sample_file.
Args:
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the sample.
filename: The name of the file.
md5: An MD5 hash of the file.
sha1: SHA1 hash of the file.
sha256: SHA256 hash of the file.
size: size of the file.
mimetype: The mimetype of the file.
campaign: An associated campaign
confidence: The campaign confidence
bucket_list: A list of bucket list items to add
upload_type: Either 'file' or 'meta'
Returns:
A JSON sample object or None if there was an error.
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'filename': filename,
'md5': md5,
'sha1': sha1,
'sha256': sha256,
'size': size,
'mimetype': mimetype,
'upload_type': 'meta',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
}
r = requests.post('{0}/samples/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_email(self,
email_path,
source,
reference,
method='',
upload_type='raw',
campaign='',
confidence='',
description='',
bucket_list=[],
password=''):
"""
Add an email object to CRITs. Only RAW, MSG, and EML are supported
currently.
Args:
email_path: The path on disk of the email.
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the email.
upload_type: 'raw', 'eml', or 'msg'
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
password: A password for a 'msg' type.
Returns:
A JSON email object from CRITs or None if there was an error.
"""
if not os.path.isfile(email_path):
log.error('{} is not a file'.format(email_path))
return None
with open(email_path, 'rb') as fdata:
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'upload_type': upload_type,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
if password:
data['password'] = password
r = requests.post("{0}/emails/".format(self.url),
data=data,
files={'filedata': fdata},
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
print('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_backdoor(self,
backdoor_name,
source,
reference,
method='',
aliases=[],
version='',
campaign='',
confidence='',
description='',
bucket_list=[]):
"""
Add a backdoor object to CRITs.
Args:
backdoor_name: The primary name of the backdoor
source: Source of the information
reference: A reference where more information can be found
method: The method for obtaining the backdoor information.
aliases: List of aliases for the backdoor.
version: Version
campaign: An associated campaign
confidence: The campaign confidence
description: A description of the email
bucket_list: A list of bucket list items to add
"""
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': method,
'name': backdoor_name,
'aliases': ','.join(aliases),
'version': version,
'campaign': campaign,
'confidence': confidence,
'bucket_list': bucket_list,
'description': description,
}
r = requests.post('{0}/backdoors/'.format(self.url),
data=data,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
return result_data
else:
log.error('Error with status code {0} and message '
'{1}'.format(r.status_code, r.text))
return None
def add_profile_point(self,
value,
source='',
reference='',
method='',
ticket='',
campaign=None,
confidence=None,
bucket_list=[]):
"""
Add an indicator to CRITs
Args:
value: The profile point itself
source: Source of the information
reference: A reference where more information can be found
method: The method for adding this indicator
campaign: If the indicator has a campaign, add it here
confidence: The confidence this indicator belongs to the given
campaign
bucket_list: Bucket list items for this indicator
ticket: A ticket associated with this indicator
Returns:
JSON object for the indicator or None if it failed.
"""
# Time to upload these indicators
data = {
'api_key': self.api_key,
'username': self.username,
'source': source,
'reference': reference,
'method': '',
'campaign': campaign,
'confidence': confidence,
'bucket_list': ','.join(bucket_list),
'ticket': ticket,
'value': value,
}
r = requests.post("{0}/profile_points/".format(self.url), data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug("Profile Point uploaded successfully - {}".format(value))
pp = json.loads(r.text)
return pp
return None
def get_events(self, event_title, regex=False):
"""
Search for events with the provided title
Args:
event_title: The title of the event
Returns:
An event JSON object returned from the server with the following:
{
"meta":{
"limit": 20, "next": null, "offset": 0,
"previous": null, "total_count": 3
},
"objects": [{}, {}, etc]
}
or None if an error occurred.
"""
regex_val = 0
if regex:
regex_val = 1
r = requests.get('{0}/events/?api_key={1}&username={2}&c-title='
'{3}®ex={4}'.format(self.url, self.api_key,
self.username, event_title,
regex_val), verify=self.verify)
if r.status_code == 200:
json_obj = json.loads(r.text)
return json_obj
else:
log.error('Non-200 status code from get_event: '
'{}'.format(r.status_code))
return None
def get_samples(self, md5='', sha1='', sha256=''):
"""
Searches for a sample in CRITs. Currently only hashes allowed.
Args:
md5: md5sum
sha1: sha1sum
sha256: sha256sum
Returns:
JSON response or None if not found
"""
params = {'api_key': self.api_key, 'username': self.username}
if md5:
params['c-md5'] = md5
if sha1:
params['c-sha1'] = sha1
if sha256:
params['c-sha256'] = sha256
r = requests.get('{0}/samples/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoors(self, name):
"""
Searches a backdoor given the name. Returns multiple results
Args:
name: The name of the backdoor. This can be an alias.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' in result_data:
if 'total_count' in result_data['meta']:
if result_data['meta']['total_count'] > 0:
return result_data
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def get_backdoor(self, name, version=''):
"""
Searches for the backdoor based on name and version.
Args:
name: The name of the backdoor. This can be an alias.
version: The version.
Returns:
Returns a JSON object contain one or more backdoor results or
None if not found.
"""
params = {}
params['or'] = 1
params['c-name'] = name
params['c-aliases__in'] = name
r = requests.get('{0}/backdoors/'.format(self.url),
params=params,
verify=self.verify,
proxies=self.proxies)
if r.status_code == 200:
result_data = json.loads(r.text)
if 'meta' not in result_data:
return None
if 'total_count' not in result_data['meta']:
return None
if result_data['meta']['total_count'] <= 0:
return None
if 'objects' not in result_data:
return None
for backdoor in result_data['objects']:
if 'version' in backdoor:
if backdoor['version'] == version:
return backdoor
else:
log.error('Non-200 status code: {}'.format(r.status_code))
return None
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
"""
Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False if the relationship exists or not.
"""
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and type {}'.format(left_id,
left_type))
if 'relationships' not in data:
return False
for relationship in data['relationships']:
if relationship['relationship'] != rel_type:
continue
if relationship['value'] != right_id:
continue
if relationship['type'] != right_type:
continue
return True
return False
def forge_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To', rel_date=None,
rel_confidence='high', rel_reason=''):
"""
Forges a relationship between two TLOs.
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
rel_date: datetime.datetime object for the date of the
relationship. If left blank, it will be datetime.datetime.now()
rel_confidence: The relationship confidence (high, medium, low)
rel_reason: Reason for the relationship.
Returns:
True if the relationship was created. False otherwise.
"""
if not rel_date:
rel_date = datetime.datetime.now()
type_trans = self._type_translation(left_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'forge_relationship',
'right_type': right_type,
'right_id': right_id,
'rel_type': rel_type,
'rel_date': rel_date,
'rel_confidence': rel_confidence,
'rel_reason': rel_reason
}
r = requests.patch(submit_url, params=params, data=data,
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Relationship built successfully: {0} <-> '
'{1}'.format(left_id, right_id))
return True
else:
log.error('Error with status code {0} and message {1} between '
'these indicators: {2} <-> '
'{3}'.format(r.status_code, r.text, left_id, right_id))
return False
def status_update(self, crits_id, crits_type, status):
"""
Update the status of the TLO. By default, the options are:
- New
- In Progress
- Analyzed
- Deprecated
Args:
crits_id: The object id of the TLO
crits_type: The type of TLO. This must be 'Indicator', ''
status: The status to change.
Returns:
True if the status was updated. False otherwise.
Raises:
CRITsInvalidTypeError
"""
obj_type = self._type_translation(crits_type)
patch_url = "{0}/{1}/{2}/".format(self.url, obj_type, crits_id)
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'status_update',
'value': status,
}
r = requests.patch(patch_url, params=params, data=data,
verify=self.verify, proxies=self.proxies)
if r.status_code == 200:
log.debug('Object {} set to {}'.format(crits_id, status))
return True
else:
log.error('Attempted to set object id {} to '
'Informational, but did not receive a '
'200'.format(crits_id))
log.error('Error message was: {}'.format(r.text))
return False
def source_add_update(self, crits_id, crits_type, source,
action_type='add', method='', reference='',
date=None):
"""
date must be in the format "%Y-%m-%d %H:%M:%S.%f"
"""
type_trans = self._type_translation(crits_type)
submit_url = '{}/{}/{}/'.format(self.url, type_trans, crits_id)
if date is None:
date = datetime.datetime.now()
date = datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S.%f')
params = {
'api_key': self.api_key,
'username': self.username,
}
data = {
'action': 'source_add_update',
'action_type': action_type,
'source': source,
'method': method,
'reference': reference,
'date': date
}
r = requests.patch(submit_url, params=params, data=json.dumps(data),
proxies=self.proxies, verify=self.verify)
if r.status_code == 200:
log.debug('Source {0} added successfully to {1} '
'{2}'.format(source, crits_type, crits_id))
return True
else:
log.error('Error with status code {0} and message {1} for '
'type {2} and id {3} and source '
'{4}'.format(r.status_code, r.text, crits_type,
crits_id, source))
return False
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/related.py | DynamicRelatedFieldMixin.get_name_for | python | def get_name_for(self, dynamic_part):
dynamic_part = self.from_python(dynamic_part)
return super(DynamicRelatedFieldMixin, self).get_name_for(dynamic_part) | Return the name for the current dynamic field, accepting a limpyd
instance for the dynamic part | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/related.py#L67-L73 | null | class DynamicRelatedFieldMixin(DynamicFieldMixin):
"""
As the related name must be unique for a relation between two objects, we
have to make a fake one for this dynamic field, based on its dynamic name.
"""
def _get_related_name(self):
if self.dynamic_version_of is not None:
self.related_name = '%s__%s__%s' % (
self.dynamic_version_of.related_name,
re_identifier.sub('_', self.dynamic_part),
id(self)
)
return super(DynamicRelatedFieldMixin, self)._get_related_name()
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin._attach_to_model | python | def _attach_to_model(self, model):
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self) | Check that the model can handle dynamic fields | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L46-L64 | null | class DynamicFieldMixin(object):
"""
This mixin adds a main functionnality to each domain it's attached to: the
ability to have an unlimited number of fields. If a field is asked in the
model which not exists, it will ask to each of its dynamic fields if it
can accepts the wanted field name. If True, a new field is created on the
fly with this new name.
The matching is done using the "pattern" argument to pass when declaring
the dynamic field on the model. This argument must be a regular expression
(or a string, but in both cases the "re.compile" method will be called).
If not defined, the default pattern will be used: ^basefieldname_\d+$ (here,
basefieldname is the name used to declare the field on the model)
To to the reverse operation, ie get a field name based on a dynamic part,
the "format" argument can be passed when declaring the dynamic field on the
model. Both pattern and format must match. If not defined, the default
format is 'basefieldname_%s'.
"""
def __init__(self, *args, **kwargs):
"""
Handle the new optional "pattern" attribute
"""
self._pattern = kwargs.pop('pattern', None)
if self._pattern:
self._pattern = re.compile(self._pattern)
self._format = kwargs.pop('format', None)
self.dynamic_version_of = None
super(DynamicFieldMixin, self).__init__(*args, **kwargs)
@property
def pattern(self):
"""
Return the pattern used to check if a field name can be accepted by this
dynamic field. Use a default one ('^fieldname_(.+)$') if not set when
the field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.pattern
if not self._pattern:
self._pattern = re.compile('^%s_(.+)$' % self.name)
return self._pattern
@property
def format(self):
"""
Return the format used to create the name of a variation of the current
dynamic field. Use a default one ('fieldname_%s') if not set when the
field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.format
if not self._format:
self._format = '%s_%%s' % self.name
return self._format
@property
def dynamic_part(self):
if not hasattr(self, '_dynamic_part'):
self._dynamic_part = self.pattern.match(self.name).groups()[0]
return self._dynamic_part
def _accept_name(self, field_name):
"""
Return True if the given field name can be accepted by this dynamic field
"""
return bool(self.pattern.match(field_name))
def __copy__(self):
"""
Copy the _pattern attribute to the new copy of this field
"""
new_copy = super(DynamicFieldMixin, self).__copy__()
new_copy._pattern = self._pattern
return new_copy
def _create_dynamic_version(self):
"""
Create a copy of the field and set it as a dynamic version of it.
"""
new_field = copy(self)
new_field.dynamic_version_of = self
return new_field
def _base_field(self):
"""
Return the base field (the one without variable part) of the current one.
"""
return self.dynamic_version_of or self
@property
def _inventory(self):
"""
Return (and create if needed) the internal inventory field, a SetField
used to track all dynamic versions used on a specific instance.
"""
if self.dynamic_version_of:
return self.dynamic_version_of._inventory
if not hasattr(self, '_inventory_field'):
self._inventory_field = limpyd_fields.SetField()
self._inventory_field._attach_to_model(self._model)
self._inventory_field._attach_to_instance(self._instance)
self._inventory_field.lockable = True
self._inventory.name = self.name
return self._inventory_field
def _call_command(self, name, *args, **kwargs):
"""
If a command is called for the main field, without dynamic part, an
ImplementationError is raised: commands can only be applied on dynamic
versions.
On dynamic versions, if the command is a modifier, we add the version in
the inventory.
"""
if self.dynamic_version_of is None:
raise ImplementationError('The main version of a dynamic field cannot accept commands')
try:
result = super(DynamicFieldMixin, self)._call_command(name, *args, **kwargs)
except:
raise
else:
if name in self.available_modifiers and name not in ('delete', 'hdel'):
self._inventory.sadd(self.dynamic_part)
return result
def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part)
def _delete_dynamic_versions(self):
"""
Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory.
"""
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete()
def get_name_for(self, dynamic_part):
"""
Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name.
"""
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name
def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name)
__call__ = get_for
def scan_keys(self, match=None, count=None):
if not hasattr(self, '_instance'):
raise ImplementationError('"scan_keys" can be used only on a bound field')
name = self.format % '*'
pattern = self.make_key(
self._instance._name,
self._instance.pk.get(),
name,
)
return self.database.scan_keys(pattern, count)
def sscan(self, match=None, count=None):
return self._inventory.sscan(match, count)
scan_versions = sscan
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin.pattern | python | def pattern(self):
if self.dynamic_version_of is not None:
return self.dynamic_version_of.pattern
if not self._pattern:
self._pattern = re.compile('^%s_(.+)$' % self.name)
return self._pattern | Return the pattern used to check if a field name can be accepted by this
dynamic field. Use a default one ('^fieldname_(.+)$') if not set when
the field was initialized | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L67-L78 | null | class DynamicFieldMixin(object):
"""
This mixin adds a main functionnality to each domain it's attached to: the
ability to have an unlimited number of fields. If a field is asked in the
model which not exists, it will ask to each of its dynamic fields if it
can accepts the wanted field name. If True, a new field is created on the
fly with this new name.
The matching is done using the "pattern" argument to pass when declaring
the dynamic field on the model. This argument must be a regular expression
(or a string, but in both cases the "re.compile" method will be called).
If not defined, the default pattern will be used: ^basefieldname_\d+$ (here,
basefieldname is the name used to declare the field on the model)
To to the reverse operation, ie get a field name based on a dynamic part,
the "format" argument can be passed when declaring the dynamic field on the
model. Both pattern and format must match. If not defined, the default
format is 'basefieldname_%s'.
"""
def __init__(self, *args, **kwargs):
"""
Handle the new optional "pattern" attribute
"""
self._pattern = kwargs.pop('pattern', None)
if self._pattern:
self._pattern = re.compile(self._pattern)
self._format = kwargs.pop('format', None)
self.dynamic_version_of = None
super(DynamicFieldMixin, self).__init__(*args, **kwargs)
def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self)
@property
@property
def format(self):
"""
Return the format used to create the name of a variation of the current
dynamic field. Use a default one ('fieldname_%s') if not set when the
field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.format
if not self._format:
self._format = '%s_%%s' % self.name
return self._format
@property
def dynamic_part(self):
if not hasattr(self, '_dynamic_part'):
self._dynamic_part = self.pattern.match(self.name).groups()[0]
return self._dynamic_part
def _accept_name(self, field_name):
"""
Return True if the given field name can be accepted by this dynamic field
"""
return bool(self.pattern.match(field_name))
def __copy__(self):
"""
Copy the _pattern attribute to the new copy of this field
"""
new_copy = super(DynamicFieldMixin, self).__copy__()
new_copy._pattern = self._pattern
return new_copy
def _create_dynamic_version(self):
"""
Create a copy of the field and set it as a dynamic version of it.
"""
new_field = copy(self)
new_field.dynamic_version_of = self
return new_field
def _base_field(self):
"""
Return the base field (the one without variable part) of the current one.
"""
return self.dynamic_version_of or self
@property
def _inventory(self):
"""
Return (and create if needed) the internal inventory field, a SetField
used to track all dynamic versions used on a specific instance.
"""
if self.dynamic_version_of:
return self.dynamic_version_of._inventory
if not hasattr(self, '_inventory_field'):
self._inventory_field = limpyd_fields.SetField()
self._inventory_field._attach_to_model(self._model)
self._inventory_field._attach_to_instance(self._instance)
self._inventory_field.lockable = True
self._inventory.name = self.name
return self._inventory_field
def _call_command(self, name, *args, **kwargs):
"""
If a command is called for the main field, without dynamic part, an
ImplementationError is raised: commands can only be applied on dynamic
versions.
On dynamic versions, if the command is a modifier, we add the version in
the inventory.
"""
if self.dynamic_version_of is None:
raise ImplementationError('The main version of a dynamic field cannot accept commands')
try:
result = super(DynamicFieldMixin, self)._call_command(name, *args, **kwargs)
except:
raise
else:
if name in self.available_modifiers and name not in ('delete', 'hdel'):
self._inventory.sadd(self.dynamic_part)
return result
def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part)
def _delete_dynamic_versions(self):
"""
Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory.
"""
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete()
def get_name_for(self, dynamic_part):
"""
Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name.
"""
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name
def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name)
__call__ = get_for
def scan_keys(self, match=None, count=None):
if not hasattr(self, '_instance'):
raise ImplementationError('"scan_keys" can be used only on a bound field')
name = self.format % '*'
pattern = self.make_key(
self._instance._name,
self._instance.pk.get(),
name,
)
return self.database.scan_keys(pattern, count)
def sscan(self, match=None, count=None):
return self._inventory.sscan(match, count)
scan_versions = sscan
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin.format | python | def format(self):
if self.dynamic_version_of is not None:
return self.dynamic_version_of.format
if not self._format:
self._format = '%s_%%s' % self.name
return self._format | Return the format used to create the name of a variation of the current
dynamic field. Use a default one ('fieldname_%s') if not set when the
field was initialized | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L81-L92 | null | class DynamicFieldMixin(object):
"""
This mixin adds a main functionnality to each domain it's attached to: the
ability to have an unlimited number of fields. If a field is asked in the
model which not exists, it will ask to each of its dynamic fields if it
can accepts the wanted field name. If True, a new field is created on the
fly with this new name.
The matching is done using the "pattern" argument to pass when declaring
the dynamic field on the model. This argument must be a regular expression
(or a string, but in both cases the "re.compile" method will be called).
If not defined, the default pattern will be used: ^basefieldname_\d+$ (here,
basefieldname is the name used to declare the field on the model)
To to the reverse operation, ie get a field name based on a dynamic part,
the "format" argument can be passed when declaring the dynamic field on the
model. Both pattern and format must match. If not defined, the default
format is 'basefieldname_%s'.
"""
def __init__(self, *args, **kwargs):
"""
Handle the new optional "pattern" attribute
"""
self._pattern = kwargs.pop('pattern', None)
if self._pattern:
self._pattern = re.compile(self._pattern)
self._format = kwargs.pop('format', None)
self.dynamic_version_of = None
super(DynamicFieldMixin, self).__init__(*args, **kwargs)
def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self)
@property
def pattern(self):
"""
Return the pattern used to check if a field name can be accepted by this
dynamic field. Use a default one ('^fieldname_(.+)$') if not set when
the field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.pattern
if not self._pattern:
self._pattern = re.compile('^%s_(.+)$' % self.name)
return self._pattern
@property
@property
def dynamic_part(self):
if not hasattr(self, '_dynamic_part'):
self._dynamic_part = self.pattern.match(self.name).groups()[0]
return self._dynamic_part
def _accept_name(self, field_name):
"""
Return True if the given field name can be accepted by this dynamic field
"""
return bool(self.pattern.match(field_name))
def __copy__(self):
"""
Copy the _pattern attribute to the new copy of this field
"""
new_copy = super(DynamicFieldMixin, self).__copy__()
new_copy._pattern = self._pattern
return new_copy
def _create_dynamic_version(self):
"""
Create a copy of the field and set it as a dynamic version of it.
"""
new_field = copy(self)
new_field.dynamic_version_of = self
return new_field
def _base_field(self):
"""
Return the base field (the one without variable part) of the current one.
"""
return self.dynamic_version_of or self
@property
def _inventory(self):
"""
Return (and create if needed) the internal inventory field, a SetField
used to track all dynamic versions used on a specific instance.
"""
if self.dynamic_version_of:
return self.dynamic_version_of._inventory
if not hasattr(self, '_inventory_field'):
self._inventory_field = limpyd_fields.SetField()
self._inventory_field._attach_to_model(self._model)
self._inventory_field._attach_to_instance(self._instance)
self._inventory_field.lockable = True
self._inventory.name = self.name
return self._inventory_field
def _call_command(self, name, *args, **kwargs):
"""
If a command is called for the main field, without dynamic part, an
ImplementationError is raised: commands can only be applied on dynamic
versions.
On dynamic versions, if the command is a modifier, we add the version in
the inventory.
"""
if self.dynamic_version_of is None:
raise ImplementationError('The main version of a dynamic field cannot accept commands')
try:
result = super(DynamicFieldMixin, self)._call_command(name, *args, **kwargs)
except:
raise
else:
if name in self.available_modifiers and name not in ('delete', 'hdel'):
self._inventory.sadd(self.dynamic_part)
return result
def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part)
def _delete_dynamic_versions(self):
"""
Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory.
"""
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete()
def get_name_for(self, dynamic_part):
"""
Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name.
"""
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name
def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name)
__call__ = get_for
def scan_keys(self, match=None, count=None):
if not hasattr(self, '_instance'):
raise ImplementationError('"scan_keys" can be used only on a bound field')
name = self.format % '*'
pattern = self.make_key(
self._instance._name,
self._instance.pk.get(),
name,
)
return self.database.scan_keys(pattern, count)
def sscan(self, match=None, count=None):
return self._inventory.sscan(match, count)
scan_versions = sscan
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin._inventory | python | def _inventory(self):
if self.dynamic_version_of:
return self.dynamic_version_of._inventory
if not hasattr(self, '_inventory_field'):
self._inventory_field = limpyd_fields.SetField()
self._inventory_field._attach_to_model(self._model)
self._inventory_field._attach_to_instance(self._instance)
self._inventory_field.lockable = True
self._inventory.name = self.name
return self._inventory_field | Return (and create if needed) the internal inventory field, a SetField
used to track all dynamic versions used on a specific instance. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L129-L144 | null | class DynamicFieldMixin(object):
"""
This mixin adds a main functionnality to each domain it's attached to: the
ability to have an unlimited number of fields. If a field is asked in the
model which not exists, it will ask to each of its dynamic fields if it
can accepts the wanted field name. If True, a new field is created on the
fly with this new name.
The matching is done using the "pattern" argument to pass when declaring
the dynamic field on the model. This argument must be a regular expression
(or a string, but in both cases the "re.compile" method will be called).
If not defined, the default pattern will be used: ^basefieldname_\d+$ (here,
basefieldname is the name used to declare the field on the model)
To to the reverse operation, ie get a field name based on a dynamic part,
the "format" argument can be passed when declaring the dynamic field on the
model. Both pattern and format must match. If not defined, the default
format is 'basefieldname_%s'.
"""
def __init__(self, *args, **kwargs):
"""
Handle the new optional "pattern" attribute
"""
self._pattern = kwargs.pop('pattern', None)
if self._pattern:
self._pattern = re.compile(self._pattern)
self._format = kwargs.pop('format', None)
self.dynamic_version_of = None
super(DynamicFieldMixin, self).__init__(*args, **kwargs)
def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self)
@property
def pattern(self):
"""
Return the pattern used to check if a field name can be accepted by this
dynamic field. Use a default one ('^fieldname_(.+)$') if not set when
the field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.pattern
if not self._pattern:
self._pattern = re.compile('^%s_(.+)$' % self.name)
return self._pattern
@property
def format(self):
"""
Return the format used to create the name of a variation of the current
dynamic field. Use a default one ('fieldname_%s') if not set when the
field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.format
if not self._format:
self._format = '%s_%%s' % self.name
return self._format
@property
def dynamic_part(self):
if not hasattr(self, '_dynamic_part'):
self._dynamic_part = self.pattern.match(self.name).groups()[0]
return self._dynamic_part
def _accept_name(self, field_name):
"""
Return True if the given field name can be accepted by this dynamic field
"""
return bool(self.pattern.match(field_name))
def __copy__(self):
"""
Copy the _pattern attribute to the new copy of this field
"""
new_copy = super(DynamicFieldMixin, self).__copy__()
new_copy._pattern = self._pattern
return new_copy
def _create_dynamic_version(self):
"""
Create a copy of the field and set it as a dynamic version of it.
"""
new_field = copy(self)
new_field.dynamic_version_of = self
return new_field
def _base_field(self):
"""
Return the base field (the one without variable part) of the current one.
"""
return self.dynamic_version_of or self
@property
def _call_command(self, name, *args, **kwargs):
"""
If a command is called for the main field, without dynamic part, an
ImplementationError is raised: commands can only be applied on dynamic
versions.
On dynamic versions, if the command is a modifier, we add the version in
the inventory.
"""
if self.dynamic_version_of is None:
raise ImplementationError('The main version of a dynamic field cannot accept commands')
try:
result = super(DynamicFieldMixin, self)._call_command(name, *args, **kwargs)
except:
raise
else:
if name in self.available_modifiers and name not in ('delete', 'hdel'):
self._inventory.sadd(self.dynamic_part)
return result
def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part)
def _delete_dynamic_versions(self):
"""
Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory.
"""
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete()
def get_name_for(self, dynamic_part):
"""
Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name.
"""
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name
def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name)
__call__ = get_for
def scan_keys(self, match=None, count=None):
if not hasattr(self, '_instance'):
raise ImplementationError('"scan_keys" can be used only on a bound field')
name = self.format % '*'
pattern = self.make_key(
self._instance._name,
self._instance.pk.get(),
name,
)
return self.database.scan_keys(pattern, count)
def sscan(self, match=None, count=None):
return self._inventory.sscan(match, count)
scan_versions = sscan
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin._call_command | python | def _call_command(self, name, *args, **kwargs):
if self.dynamic_version_of is None:
raise ImplementationError('The main version of a dynamic field cannot accept commands')
try:
result = super(DynamicFieldMixin, self)._call_command(name, *args, **kwargs)
except:
raise
else:
if name in self.available_modifiers and name not in ('delete', 'hdel'):
self._inventory.sadd(self.dynamic_part)
return result | If a command is called for the main field, without dynamic part, an
ImplementationError is raised: commands can only be applied on dynamic
versions.
On dynamic versions, if the command is a modifier, we add the version in
the inventory. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L146-L163 | null | class DynamicFieldMixin(object):
"""
This mixin adds a main functionnality to each domain it's attached to: the
ability to have an unlimited number of fields. If a field is asked in the
model which not exists, it will ask to each of its dynamic fields if it
can accepts the wanted field name. If True, a new field is created on the
fly with this new name.
The matching is done using the "pattern" argument to pass when declaring
the dynamic field on the model. This argument must be a regular expression
(or a string, but in both cases the "re.compile" method will be called).
If not defined, the default pattern will be used: ^basefieldname_\d+$ (here,
basefieldname is the name used to declare the field on the model)
To to the reverse operation, ie get a field name based on a dynamic part,
the "format" argument can be passed when declaring the dynamic field on the
model. Both pattern and format must match. If not defined, the default
format is 'basefieldname_%s'.
"""
def __init__(self, *args, **kwargs):
"""
Handle the new optional "pattern" attribute
"""
self._pattern = kwargs.pop('pattern', None)
if self._pattern:
self._pattern = re.compile(self._pattern)
self._format = kwargs.pop('format', None)
self.dynamic_version_of = None
super(DynamicFieldMixin, self).__init__(*args, **kwargs)
def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self)
@property
def pattern(self):
"""
Return the pattern used to check if a field name can be accepted by this
dynamic field. Use a default one ('^fieldname_(.+)$') if not set when
the field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.pattern
if not self._pattern:
self._pattern = re.compile('^%s_(.+)$' % self.name)
return self._pattern
@property
def format(self):
"""
Return the format used to create the name of a variation of the current
dynamic field. Use a default one ('fieldname_%s') if not set when the
field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.format
if not self._format:
self._format = '%s_%%s' % self.name
return self._format
@property
def dynamic_part(self):
if not hasattr(self, '_dynamic_part'):
self._dynamic_part = self.pattern.match(self.name).groups()[0]
return self._dynamic_part
def _accept_name(self, field_name):
"""
Return True if the given field name can be accepted by this dynamic field
"""
return bool(self.pattern.match(field_name))
def __copy__(self):
"""
Copy the _pattern attribute to the new copy of this field
"""
new_copy = super(DynamicFieldMixin, self).__copy__()
new_copy._pattern = self._pattern
return new_copy
def _create_dynamic_version(self):
"""
Create a copy of the field and set it as a dynamic version of it.
"""
new_field = copy(self)
new_field.dynamic_version_of = self
return new_field
def _base_field(self):
"""
Return the base field (the one without variable part) of the current one.
"""
return self.dynamic_version_of or self
@property
def _inventory(self):
"""
Return (and create if needed) the internal inventory field, a SetField
used to track all dynamic versions used on a specific instance.
"""
if self.dynamic_version_of:
return self.dynamic_version_of._inventory
if not hasattr(self, '_inventory_field'):
self._inventory_field = limpyd_fields.SetField()
self._inventory_field._attach_to_model(self._model)
self._inventory_field._attach_to_instance(self._instance)
self._inventory_field.lockable = True
self._inventory.name = self.name
return self._inventory_field
def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part)
def _delete_dynamic_versions(self):
"""
Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory.
"""
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete()
def get_name_for(self, dynamic_part):
"""
Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name.
"""
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name
def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name)
__call__ = get_for
def scan_keys(self, match=None, count=None):
if not hasattr(self, '_instance'):
raise ImplementationError('"scan_keys" can be used only on a bound field')
name = self.format % '*'
pattern = self.make_key(
self._instance._name,
self._instance.pk.get(),
name,
)
return self.database.scan_keys(pattern, count)
def sscan(self, match=None, count=None):
return self._inventory.sscan(match, count)
scan_versions = sscan
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin.delete | python | def delete(self):
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part) | If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L165-L174 | null | class DynamicFieldMixin(object):
"""
This mixin adds a main functionnality to each domain it's attached to: the
ability to have an unlimited number of fields. If a field is asked in the
model which not exists, it will ask to each of its dynamic fields if it
can accepts the wanted field name. If True, a new field is created on the
fly with this new name.
The matching is done using the "pattern" argument to pass when declaring
the dynamic field on the model. This argument must be a regular expression
(or a string, but in both cases the "re.compile" method will be called).
If not defined, the default pattern will be used: ^basefieldname_\d+$ (here,
basefieldname is the name used to declare the field on the model)
To to the reverse operation, ie get a field name based on a dynamic part,
the "format" argument can be passed when declaring the dynamic field on the
model. Both pattern and format must match. If not defined, the default
format is 'basefieldname_%s'.
"""
def __init__(self, *args, **kwargs):
"""
Handle the new optional "pattern" attribute
"""
self._pattern = kwargs.pop('pattern', None)
if self._pattern:
self._pattern = re.compile(self._pattern)
self._format = kwargs.pop('format', None)
self.dynamic_version_of = None
super(DynamicFieldMixin, self).__init__(*args, **kwargs)
def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self)
@property
def pattern(self):
"""
Return the pattern used to check if a field name can be accepted by this
dynamic field. Use a default one ('^fieldname_(.+)$') if not set when
the field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.pattern
if not self._pattern:
self._pattern = re.compile('^%s_(.+)$' % self.name)
return self._pattern
@property
def format(self):
"""
Return the format used to create the name of a variation of the current
dynamic field. Use a default one ('fieldname_%s') if not set when the
field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.format
if not self._format:
self._format = '%s_%%s' % self.name
return self._format
@property
def dynamic_part(self):
if not hasattr(self, '_dynamic_part'):
self._dynamic_part = self.pattern.match(self.name).groups()[0]
return self._dynamic_part
def _accept_name(self, field_name):
"""
Return True if the given field name can be accepted by this dynamic field
"""
return bool(self.pattern.match(field_name))
def __copy__(self):
"""
Copy the _pattern attribute to the new copy of this field
"""
new_copy = super(DynamicFieldMixin, self).__copy__()
new_copy._pattern = self._pattern
return new_copy
def _create_dynamic_version(self):
"""
Create a copy of the field and set it as a dynamic version of it.
"""
new_field = copy(self)
new_field.dynamic_version_of = self
return new_field
def _base_field(self):
"""
Return the base field (the one without variable part) of the current one.
"""
return self.dynamic_version_of or self
@property
def _inventory(self):
"""
Return (and create if needed) the internal inventory field, a SetField
used to track all dynamic versions used on a specific instance.
"""
if self.dynamic_version_of:
return self.dynamic_version_of._inventory
if not hasattr(self, '_inventory_field'):
self._inventory_field = limpyd_fields.SetField()
self._inventory_field._attach_to_model(self._model)
self._inventory_field._attach_to_instance(self._instance)
self._inventory_field.lockable = True
self._inventory.name = self.name
return self._inventory_field
def _call_command(self, name, *args, **kwargs):
"""
If a command is called for the main field, without dynamic part, an
ImplementationError is raised: commands can only be applied on dynamic
versions.
On dynamic versions, if the command is a modifier, we add the version in
the inventory.
"""
if self.dynamic_version_of is None:
raise ImplementationError('The main version of a dynamic field cannot accept commands')
try:
result = super(DynamicFieldMixin, self)._call_command(name, *args, **kwargs)
except:
raise
else:
if name in self.available_modifiers and name not in ('delete', 'hdel'):
self._inventory.sadd(self.dynamic_part)
return result
def _delete_dynamic_versions(self):
"""
Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory.
"""
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete()
def get_name_for(self, dynamic_part):
"""
Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name.
"""
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name
def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name)
__call__ = get_for
def scan_keys(self, match=None, count=None):
if not hasattr(self, '_instance'):
raise ImplementationError('"scan_keys" can be used only on a bound field')
name = self.format % '*'
pattern = self.make_key(
self._instance._name,
self._instance.pk.get(),
name,
)
return self.database.scan_keys(pattern, count)
def sscan(self, match=None, count=None):
return self._inventory.sscan(match, count)
scan_versions = sscan
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin._delete_dynamic_versions | python | def _delete_dynamic_versions(self):
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete() | Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L176-L196 | null | class DynamicFieldMixin(object):
"""
This mixin adds a main functionnality to each domain it's attached to: the
ability to have an unlimited number of fields. If a field is asked in the
model which not exists, it will ask to each of its dynamic fields if it
can accepts the wanted field name. If True, a new field is created on the
fly with this new name.
The matching is done using the "pattern" argument to pass when declaring
the dynamic field on the model. This argument must be a regular expression
(or a string, but in both cases the "re.compile" method will be called).
If not defined, the default pattern will be used: ^basefieldname_\d+$ (here,
basefieldname is the name used to declare the field on the model)
To to the reverse operation, ie get a field name based on a dynamic part,
the "format" argument can be passed when declaring the dynamic field on the
model. Both pattern and format must match. If not defined, the default
format is 'basefieldname_%s'.
"""
def __init__(self, *args, **kwargs):
"""
Handle the new optional "pattern" attribute
"""
self._pattern = kwargs.pop('pattern', None)
if self._pattern:
self._pattern = re.compile(self._pattern)
self._format = kwargs.pop('format', None)
self.dynamic_version_of = None
super(DynamicFieldMixin, self).__init__(*args, **kwargs)
def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self)
@property
def pattern(self):
"""
Return the pattern used to check if a field name can be accepted by this
dynamic field. Use a default one ('^fieldname_(.+)$') if not set when
the field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.pattern
if not self._pattern:
self._pattern = re.compile('^%s_(.+)$' % self.name)
return self._pattern
@property
def format(self):
"""
Return the format used to create the name of a variation of the current
dynamic field. Use a default one ('fieldname_%s') if not set when the
field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.format
if not self._format:
self._format = '%s_%%s' % self.name
return self._format
@property
def dynamic_part(self):
if not hasattr(self, '_dynamic_part'):
self._dynamic_part = self.pattern.match(self.name).groups()[0]
return self._dynamic_part
def _accept_name(self, field_name):
"""
Return True if the given field name can be accepted by this dynamic field
"""
return bool(self.pattern.match(field_name))
def __copy__(self):
"""
Copy the _pattern attribute to the new copy of this field
"""
new_copy = super(DynamicFieldMixin, self).__copy__()
new_copy._pattern = self._pattern
return new_copy
def _create_dynamic_version(self):
"""
Create a copy of the field and set it as a dynamic version of it.
"""
new_field = copy(self)
new_field.dynamic_version_of = self
return new_field
def _base_field(self):
"""
Return the base field (the one without variable part) of the current one.
"""
return self.dynamic_version_of or self
@property
def _inventory(self):
"""
Return (and create if needed) the internal inventory field, a SetField
used to track all dynamic versions used on a specific instance.
"""
if self.dynamic_version_of:
return self.dynamic_version_of._inventory
if not hasattr(self, '_inventory_field'):
self._inventory_field = limpyd_fields.SetField()
self._inventory_field._attach_to_model(self._model)
self._inventory_field._attach_to_instance(self._instance)
self._inventory_field.lockable = True
self._inventory.name = self.name
return self._inventory_field
def _call_command(self, name, *args, **kwargs):
"""
If a command is called for the main field, without dynamic part, an
ImplementationError is raised: commands can only be applied on dynamic
versions.
On dynamic versions, if the command is a modifier, we add the version in
the inventory.
"""
if self.dynamic_version_of is None:
raise ImplementationError('The main version of a dynamic field cannot accept commands')
try:
result = super(DynamicFieldMixin, self)._call_command(name, *args, **kwargs)
except:
raise
else:
if name in self.available_modifiers and name not in ('delete', 'hdel'):
self._inventory.sadd(self.dynamic_part)
return result
def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part)
def get_name_for(self, dynamic_part):
"""
Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name.
"""
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name
def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name)
__call__ = get_for
def scan_keys(self, match=None, count=None):
if not hasattr(self, '_instance'):
raise ImplementationError('"scan_keys" can be used only on a bound field')
name = self.format % '*'
pattern = self.make_key(
self._instance._name,
self._instance.pk.get(),
name,
)
return self.database.scan_keys(pattern, count)
def sscan(self, match=None, count=None):
return self._inventory.sscan(match, count)
scan_versions = sscan
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin.get_name_for | python | def get_name_for(self, dynamic_part):
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name | Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L198-L208 | null | class DynamicFieldMixin(object):
"""
This mixin adds a main functionnality to each domain it's attached to: the
ability to have an unlimited number of fields. If a field is asked in the
model which not exists, it will ask to each of its dynamic fields if it
can accepts the wanted field name. If True, a new field is created on the
fly with this new name.
The matching is done using the "pattern" argument to pass when declaring
the dynamic field on the model. This argument must be a regular expression
(or a string, but in both cases the "re.compile" method will be called).
If not defined, the default pattern will be used: ^basefieldname_\d+$ (here,
basefieldname is the name used to declare the field on the model)
To to the reverse operation, ie get a field name based on a dynamic part,
the "format" argument can be passed when declaring the dynamic field on the
model. Both pattern and format must match. If not defined, the default
format is 'basefieldname_%s'.
"""
def __init__(self, *args, **kwargs):
"""
Handle the new optional "pattern" attribute
"""
self._pattern = kwargs.pop('pattern', None)
if self._pattern:
self._pattern = re.compile(self._pattern)
self._format = kwargs.pop('format', None)
self.dynamic_version_of = None
super(DynamicFieldMixin, self).__init__(*args, **kwargs)
def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self)
@property
def pattern(self):
"""
Return the pattern used to check if a field name can be accepted by this
dynamic field. Use a default one ('^fieldname_(.+)$') if not set when
the field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.pattern
if not self._pattern:
self._pattern = re.compile('^%s_(.+)$' % self.name)
return self._pattern
@property
def format(self):
"""
Return the format used to create the name of a variation of the current
dynamic field. Use a default one ('fieldname_%s') if not set when the
field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.format
if not self._format:
self._format = '%s_%%s' % self.name
return self._format
@property
def dynamic_part(self):
if not hasattr(self, '_dynamic_part'):
self._dynamic_part = self.pattern.match(self.name).groups()[0]
return self._dynamic_part
def _accept_name(self, field_name):
"""
Return True if the given field name can be accepted by this dynamic field
"""
return bool(self.pattern.match(field_name))
def __copy__(self):
"""
Copy the _pattern attribute to the new copy of this field
"""
new_copy = super(DynamicFieldMixin, self).__copy__()
new_copy._pattern = self._pattern
return new_copy
def _create_dynamic_version(self):
"""
Create a copy of the field and set it as a dynamic version of it.
"""
new_field = copy(self)
new_field.dynamic_version_of = self
return new_field
def _base_field(self):
"""
Return the base field (the one without variable part) of the current one.
"""
return self.dynamic_version_of or self
@property
def _inventory(self):
"""
Return (and create if needed) the internal inventory field, a SetField
used to track all dynamic versions used on a specific instance.
"""
if self.dynamic_version_of:
return self.dynamic_version_of._inventory
if not hasattr(self, '_inventory_field'):
self._inventory_field = limpyd_fields.SetField()
self._inventory_field._attach_to_model(self._model)
self._inventory_field._attach_to_instance(self._instance)
self._inventory_field.lockable = True
self._inventory.name = self.name
return self._inventory_field
def _call_command(self, name, *args, **kwargs):
"""
If a command is called for the main field, without dynamic part, an
ImplementationError is raised: commands can only be applied on dynamic
versions.
On dynamic versions, if the command is a modifier, we add the version in
the inventory.
"""
if self.dynamic_version_of is None:
raise ImplementationError('The main version of a dynamic field cannot accept commands')
try:
result = super(DynamicFieldMixin, self)._call_command(name, *args, **kwargs)
except:
raise
else:
if name in self.available_modifiers and name not in ('delete', 'hdel'):
self._inventory.sadd(self.dynamic_part)
return result
def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part)
def _delete_dynamic_versions(self):
"""
Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory.
"""
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete()
def get_for(self, dynamic_part):
"""
Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name
"""
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name)
__call__ = get_for
def scan_keys(self, match=None, count=None):
if not hasattr(self, '_instance'):
raise ImplementationError('"scan_keys" can be used only on a bound field')
name = self.format % '*'
pattern = self.make_key(
self._instance._name,
self._instance.pk.get(),
name,
)
return self.database.scan_keys(pattern, count)
def sscan(self, match=None, count=None):
return self._inventory.sscan(match, count)
scan_versions = sscan
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/fields.py | DynamicFieldMixin.get_for | python | def get_for(self, dynamic_part):
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(name) | Return a variation of the current dynamic field based on the given
dynamic part. Use the "format" attribute to create the final name | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/fields.py#L210-L218 | null | class DynamicFieldMixin(object):
"""
This mixin adds a main functionnality to each domain it's attached to: the
ability to have an unlimited number of fields. If a field is asked in the
model which not exists, it will ask to each of its dynamic fields if it
can accepts the wanted field name. If True, a new field is created on the
fly with this new name.
The matching is done using the "pattern" argument to pass when declaring
the dynamic field on the model. This argument must be a regular expression
(or a string, but in both cases the "re.compile" method will be called).
If not defined, the default pattern will be used: ^basefieldname_\d+$ (here,
basefieldname is the name used to declare the field on the model)
To to the reverse operation, ie get a field name based on a dynamic part,
the "format" argument can be passed when declaring the dynamic field on the
model. Both pattern and format must match. If not defined, the default
format is 'basefieldname_%s'.
"""
def __init__(self, *args, **kwargs):
"""
Handle the new optional "pattern" attribute
"""
self._pattern = kwargs.pop('pattern', None)
if self._pattern:
self._pattern = re.compile(self._pattern)
self._format = kwargs.pop('format', None)
self.dynamic_version_of = None
super(DynamicFieldMixin, self).__init__(*args, **kwargs)
def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self)
@property
def pattern(self):
"""
Return the pattern used to check if a field name can be accepted by this
dynamic field. Use a default one ('^fieldname_(.+)$') if not set when
the field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.pattern
if not self._pattern:
self._pattern = re.compile('^%s_(.+)$' % self.name)
return self._pattern
@property
def format(self):
"""
Return the format used to create the name of a variation of the current
dynamic field. Use a default one ('fieldname_%s') if not set when the
field was initialized
"""
if self.dynamic_version_of is not None:
return self.dynamic_version_of.format
if not self._format:
self._format = '%s_%%s' % self.name
return self._format
@property
def dynamic_part(self):
if not hasattr(self, '_dynamic_part'):
self._dynamic_part = self.pattern.match(self.name).groups()[0]
return self._dynamic_part
def _accept_name(self, field_name):
"""
Return True if the given field name can be accepted by this dynamic field
"""
return bool(self.pattern.match(field_name))
def __copy__(self):
"""
Copy the _pattern attribute to the new copy of this field
"""
new_copy = super(DynamicFieldMixin, self).__copy__()
new_copy._pattern = self._pattern
return new_copy
def _create_dynamic_version(self):
"""
Create a copy of the field and set it as a dynamic version of it.
"""
new_field = copy(self)
new_field.dynamic_version_of = self
return new_field
def _base_field(self):
"""
Return the base field (the one without variable part) of the current one.
"""
return self.dynamic_version_of or self
@property
def _inventory(self):
"""
Return (and create if needed) the internal inventory field, a SetField
used to track all dynamic versions used on a specific instance.
"""
if self.dynamic_version_of:
return self.dynamic_version_of._inventory
if not hasattr(self, '_inventory_field'):
self._inventory_field = limpyd_fields.SetField()
self._inventory_field._attach_to_model(self._model)
self._inventory_field._attach_to_instance(self._instance)
self._inventory_field.lockable = True
self._inventory.name = self.name
return self._inventory_field
def _call_command(self, name, *args, **kwargs):
"""
If a command is called for the main field, without dynamic part, an
ImplementationError is raised: commands can only be applied on dynamic
versions.
On dynamic versions, if the command is a modifier, we add the version in
the inventory.
"""
if self.dynamic_version_of is None:
raise ImplementationError('The main version of a dynamic field cannot accept commands')
try:
result = super(DynamicFieldMixin, self)._call_command(name, *args, **kwargs)
except:
raise
else:
if name in self.available_modifiers and name not in ('delete', 'hdel'):
self._inventory.sadd(self.dynamic_part)
return result
def delete(self):
"""
If a dynamic version, delete it the standard way and remove it from the
inventory, else delete all dynamic versions.
"""
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part)
def _delete_dynamic_versions(self):
"""
Call the `delete` method of all dynamic versions of the current field
found in the inventory then clean the inventory.
"""
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete()
def get_name_for(self, dynamic_part):
"""
Compute the name of the variation of the current dynamic field based on
the given dynamic part. Use the "format" attribute to create the final
name.
"""
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return name
__call__ = get_for
def scan_keys(self, match=None, count=None):
if not hasattr(self, '_instance'):
raise ImplementationError('"scan_keys" can be used only on a bound field')
name = self.format % '*'
pattern = self.make_key(
self._instance._name,
self._instance.pk.get(),
name,
)
return self.database.scan_keys(pattern, count)
def sscan(self, match=None, count=None):
return self._inventory.sscan(match, count)
scan_versions = sscan
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/collection.py | CollectionManagerForModelWithDynamicFieldMixin.dynamic_filter | python | def dynamic_filter(self, field_name, dynamic_part, value, index_suffix=''):
field_name_parts = field_name.split('__')
real_field_name = field_name_parts.pop(0)
dynamic_field_name = self.cls.get_field(real_field_name).get_name_for(dynamic_part)
field_name_parts.insert(0, dynamic_field_name)
filter_name = '__'.join(field_name_parts)
if not index_suffix:
index_suffix = ''
elif not index_suffix.startswith('__'):
index_suffix = '__' + index_suffix
return self.filter(**{filter_name + index_suffix: value}) | Add a filter to the collection, using a dynamic field. The key part of
the filter is composed using the field_name, which must be the field
name of a dynamic field on the attached model, and a dynamic part.
The index_suffix allow to specify which index to use. It's an empty string
by default for the default equal index (could be "__eq" or "eq" to have the
exact same result)
Finally return the collection, by calling self.filter | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/collection.py#L9-L28 | null | class CollectionManagerForModelWithDynamicFieldMixin(object):
|
limpyd/redis-limpyd-extensions | limpyd_extensions/related.py | _RelatedCollectionWithMethods._to_fields | python | def _to_fields(self, *values):
result = []
for related_instance in values:
if not isinstance(related_instance, model.RedisModel):
related_instance = self.related_field._model(related_instance)
result.append(getattr(related_instance, self.related_field.name))
return result | Take a list of values, which must be primary keys of the model linked
to the related collection, and return a list of related fields. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/related.py#L20-L30 | null | class _RelatedCollectionWithMethods(RelatedCollection):
def _reverse_call(self, related_method, *values):
"""
Convert each value to a related field, then call the method on each
field, passing self.instance as argument.
If related_method is a string, it will be the method of the related field.
If it's a callable, it's a function which accept the related field and
self.instance.
"""
related_fields = self._to_fields(*values)
for related_field in related_fields:
if callable(related_method):
related_method(related_field, self.instance._pk)
else:
getattr(related_field, related_method)(self.instance._pk)
|
limpyd/redis-limpyd-extensions | limpyd_extensions/related.py | _RelatedCollectionWithMethods._reverse_call | python | def _reverse_call(self, related_method, *values):
related_fields = self._to_fields(*values)
for related_field in related_fields:
if callable(related_method):
related_method(related_field, self.instance._pk)
else:
getattr(related_field, related_method)(self.instance._pk) | Convert each value to a related field, then call the method on each
field, passing self.instance as argument.
If related_method is a string, it will be the method of the related field.
If it's a callable, it's a function which accept the related field and
self.instance. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/related.py#L32-L45 | null | class _RelatedCollectionWithMethods(RelatedCollection):
def _to_fields(self, *values):
"""
Take a list of values, which must be primary keys of the model linked
to the related collection, and return a list of related fields.
"""
result = []
for related_instance in values:
if not isinstance(related_instance, model.RedisModel):
related_instance = self.related_field._model(related_instance)
result.append(getattr(related_instance, self.related_field.name))
return result
|
limpyd/redis-limpyd-extensions | limpyd_extensions/related.py | _RelatedCollectionForFK.srem | python | def srem(self, *values):
self._reverse_call(lambda related_field, value: related_field.delete(), *values) | Do a "set" call with self.instance as parameter for each value. Values
must be primary keys of the related model. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/related.py#L58-L63 | null | class _RelatedCollectionForFK(_RelatedCollectionWithMethods):
_set_method = None
def sadd(self, *values):
"""
Do a "hset/set" call with self.instance as parameter for each value. Values
must be primary keys of the related model.
"""
self._reverse_call(self._set_method, *values)
|
limpyd/redis-limpyd-extensions | limpyd_extensions/related.py | RelatedCollectionForList.lrem | python | def lrem(self, *values):
self._reverse_call(lambda related_field, value: related_field.lrem(0, value), *values) | Do a "lrem" call with self.instance as parameter for each value. Values
must be primary keys of the related model.
The "count" argument of the final call will be 0 to remove all the
matching values. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/related.py#L123-L130 | null | class RelatedCollectionForList(_RelatedCollectionWithMethods):
"""
A RelatedCollection for M2MListField that can simulate calls to a real List.
Available methods: lpush, rpush and lrem.
"""
def lpush(self, *values):
"""
Do a "lpush" call with self.instance as parameter for each value. Values
must be primary keys of the related model.
"""
self._reverse_call('lpush', *values)
def rpush(self, *values):
"""
Do a "rpush" call with self.instance as parameter for each value. Values
must be primary keys of the related model.
"""
self._reverse_call('rpush', *values)
|
limpyd/redis-limpyd-extensions | limpyd_extensions/related.py | RelatedCollectionForSortedSet.zadd | python | def zadd(self, *args, **kwargs):
if 'values_callback' not in kwargs:
kwargs['values_callback'] = self._to_fields
pieces = fields.SortedSetField.coerce_zadd_args(*args, **kwargs)
for (score, related_field) in zip(*[iter(pieces)] * 2):
related_method = getattr(related_field, 'zadd')
related_method(score, self.instance._pk, values_callback=None) | For each score/value given as paramter, do a "zadd" call with
score/self.instance as parameter call for each value. Values must be
primary keys of the related model. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/related.py#L140-L151 | null | class RelatedCollectionForSortedSet(_RelatedCollectionWithMethods):
"""
A RelatedCollection for M2MSortedSetField that can simulate calls to a real
SortedSet
Available methods: zadd and zrem
"""
def zrem(self, *values):
"""
Do a "zrem" call with self.instance as parameter for each value. Values must
must be primary keys of the related model.
"""
self._reverse_call('zrem', *values)
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin._get_dynamic_field_for | python | def _get_dynamic_field_for(cls, field_name):
from .fields import DynamicFieldMixin # here to avoid circular import
if cls not in ModelWithDynamicFieldMixin._dynamic_fields_cache:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls] = {}
if field_name not in ModelWithDynamicFieldMixin._dynamic_fields_cache[cls]:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = None
for a_field_name in cls._fields:
field = cls.get_field(a_field_name)
if isinstance(field, DynamicFieldMixin) and field._accept_name(field_name):
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = field
break
field = ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name]
if field is None:
raise ValueError('No DynamicField matching "%s"' % field_name)
return field | Return the dynamic field within this class that match the given name.
Keep an internal cache to speed up future calls wieh same field name.
(The cache store the field for each individual class and subclasses, to
keep the link between a field and its direct model) | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L21-L46 | null | class ModelWithDynamicFieldMixin(object):
"""
This mixin must be used to declare each model that is intended to use a
DynamicField, creating fields on the fly when needed.
"""
_dynamic_fields_cache = {}
collection_manager = CollectionManagerForModelWithDynamicField
@classmethod
@classmethod
def has_field(cls, field_name):
"""
Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name.
"""
if super(ModelWithDynamicFieldMixin, cls).has_field(field_name):
return True
try:
cls._get_dynamic_field_for(field_name)
except ValueError:
return False
else:
return True
@classmethod
def get_class_field(cls, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the model.
"""
try:
field = super(ModelWithDynamicFieldMixin, cls).get_class_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = cls._get_dynamic_field_for(field_name)
field = cls._add_dynamic_field_to_model(dynamic_field, field_name)
return field
# at the class level, we use get_class_field to get a field
# but in __init__, we update it to use get_instance_field
get_field = get_class_field
def get_instance_field(self, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the instance.
"""
try:
field = super(ModelWithDynamicFieldMixin, self).get_instance_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = self._get_dynamic_field_for(field_name) # it's a model bound field
dynamic_field = self.get_field(dynamic_field.name) # we now have an instance bound field
field = self._add_dynamic_field_to_instance(dynamic_field, field_name)
return field
@classmethod
def _add_dynamic_field_to_model(cls, field, field_name):
"""
Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_model(cls)
# set it as an attribute on the class, to be reachable
setattr(cls, "_redis_attr_%s" % field_name, new_field)
# NOTE: don't add the field to the "_fields" list, to avoid use extra
# memory to each future instance that will create a field for each
# dynamic one created
# # add the field to the list to avoid to done all of this again
# # (_fields is already on this class only, not subclasses)
# cls._fields.append(field_name)
# each subclass needs its own copy
for subclass in cls.__subclasses__():
subclass._add_dynamic_field_to_model(field, field_name)
return new_field
def _add_dynamic_field_to_instance(self, field, field_name):
"""
Add a copy of the DynamicField "field" to the current instance using the
"field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_instance(self)
# add the field to the list to avoid doing all of this again
if field_name not in self._fields: # (maybe already in it via the class)
if id(self._fields) == id(self.__class__._fields):
# unlink the list from the class
self._fields = list(self._fields)
self._fields.append(field_name)
# if the field is an hashable field, add it to the list to allow calling
# hmget on these fields
if isinstance(field, limpyd_fields.InstanceHashField):
if id(self._instancehash_fields) == id(self.__class__._instancehash_fields):
# unlink the link from the class
self._instancehash_fields = list(self._instancehash_fields)
self._instancehash_fields.append(field_name)
# set it as an attribute on the instance, to be reachable
setattr(self, field_name, new_field)
return new_field
@classmethod
def get_field_name_for(cls, field_name, dynamic_part):
"""
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
"""
field = cls.get_field(field_name)
return field.get_name_for(dynamic_part)
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin.has_field | python | def has_field(cls, field_name):
if super(ModelWithDynamicFieldMixin, cls).has_field(field_name):
return True
try:
cls._get_dynamic_field_for(field_name)
except ValueError:
return False
else:
return True | Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L49-L63 | null | class ModelWithDynamicFieldMixin(object):
"""
This mixin must be used to declare each model that is intended to use a
DynamicField, creating fields on the fly when needed.
"""
_dynamic_fields_cache = {}
collection_manager = CollectionManagerForModelWithDynamicField
@classmethod
def _get_dynamic_field_for(cls, field_name):
"""
Return the dynamic field within this class that match the given name.
Keep an internal cache to speed up future calls wieh same field name.
(The cache store the field for each individual class and subclasses, to
keep the link between a field and its direct model)
"""
from .fields import DynamicFieldMixin # here to avoid circular import
if cls not in ModelWithDynamicFieldMixin._dynamic_fields_cache:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls] = {}
if field_name not in ModelWithDynamicFieldMixin._dynamic_fields_cache[cls]:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = None
for a_field_name in cls._fields:
field = cls.get_field(a_field_name)
if isinstance(field, DynamicFieldMixin) and field._accept_name(field_name):
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = field
break
field = ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name]
if field is None:
raise ValueError('No DynamicField matching "%s"' % field_name)
return field
@classmethod
@classmethod
def get_class_field(cls, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the model.
"""
try:
field = super(ModelWithDynamicFieldMixin, cls).get_class_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = cls._get_dynamic_field_for(field_name)
field = cls._add_dynamic_field_to_model(dynamic_field, field_name)
return field
# at the class level, we use get_class_field to get a field
# but in __init__, we update it to use get_instance_field
get_field = get_class_field
def get_instance_field(self, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the instance.
"""
try:
field = super(ModelWithDynamicFieldMixin, self).get_instance_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = self._get_dynamic_field_for(field_name) # it's a model bound field
dynamic_field = self.get_field(dynamic_field.name) # we now have an instance bound field
field = self._add_dynamic_field_to_instance(dynamic_field, field_name)
return field
@classmethod
def _add_dynamic_field_to_model(cls, field, field_name):
"""
Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_model(cls)
# set it as an attribute on the class, to be reachable
setattr(cls, "_redis_attr_%s" % field_name, new_field)
# NOTE: don't add the field to the "_fields" list, to avoid use extra
# memory to each future instance that will create a field for each
# dynamic one created
# # add the field to the list to avoid to done all of this again
# # (_fields is already on this class only, not subclasses)
# cls._fields.append(field_name)
# each subclass needs its own copy
for subclass in cls.__subclasses__():
subclass._add_dynamic_field_to_model(field, field_name)
return new_field
def _add_dynamic_field_to_instance(self, field, field_name):
"""
Add a copy of the DynamicField "field" to the current instance using the
"field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_instance(self)
# add the field to the list to avoid doing all of this again
if field_name not in self._fields: # (maybe already in it via the class)
if id(self._fields) == id(self.__class__._fields):
# unlink the list from the class
self._fields = list(self._fields)
self._fields.append(field_name)
# if the field is an hashable field, add it to the list to allow calling
# hmget on these fields
if isinstance(field, limpyd_fields.InstanceHashField):
if id(self._instancehash_fields) == id(self.__class__._instancehash_fields):
# unlink the link from the class
self._instancehash_fields = list(self._instancehash_fields)
self._instancehash_fields.append(field_name)
# set it as an attribute on the instance, to be reachable
setattr(self, field_name, new_field)
return new_field
@classmethod
def get_field_name_for(cls, field_name, dynamic_part):
"""
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
"""
field = cls.get_field(field_name)
return field.get_name_for(dynamic_part)
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin.get_class_field | python | def get_class_field(cls, field_name):
try:
field = super(ModelWithDynamicFieldMixin, cls).get_class_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = cls._get_dynamic_field_for(field_name)
field = cls._add_dynamic_field_to_model(dynamic_field, field_name)
return field | Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the model. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L66-L79 | null | class ModelWithDynamicFieldMixin(object):
"""
This mixin must be used to declare each model that is intended to use a
DynamicField, creating fields on the fly when needed.
"""
_dynamic_fields_cache = {}
collection_manager = CollectionManagerForModelWithDynamicField
@classmethod
def _get_dynamic_field_for(cls, field_name):
"""
Return the dynamic field within this class that match the given name.
Keep an internal cache to speed up future calls wieh same field name.
(The cache store the field for each individual class and subclasses, to
keep the link between a field and its direct model)
"""
from .fields import DynamicFieldMixin # here to avoid circular import
if cls not in ModelWithDynamicFieldMixin._dynamic_fields_cache:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls] = {}
if field_name not in ModelWithDynamicFieldMixin._dynamic_fields_cache[cls]:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = None
for a_field_name in cls._fields:
field = cls.get_field(a_field_name)
if isinstance(field, DynamicFieldMixin) and field._accept_name(field_name):
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = field
break
field = ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name]
if field is None:
raise ValueError('No DynamicField matching "%s"' % field_name)
return field
@classmethod
def has_field(cls, field_name):
"""
Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name.
"""
if super(ModelWithDynamicFieldMixin, cls).has_field(field_name):
return True
try:
cls._get_dynamic_field_for(field_name)
except ValueError:
return False
else:
return True
@classmethod
# at the class level, we use get_class_field to get a field
# but in __init__, we update it to use get_instance_field
get_field = get_class_field
def get_instance_field(self, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the instance.
"""
try:
field = super(ModelWithDynamicFieldMixin, self).get_instance_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = self._get_dynamic_field_for(field_name) # it's a model bound field
dynamic_field = self.get_field(dynamic_field.name) # we now have an instance bound field
field = self._add_dynamic_field_to_instance(dynamic_field, field_name)
return field
@classmethod
def _add_dynamic_field_to_model(cls, field, field_name):
"""
Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_model(cls)
# set it as an attribute on the class, to be reachable
setattr(cls, "_redis_attr_%s" % field_name, new_field)
# NOTE: don't add the field to the "_fields" list, to avoid use extra
# memory to each future instance that will create a field for each
# dynamic one created
# # add the field to the list to avoid to done all of this again
# # (_fields is already on this class only, not subclasses)
# cls._fields.append(field_name)
# each subclass needs its own copy
for subclass in cls.__subclasses__():
subclass._add_dynamic_field_to_model(field, field_name)
return new_field
def _add_dynamic_field_to_instance(self, field, field_name):
"""
Add a copy of the DynamicField "field" to the current instance using the
"field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_instance(self)
# add the field to the list to avoid doing all of this again
if field_name not in self._fields: # (maybe already in it via the class)
if id(self._fields) == id(self.__class__._fields):
# unlink the list from the class
self._fields = list(self._fields)
self._fields.append(field_name)
# if the field is an hashable field, add it to the list to allow calling
# hmget on these fields
if isinstance(field, limpyd_fields.InstanceHashField):
if id(self._instancehash_fields) == id(self.__class__._instancehash_fields):
# unlink the link from the class
self._instancehash_fields = list(self._instancehash_fields)
self._instancehash_fields.append(field_name)
# set it as an attribute on the instance, to be reachable
setattr(self, field_name, new_field)
return new_field
@classmethod
def get_field_name_for(cls, field_name, dynamic_part):
"""
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
"""
field = cls.get_field(field_name)
return field.get_name_for(dynamic_part)
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin.get_instance_field | python | def get_instance_field(self, field_name):
try:
field = super(ModelWithDynamicFieldMixin, self).get_instance_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = self._get_dynamic_field_for(field_name) # it's a model bound field
dynamic_field = self.get_field(dynamic_field.name) # we now have an instance bound field
field = self._add_dynamic_field_to_instance(dynamic_field, field_name)
return field | Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the instance. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L85-L99 | null | class ModelWithDynamicFieldMixin(object):
"""
This mixin must be used to declare each model that is intended to use a
DynamicField, creating fields on the fly when needed.
"""
_dynamic_fields_cache = {}
collection_manager = CollectionManagerForModelWithDynamicField
@classmethod
def _get_dynamic_field_for(cls, field_name):
"""
Return the dynamic field within this class that match the given name.
Keep an internal cache to speed up future calls wieh same field name.
(The cache store the field for each individual class and subclasses, to
keep the link between a field and its direct model)
"""
from .fields import DynamicFieldMixin # here to avoid circular import
if cls not in ModelWithDynamicFieldMixin._dynamic_fields_cache:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls] = {}
if field_name not in ModelWithDynamicFieldMixin._dynamic_fields_cache[cls]:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = None
for a_field_name in cls._fields:
field = cls.get_field(a_field_name)
if isinstance(field, DynamicFieldMixin) and field._accept_name(field_name):
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = field
break
field = ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name]
if field is None:
raise ValueError('No DynamicField matching "%s"' % field_name)
return field
@classmethod
def has_field(cls, field_name):
"""
Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name.
"""
if super(ModelWithDynamicFieldMixin, cls).has_field(field_name):
return True
try:
cls._get_dynamic_field_for(field_name)
except ValueError:
return False
else:
return True
@classmethod
def get_class_field(cls, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the model.
"""
try:
field = super(ModelWithDynamicFieldMixin, cls).get_class_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = cls._get_dynamic_field_for(field_name)
field = cls._add_dynamic_field_to_model(dynamic_field, field_name)
return field
# at the class level, we use get_class_field to get a field
# but in __init__, we update it to use get_instance_field
get_field = get_class_field
@classmethod
def _add_dynamic_field_to_model(cls, field, field_name):
"""
Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_model(cls)
# set it as an attribute on the class, to be reachable
setattr(cls, "_redis_attr_%s" % field_name, new_field)
# NOTE: don't add the field to the "_fields" list, to avoid use extra
# memory to each future instance that will create a field for each
# dynamic one created
# # add the field to the list to avoid to done all of this again
# # (_fields is already on this class only, not subclasses)
# cls._fields.append(field_name)
# each subclass needs its own copy
for subclass in cls.__subclasses__():
subclass._add_dynamic_field_to_model(field, field_name)
return new_field
def _add_dynamic_field_to_instance(self, field, field_name):
"""
Add a copy of the DynamicField "field" to the current instance using the
"field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_instance(self)
# add the field to the list to avoid doing all of this again
if field_name not in self._fields: # (maybe already in it via the class)
if id(self._fields) == id(self.__class__._fields):
# unlink the list from the class
self._fields = list(self._fields)
self._fields.append(field_name)
# if the field is an hashable field, add it to the list to allow calling
# hmget on these fields
if isinstance(field, limpyd_fields.InstanceHashField):
if id(self._instancehash_fields) == id(self.__class__._instancehash_fields):
# unlink the link from the class
self._instancehash_fields = list(self._instancehash_fields)
self._instancehash_fields.append(field_name)
# set it as an attribute on the instance, to be reachable
setattr(self, field_name, new_field)
return new_field
@classmethod
def get_field_name_for(cls, field_name, dynamic_part):
"""
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
"""
field = cls.get_field(field_name)
return field.get_name_for(dynamic_part)
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin._add_dynamic_field_to_model | python | def _add_dynamic_field_to_model(cls, field, field_name):
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_model(cls)
# set it as an attribute on the class, to be reachable
setattr(cls, "_redis_attr_%s" % field_name, new_field)
# NOTE: don't add the field to the "_fields" list, to avoid use extra
# memory to each future instance that will create a field for each
# dynamic one created
# # add the field to the list to avoid to done all of this again
# # (_fields is already on this class only, not subclasses)
# cls._fields.append(field_name)
# each subclass needs its own copy
for subclass in cls.__subclasses__():
subclass._add_dynamic_field_to_model(field, field_name)
return new_field | Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L102-L127 | null | class ModelWithDynamicFieldMixin(object):
"""
This mixin must be used to declare each model that is intended to use a
DynamicField, creating fields on the fly when needed.
"""
_dynamic_fields_cache = {}
collection_manager = CollectionManagerForModelWithDynamicField
@classmethod
def _get_dynamic_field_for(cls, field_name):
"""
Return the dynamic field within this class that match the given name.
Keep an internal cache to speed up future calls wieh same field name.
(The cache store the field for each individual class and subclasses, to
keep the link between a field and its direct model)
"""
from .fields import DynamicFieldMixin # here to avoid circular import
if cls not in ModelWithDynamicFieldMixin._dynamic_fields_cache:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls] = {}
if field_name not in ModelWithDynamicFieldMixin._dynamic_fields_cache[cls]:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = None
for a_field_name in cls._fields:
field = cls.get_field(a_field_name)
if isinstance(field, DynamicFieldMixin) and field._accept_name(field_name):
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = field
break
field = ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name]
if field is None:
raise ValueError('No DynamicField matching "%s"' % field_name)
return field
@classmethod
def has_field(cls, field_name):
"""
Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name.
"""
if super(ModelWithDynamicFieldMixin, cls).has_field(field_name):
return True
try:
cls._get_dynamic_field_for(field_name)
except ValueError:
return False
else:
return True
@classmethod
def get_class_field(cls, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the model.
"""
try:
field = super(ModelWithDynamicFieldMixin, cls).get_class_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = cls._get_dynamic_field_for(field_name)
field = cls._add_dynamic_field_to_model(dynamic_field, field_name)
return field
# at the class level, we use get_class_field to get a field
# but in __init__, we update it to use get_instance_field
get_field = get_class_field
def get_instance_field(self, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the instance.
"""
try:
field = super(ModelWithDynamicFieldMixin, self).get_instance_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = self._get_dynamic_field_for(field_name) # it's a model bound field
dynamic_field = self.get_field(dynamic_field.name) # we now have an instance bound field
field = self._add_dynamic_field_to_instance(dynamic_field, field_name)
return field
@classmethod
def _add_dynamic_field_to_instance(self, field, field_name):
"""
Add a copy of the DynamicField "field" to the current instance using the
"field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_instance(self)
# add the field to the list to avoid doing all of this again
if field_name not in self._fields: # (maybe already in it via the class)
if id(self._fields) == id(self.__class__._fields):
# unlink the list from the class
self._fields = list(self._fields)
self._fields.append(field_name)
# if the field is an hashable field, add it to the list to allow calling
# hmget on these fields
if isinstance(field, limpyd_fields.InstanceHashField):
if id(self._instancehash_fields) == id(self.__class__._instancehash_fields):
# unlink the link from the class
self._instancehash_fields = list(self._instancehash_fields)
self._instancehash_fields.append(field_name)
# set it as an attribute on the instance, to be reachable
setattr(self, field_name, new_field)
return new_field
@classmethod
def get_field_name_for(cls, field_name, dynamic_part):
"""
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
"""
field = cls.get_field(field_name)
return field.get_name_for(dynamic_part)
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin._add_dynamic_field_to_instance | python | def _add_dynamic_field_to_instance(self, field, field_name):
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_instance(self)
# add the field to the list to avoid doing all of this again
if field_name not in self._fields: # (maybe already in it via the class)
if id(self._fields) == id(self.__class__._fields):
# unlink the list from the class
self._fields = list(self._fields)
self._fields.append(field_name)
# if the field is an hashable field, add it to the list to allow calling
# hmget on these fields
if isinstance(field, limpyd_fields.InstanceHashField):
if id(self._instancehash_fields) == id(self.__class__._instancehash_fields):
# unlink the link from the class
self._instancehash_fields = list(self._instancehash_fields)
self._instancehash_fields.append(field_name)
# set it as an attribute on the instance, to be reachable
setattr(self, field_name, new_field)
return new_field | Add a copy of the DynamicField "field" to the current instance using the
"field_name" name | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L129-L157 | null | class ModelWithDynamicFieldMixin(object):
"""
This mixin must be used to declare each model that is intended to use a
DynamicField, creating fields on the fly when needed.
"""
_dynamic_fields_cache = {}
collection_manager = CollectionManagerForModelWithDynamicField
@classmethod
def _get_dynamic_field_for(cls, field_name):
"""
Return the dynamic field within this class that match the given name.
Keep an internal cache to speed up future calls wieh same field name.
(The cache store the field for each individual class and subclasses, to
keep the link between a field and its direct model)
"""
from .fields import DynamicFieldMixin # here to avoid circular import
if cls not in ModelWithDynamicFieldMixin._dynamic_fields_cache:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls] = {}
if field_name not in ModelWithDynamicFieldMixin._dynamic_fields_cache[cls]:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = None
for a_field_name in cls._fields:
field = cls.get_field(a_field_name)
if isinstance(field, DynamicFieldMixin) and field._accept_name(field_name):
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = field
break
field = ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name]
if field is None:
raise ValueError('No DynamicField matching "%s"' % field_name)
return field
@classmethod
def has_field(cls, field_name):
"""
Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name.
"""
if super(ModelWithDynamicFieldMixin, cls).has_field(field_name):
return True
try:
cls._get_dynamic_field_for(field_name)
except ValueError:
return False
else:
return True
@classmethod
def get_class_field(cls, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the model.
"""
try:
field = super(ModelWithDynamicFieldMixin, cls).get_class_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = cls._get_dynamic_field_for(field_name)
field = cls._add_dynamic_field_to_model(dynamic_field, field_name)
return field
# at the class level, we use get_class_field to get a field
# but in __init__, we update it to use get_instance_field
get_field = get_class_field
def get_instance_field(self, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the instance.
"""
try:
field = super(ModelWithDynamicFieldMixin, self).get_instance_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = self._get_dynamic_field_for(field_name) # it's a model bound field
dynamic_field = self.get_field(dynamic_field.name) # we now have an instance bound field
field = self._add_dynamic_field_to_instance(dynamic_field, field_name)
return field
@classmethod
def _add_dynamic_field_to_model(cls, field, field_name):
"""
Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_model(cls)
# set it as an attribute on the class, to be reachable
setattr(cls, "_redis_attr_%s" % field_name, new_field)
# NOTE: don't add the field to the "_fields" list, to avoid use extra
# memory to each future instance that will create a field for each
# dynamic one created
# # add the field to the list to avoid to done all of this again
# # (_fields is already on this class only, not subclasses)
# cls._fields.append(field_name)
# each subclass needs its own copy
for subclass in cls.__subclasses__():
subclass._add_dynamic_field_to_model(field, field_name)
return new_field
@classmethod
def get_field_name_for(cls, field_name, dynamic_part):
"""
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
"""
field = cls.get_field(field_name)
return field.get_name_for(dynamic_part)
|
limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/model.py | ModelWithDynamicFieldMixin.get_field_name_for | python | def get_field_name_for(cls, field_name, dynamic_part):
field = cls.get_field(field_name)
return field.get_name_for(dynamic_part) | Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field. | train | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/model.py#L160-L167 | null | class ModelWithDynamicFieldMixin(object):
"""
This mixin must be used to declare each model that is intended to use a
DynamicField, creating fields on the fly when needed.
"""
_dynamic_fields_cache = {}
collection_manager = CollectionManagerForModelWithDynamicField
@classmethod
def _get_dynamic_field_for(cls, field_name):
"""
Return the dynamic field within this class that match the given name.
Keep an internal cache to speed up future calls wieh same field name.
(The cache store the field for each individual class and subclasses, to
keep the link between a field and its direct model)
"""
from .fields import DynamicFieldMixin # here to avoid circular import
if cls not in ModelWithDynamicFieldMixin._dynamic_fields_cache:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls] = {}
if field_name not in ModelWithDynamicFieldMixin._dynamic_fields_cache[cls]:
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = None
for a_field_name in cls._fields:
field = cls.get_field(a_field_name)
if isinstance(field, DynamicFieldMixin) and field._accept_name(field_name):
ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name] = field
break
field = ModelWithDynamicFieldMixin._dynamic_fields_cache[cls][field_name]
if field is None:
raise ValueError('No DynamicField matching "%s"' % field_name)
return field
@classmethod
def has_field(cls, field_name):
"""
Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name.
"""
if super(ModelWithDynamicFieldMixin, cls).has_field(field_name):
return True
try:
cls._get_dynamic_field_for(field_name)
except ValueError:
return False
else:
return True
@classmethod
def get_class_field(cls, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the model.
"""
try:
field = super(ModelWithDynamicFieldMixin, cls).get_class_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = cls._get_dynamic_field_for(field_name)
field = cls._add_dynamic_field_to_model(dynamic_field, field_name)
return field
# at the class level, we use get_class_field to get a field
# but in __init__, we update it to use get_instance_field
get_field = get_class_field
def get_instance_field(self, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the instance.
"""
try:
field = super(ModelWithDynamicFieldMixin, self).get_instance_field(field_name)
except AttributeError:
# the "has_field" returned True but getattr raised... we have a DynamicField
dynamic_field = self._get_dynamic_field_for(field_name) # it's a model bound field
dynamic_field = self.get_field(dynamic_field.name) # we now have an instance bound field
field = self._add_dynamic_field_to_instance(dynamic_field, field_name)
return field
@classmethod
def _add_dynamic_field_to_model(cls, field, field_name):
"""
Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_model(cls)
# set it as an attribute on the class, to be reachable
setattr(cls, "_redis_attr_%s" % field_name, new_field)
# NOTE: don't add the field to the "_fields" list, to avoid use extra
# memory to each future instance that will create a field for each
# dynamic one created
# # add the field to the list to avoid to done all of this again
# # (_fields is already on this class only, not subclasses)
# cls._fields.append(field_name)
# each subclass needs its own copy
for subclass in cls.__subclasses__():
subclass._add_dynamic_field_to_model(field, field_name)
return new_field
def _add_dynamic_field_to_instance(self, field, field_name):
"""
Add a copy of the DynamicField "field" to the current instance using the
"field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_name
new_field._attach_to_instance(self)
# add the field to the list to avoid doing all of this again
if field_name not in self._fields: # (maybe already in it via the class)
if id(self._fields) == id(self.__class__._fields):
# unlink the list from the class
self._fields = list(self._fields)
self._fields.append(field_name)
# if the field is an hashable field, add it to the list to allow calling
# hmget on these fields
if isinstance(field, limpyd_fields.InstanceHashField):
if id(self._instancehash_fields) == id(self.__class__._instancehash_fields):
# unlink the link from the class
self._instancehash_fields = list(self._instancehash_fields)
self._instancehash_fields.append(field_name)
# set it as an attribute on the instance, to be reachable
setattr(self, field_name, new_field)
return new_field
@classmethod
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _custom_argv | python | def _custom_argv(argv):
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv | Overwrite argv[1:] with argv, restore on exit. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L42-L49 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _patched_pep257 | python | def _patched_pep257():
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info | Monkey-patch pep257 after imports to avoid info logging. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L53-L68 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _stamped_deps | python | def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs) | Run func, assumed to have dependencies as its first argument. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L71-L82 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _debug_linter_status | python | def _debug_linter_status(linter, filename, show_lint_files):
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename)) | Indicate that we are running this linter if required. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L99-L102 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _run_flake8_internal | python | def _run_flake8_internal(filename):
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict | Run flake8. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L105-L158 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _run_flake8 | python | def _run_flake8(filename, stamp_file_name, show_lint_files):
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename) | Run flake8, cached by stamp_file_name. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L161-L166 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _run_prospector_on | python | def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict | Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L191-L235 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _run_prospector | python | def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs) | Run prospector. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L244-L286 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _run_pyroma | python | def _run_pyroma(setup_file, show_lint_files):
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict | Run pyroma. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L289-L311 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _run_polysquare_style_linter | python | def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict | Run polysquare-generic-file-linter on matched_filenames. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L322-L355 | [
"def _debug_linter_status(linter, filename, show_lint_files):\n \"\"\"Indicate that we are running this linter if required.\"\"\"\n if show_lint_files:\n print(\"{linter}: {filename}\".format(linter=linter, filename=filename))\n"
] | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _run_spellcheck_linter | python | def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict | Run spellcheck-linter on matched_filenames. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L358-L389 | [
"def _debug_linter_status(linter, filename, show_lint_files):\n \"\"\"Indicate that we are running this linter if required.\"\"\"\n if show_lint_files:\n print(\"{linter}: {filename}\".format(linter=linter, filename=filename))\n"
] | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _run_markdownlint | python | def _run_markdownlint(matched_filenames, show_lint_files):
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict | Run markdownlint on matched_filenames. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L392-L418 | [
"def _debug_linter_status(linter, filename, show_lint_files):\n \"\"\"Indicate that we are running this linter if required.\"\"\"\n if show_lint_files:\n print(\"{linter}: {filename}\".format(linter=linter, filename=filename))\n"
] | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.