prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): <|fim_middle|> def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
if not value: return [] if isinstance(value, list): return value return value.split(',')
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): <|fim_middle|> def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
return ','.join(value)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. <|fim_middle|> def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): <|fim_middle|> def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): <|fim_middle|> choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: <|fim_middle|> if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
raise AttributeError # ?
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: <|fim_middle|> return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: <|fim_middle|> def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: <|fim_middle|> kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
value = 'null'
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: <|fim_middle|> if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
return []
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): <|fim_middle|> return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
return value
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): <|fim_middle|> for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default()
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): <|fim_middle|> else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
defaults['initial'] = self.default defaults['show_hidden_initial'] = True
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: <|fim_middle|> for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
defaults['initial'] = self.get_default()
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): <|fim_middle|> defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
del kwargs[k]
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. <|fim_middle|> def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
raise ValidationError(self.error_messages['invalid_choice'] % invalid_values)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): <|fim_middle|> elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
return self._choices.copy()
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): <|fim_middle|> else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
choices, self._choices = itertools.tee(self._choices) return choices
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: <|fim_middle|> choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
return self._choices
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: <|fim_middle|> <|fim▁end|>
add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def <|fim_middle|>(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
__init__
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def <|fim_middle|>(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
__init__
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def <|fim_middle|>(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
__get__
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def <|fim_middle|>(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
__set__
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def <|fim_middle|>(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
__delete__
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def <|fim_middle|>(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
get_attname
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def <|fim_middle|>(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
contribute_to_class
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def <|fim_middle|>(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
fix_init_kwarg
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def <|fim_middle|>(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
formfield
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def <|fim_middle|>(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
get_internal_type
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def <|fim_middle|>(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
to_python
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def <|fim_middle|>(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
get_prep_value
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def <|fim_middle|>(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
formfield
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def <|fim_middle|>(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
validate
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def <|fim_middle|>(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
_get_choices
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<|fim▁hole|>from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!')<|fim▁end|>
# See the License for the specific language governing permissions and # limitations under the License.
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): <|fim_middle|> def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
"""Inability to send mail.""" pass
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): <|fim_middle|> def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
"""Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!')
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): <|fim_middle|> def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
"""SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): <|fim_middle|> <|fim▁end|>
"""Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!')
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: <|fim_middle|> elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!')
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': <|fim_middle|> elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
_send_smtp(message, subject, to, to_name, sender, sender_name)
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': <|fim_middle|> else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
_send_mailjet(message, subject, to, to_name, sender, sender_name)
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: <|fim_middle|> def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!')
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: <|fim_middle|> try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
raise MailFailure('SMTP Server Not Configured')
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: <|fim_middle|> server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
server.set_debuglevel(True)
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: <|fim_middle|> # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: <|fim_middle|> to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
from_obj["Name"] = sender_name
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: <|fim_middle|> message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
to_obj[0]["Name"] = to_name
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: <|fim_middle|> try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!')
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': <|fim_middle|> <|fim▁end|>
app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!')
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def <|fim_middle|>(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
send
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def <|fim_middle|>(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
_send_smtp
<|file_name|>mail.py<|end_file_name|><|fim▁begin|># Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """Inability to send mail.""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """Send an email.""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def <|fim_middle|>(message, subject, to, to_name, sender, sender_name): """Mailjet implementation of sending email.""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { "Email": sender, } if sender_name: from_obj["Name"] = sender_name to_obj = [{ "Email": to, }] if to_name: to_obj[0]["Name"] = to_name message = { "From": from_obj, "To": to_obj, "Subject": subject, "TextPart": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') <|fim▁end|>
_send_mailjet
<|file_name|>add_vcf_to_project.py<|end_file_name|><|fim▁begin|>import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser):<|fim▁hole|> parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables") def handle(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual in project.individual_set.all(): individual.vcf_files.clear() if options.get('indiv_id'): individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file) else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path])<|fim▁end|>
parser.add_argument('args', nargs='*')
<|file_name|>add_vcf_to_project.py<|end_file_name|><|fim▁begin|>import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): <|fim_middle|> <|fim▁end|>
def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables") def handle(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual in project.individual_set.all(): individual.vcf_files.clear() if options.get('indiv_id'): individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file) else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path])
<|file_name|>add_vcf_to_project.py<|end_file_name|><|fim▁begin|>import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser): <|fim_middle|> def handle(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual in project.individual_set.all(): individual.vcf_files.clear() if options.get('indiv_id'): individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file) else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path]) <|fim▁end|>
parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables")
<|file_name|>add_vcf_to_project.py<|end_file_name|><|fim▁begin|>import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables") def handle(self, *args, **options): <|fim_middle|> <|fim▁end|>
project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual in project.individual_set.all(): individual.vcf_files.clear() if options.get('indiv_id'): individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file) else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path])
<|file_name|>add_vcf_to_project.py<|end_file_name|><|fim▁begin|>import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables") def handle(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): <|fim_middle|> if options.get('indiv_id'): individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file) else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path]) <|fim▁end|>
for individual in project.individual_set.all(): individual.vcf_files.clear()
<|file_name|>add_vcf_to_project.py<|end_file_name|><|fim▁begin|>import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables") def handle(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual in project.individual_set.all(): individual.vcf_files.clear() if options.get('indiv_id'): <|fim_middle|> else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path]) <|fim▁end|>
individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file)
<|file_name|>add_vcf_to_project.py<|end_file_name|><|fim▁begin|>import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables") def handle(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual in project.individual_set.all(): individual.vcf_files.clear() if options.get('indiv_id'): individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file) else: <|fim_middle|> if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path]) <|fim▁end|>
sample_management.add_vcf_file_to_project(project, vcf_file)
<|file_name|>add_vcf_to_project.py<|end_file_name|><|fim▁begin|>import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables") def handle(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual in project.individual_set.all(): individual.vcf_files.clear() if options.get('indiv_id'): individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file) else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): <|fim_middle|> <|fim▁end|>
print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path])
<|file_name|>add_vcf_to_project.py<|end_file_name|><|fim▁begin|>import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def <|fim_middle|>(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables") def handle(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual in project.individual_set.all(): individual.vcf_files.clear() if options.get('indiv_id'): individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file) else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path]) <|fim▁end|>
add_arguments
<|file_name|>add_vcf_to_project.py<|end_file_name|><|fim▁begin|>import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables") def <|fim_middle|>(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual in project.individual_set.all(): individual.vcf_files.clear() if options.get('indiv_id'): individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file) else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path]) <|fim▁end|>
handle
<|file_name|>types_bytes_subscrstep.py<|end_file_name|><|fim▁begin|>""" categories: Types,bytes description: Bytes subscr with step != 1 not implemented cause: Unknown workaround: Unknown<|fim▁hole|>print(b'123'[0:3:2])<|fim▁end|>
"""
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop()<|fim▁hole|> def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:])<|fim▁end|>
def quit(self, _=None): """quit the application""" self.root.quit()
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: <|fim_middle|> def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
"""Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='')
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): <|fim_middle|> def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set()
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): <|fim_middle|> def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
"""launch the mainloop of the application""" self.root.mainloop()
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): <|fim_middle|> def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
"""quit the application""" self.root.quit()
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): <|fim_middle|> def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
"""launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='')
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): <|fim_middle|> if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
"""launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop()
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): <|fim_middle|> else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
PYLINT = 'pylint.bat'
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: <|fim_middle|> class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
PYLINT = 'pylint'
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: <|fim_middle|> gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
Run(sys.argv[1:])
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def <|fim_middle|>(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
__init__
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def <|fim_middle|>(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
mainloop
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def <|fim_middle|>(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
quit
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def <|fim_middle|>(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def Run(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
run_lint
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>"""Tkinker gui for pylint""" from Tkinter import Tk, Frame, Listbox, Entry, Label, Button, Scrollbar from Tkinter import TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH import os import sys if sys.platform.startswith('win'): PYLINT = 'pylint.bat' else: PYLINT = 'pylint' class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set() def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def run_lint(self, _=None): """launches pylint""" colors = {'W:':'red1', 'E:': 'red4', 'W:': 'red3', '**': 'navy'} self.root.configure(cursor='watch') self.results.focus_set() self.results.delete(0, END) self.results.update() module = self.txtModule.get() pout = os.popen('%s %s' % (PYLINT, module), 'r') for line in pout.xreadlines(): line = line.rstrip() self.results.insert(END, line) fg_color = colors.get(line[:2], 'black') self.results.itemconfigure(END, fg=fg_color) self.results.update() self.root.configure(cursor='') def <|fim_middle|>(args): """launch pylint gui from args""" if args: print 'USAGE: pylint-gui\n launch a simple pylint gui using Tk' return gui = LintGui() gui.mainloop() if __name__ == '__main__': Run(sys.argv[1:]) <|fim▁end|>
Run
<|file_name|>test_first_seen_event.py<|end_file_name|><|fim▁begin|>from sentry.testutils.cases import RuleTestCase from sentry.rules.conditions.first_seen_event import FirstSeenEventCondition class FirstSeenEventConditionTest(RuleTestCase): rule_cls = FirstSeenEventCondition def test_applies_correctly(self):<|fim▁hole|> self.assertPasses(rule, self.event, is_new=True) self.assertDoesNotPass(rule, self.event, is_new=False)<|fim▁end|>
rule = self.get_rule()
<|file_name|>test_first_seen_event.py<|end_file_name|><|fim▁begin|>from sentry.testutils.cases import RuleTestCase from sentry.rules.conditions.first_seen_event import FirstSeenEventCondition class FirstSeenEventConditionTest(RuleTestCase): <|fim_middle|> <|fim▁end|>
rule_cls = FirstSeenEventCondition def test_applies_correctly(self): rule = self.get_rule() self.assertPasses(rule, self.event, is_new=True) self.assertDoesNotPass(rule, self.event, is_new=False)
<|file_name|>test_first_seen_event.py<|end_file_name|><|fim▁begin|>from sentry.testutils.cases import RuleTestCase from sentry.rules.conditions.first_seen_event import FirstSeenEventCondition class FirstSeenEventConditionTest(RuleTestCase): rule_cls = FirstSeenEventCondition def test_applies_correctly(self): <|fim_middle|> <|fim▁end|>
rule = self.get_rule() self.assertPasses(rule, self.event, is_new=True) self.assertDoesNotPass(rule, self.event, is_new=False)
<|file_name|>test_first_seen_event.py<|end_file_name|><|fim▁begin|>from sentry.testutils.cases import RuleTestCase from sentry.rules.conditions.first_seen_event import FirstSeenEventCondition class FirstSeenEventConditionTest(RuleTestCase): rule_cls = FirstSeenEventCondition def <|fim_middle|>(self): rule = self.get_rule() self.assertPasses(rule, self.event, is_new=True) self.assertDoesNotPass(rule, self.event, is_new=False) <|fim▁end|>
test_applies_correctly
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, )<|fim▁hole|> """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth )<|fim▁end|>
def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info.
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): <|fim_middle|> <|fim▁end|>
""" Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth )
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): <|fim_middle|> @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth ) <|fim▁end|>
self.requested_depth = requested_depth
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): <|fim_middle|> @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth ) <|fim▁end|>
return "blocks_api:block_depth"
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): <|fim_middle|> def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth ) <|fim▁end|>
""" Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, )
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def transform(self, usage_info, block_structure): <|fim_middle|> <|fim▁end|>
""" Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth )
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: <|fim_middle|> else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth ) <|fim▁end|>
block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: <|fim_middle|> block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth ) <|fim▁end|>
block_depth = 0
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: <|fim_middle|> <|fim▁end|>
block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth )
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def <|fim_middle|>(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth ) <|fim▁end|>
__init__
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def <|fim_middle|>(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth ) <|fim▁end|>
name
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def <|fim_middle|>(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def transform(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth ) <|fim▁end|>
get_block_depth
<|file_name|>block_depth.py<|end_file_name|><|fim▁begin|>""" Block Depth Transformer """ from __future__ import absolute_import from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer class BlockDepthTransformer(BlockStructureTransformer): """ Keep track of the depth of each block within the block structure. In case of multiple paths to a given node (in a DAG), use the shallowest depth. """ WRITE_VERSION = 1 READ_VERSION = 1 BLOCK_DEPTH = 'block_depth' def __init__(self, requested_depth=None): self.requested_depth = requested_depth @classmethod def name(cls): return "blocks_api:block_depth" @classmethod def get_block_depth(cls, block_structure, block_key): """ Return the precalculated depth of a block within the block_structure: Arguments: block_structure: a BlockStructure instance block_key: the key of the block whose depth we want to know Returns: int """ return block_structure.get_transformer_block_field( block_key, cls, cls.BLOCK_DEPTH, ) def <|fim_middle|>(self, usage_info, block_structure): """ Mutates block_structure based on the given usage_info. """ for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) if parents: block_depth = min( self.get_block_depth(block_structure, parent_key) for parent_key in parents ) + 1 else: block_depth = 0 block_structure.set_transformer_block_field( block_key, self, self.BLOCK_DEPTH, block_depth ) if self.requested_depth is not None: block_structure.remove_block_traversal( lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth ) <|fim▁end|>
transform
<|file_name|>suite.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python """ ``climactic.suite`` ------------------- .. autoclass:: ClimacticTestSuite """ import logging import unittest from pathlib import Path from climactic.case import ClimacticTestCase logger = logging.getLogger(__name__) class ClimacticTestSuite(unittest.TestSuite): """ A collection of tests. """ @classmethod def from_targets(cls, *targets, **kwargs): suite = cls() tests = [] logger.trace("Processing target list {}", list(targets)) for target in targets: logger.trace("Processing target '{}'", target) try: target_path = Path(target).resolve() except FileNotFoundError: logger.warn( "Target '{}' could not be found", target ) continue if target_path.is_dir(): target_tests = cls.collect_dir( target_path, **kwargs ) tests.extend(target_tests) else: for target_test in cls.collect_file( target_path ): tests.append(target_test) suite.addTests(tests) return suite @classmethod def from_dir(cls, dir_path, **kwargs): return cls.from_targets(dir_path, **kwargs) @classmethod def collect_dir(cls, dir_path, recursive=True): tests = [] dir_path = Path(dir_path) logger.trace("+ Collecting dir {}", str(dir_path)) target_paths = dir_path.glob( ("**" if recursive else "*") + "/test_*.yml" )<|fim▁hole|> target_path, base_path=dir_path ): tests.append(test) logger.trace("- Collecting dir {}", str(dir_path)) return tests @classmethod def collect_file(cls, target_path, base_path=None): logger.trace( " + Loading yml file {!r}", str(target_path) ) yield from ClimacticTestCase.from_path( target_path, base_path=base_path )<|fim▁end|>
for target_path in target_paths: for test in cls.collect_file(
<|file_name|>suite.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python """ ``climactic.suite`` ------------------- .. autoclass:: ClimacticTestSuite """ import logging import unittest from pathlib import Path from climactic.case import ClimacticTestCase logger = logging.getLogger(__name__) class ClimacticTestSuite(unittest.TestSuite): <|fim_middle|> <|fim▁end|>
""" A collection of tests. """ @classmethod def from_targets(cls, *targets, **kwargs): suite = cls() tests = [] logger.trace("Processing target list {}", list(targets)) for target in targets: logger.trace("Processing target '{}'", target) try: target_path = Path(target).resolve() except FileNotFoundError: logger.warn( "Target '{}' could not be found", target ) continue if target_path.is_dir(): target_tests = cls.collect_dir( target_path, **kwargs ) tests.extend(target_tests) else: for target_test in cls.collect_file( target_path ): tests.append(target_test) suite.addTests(tests) return suite @classmethod def from_dir(cls, dir_path, **kwargs): return cls.from_targets(dir_path, **kwargs) @classmethod def collect_dir(cls, dir_path, recursive=True): tests = [] dir_path = Path(dir_path) logger.trace("+ Collecting dir {}", str(dir_path)) target_paths = dir_path.glob( ("**" if recursive else "*") + "/test_*.yml" ) for target_path in target_paths: for test in cls.collect_file( target_path, base_path=dir_path ): tests.append(test) logger.trace("- Collecting dir {}", str(dir_path)) return tests @classmethod def collect_file(cls, target_path, base_path=None): logger.trace( " + Loading yml file {!r}", str(target_path) ) yield from ClimacticTestCase.from_path( target_path, base_path=base_path )