def get_notes(self): """ Returns the body of the docstring trimmed before any parameters are listed. First, get the class docstring and then get the method's. The methods will always inherit the class comments. """ docstring = "" class_docs = self.callback.__doc__ or '' class_docs = smart_text(class_docs) class_docs = IntrospectorHelper.strip_yaml_from_docstring(class_docs) class_docs = IntrospectorHelper.strip_params_from_docstring(class_docs) method_docs = self.get_docs() if class_docs is not None: docstring += class_docs + " \n" if method_docs is not None: method_docs = formatting.dedent(smart_text(method_docs)) method_docs = IntrospectorHelper.strip_yaml_from_docstring( method_docs ) method_docs = IntrospectorHelper.strip_params_from_docstring( method_docs ) docstring += '\n' + method_docs return do_markdown(docstring)
def get_notes(self): """ Returns the body of the docstring trimmed before any parameters are listed. First, get the class docstring and then get the method's. The methods will always inherit the class comments. """ docstring = "" class_docs = self.callback.__doc__ or '' class_docs = smart_text(class_docs) class_docs = IntrospectorHelper.strip_yaml_from_docstring(class_docs) class_docs = IntrospectorHelper.strip_params_from_docstring(class_docs) method_docs = self.get_docs() if class_docs is not None: docstring += class_docs + " \n" if method_docs is not None: method_docs = formatting.dedent(smart_text(method_docs)) method_docs = IntrospectorHelper.strip_yaml_from_docstring( method_docs) method_docs = IntrospectorHelper.strip_params_from_docstring( method_docs) docstring += '\n' + method_docs return do_markdown(docstring)
def label_from_instance(self, obj): """ Return a readable representation for use with eg. select widgets. """ desc = smart_text(obj) ident = smart_text(self.to_native(obj)) if desc == ident: return desc return "%s - %s" % (desc, ident)
def __init__(self, source=None, label=None, help_text=None): self.parent = None self.creation_counter = Field.creation_counter Field.creation_counter += 1 self.source = source if label is not None: self.label = smart_text(label) if help_text is not None: self.help_text = smart_text(help_text)
def valid_value(self, value): """ Check to see if the provided value is a valid choice. """ for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == smart_text(k2): return True else: if value == smart_text(k) or value == k: return True return False
def to_internal_value(self, data): try: return self.get_queryset().get(**{self.slug_field: data}) except ObjectDoesNotExist: self.fail('does_not_exist', slug_name=self.slug_field, value=smart_text(data)) except (TypeError, ValueError): self.fail('invalid')
def from_native(self, data): if self.queryset is None: raise Exception('Writable related fields must include a `queryset` argument') data = data.strip() # alter the value if self.coerce is not None: data = self.coerce(data) try: return self.queryset.get(**{self.slug_lookup_field: data}) except ObjectDoesNotExist: if not self.allow_create: # new objects are not allowed to be created # hence the exception raise ValidationError( self.error_messages['does_not_exist'] % (self.slug_field, smart_text(data)) ) obj = self.queryset.model(**{self.slug_field: data}) obj.save() return obj except (TypeError, ValueError): msg = self.error_messages['invalid'] raise ValidationError(msg)
def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ auth = get_authorization_header(request).split() auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower() if not auth or smart_text(auth[0].lower()) != auth_header_prefix: return None if len(auth) == 1: msg = 'Invalid Authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = ('Invalid Authorization header. Credentials string ' 'should not contain spaces.') raise exceptions.AuthenticationFailed(msg) try: payload = jwt_decode_handler(auth[1]) except jwt.ExpiredSignature: msg = 'Signature has expired.' raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = 'Error decoding signature.' raise exceptions.AuthenticationFailed(msg) user = self.authenticate_credentials(payload) return (user, auth[1])
def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: print date.today() xml.startElement("list-item", { 'lastupdated': str(date.today()), 'test1': 'testing' }) self._to_xml(xml, item) xml.endElement("list-item") elif isinstance(data, dict): for key, value in six.iteritems(data): if key == 'reference_number': xml.startElement(key, {'abc': 'test'}) self._to_xml(xml, value) xml.endElement(key) else: xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) elif data is None: # Don't output any value pass else: xml.characters(smart_text(data))
def get_view_doc(view, html=True): """ Build view documentation. Return in html format. If you want in markdown format, use html=False """ try: description = view.__doc__ or '' description = formatting.dedent(smart_text(description)) # include filters in description filter_fields = get_filter_fields(view) if filter_fields: filter_doc = ['\n\n\n## Filters', ''] for f in filter_fields: filter_doc.append('- `%s`' % f) description += '\n'.join(filter_doc) # replace {api_url} by current base url api_url = "/api" description = description.replace('{api_url}', api_url) if html: description = formatting.markup_description(description) return description except: import traceback traceback.print_exc() raise
def from_native(self, value): if isinstance(value, six.string_types): return value if value is None: return '' return smart_text(value)
def test_view_description_supports_unicode(self): """ Unicode in docstrings should be respected. """ self.assertEqual( ViewWithNonASCIICharactersInDocstring().get_view_description(), smart_text(UTF8_TEST_DOCSTRING))
def from_native(self, data): if isinstance(data, basestring): try: data = self.queryset.only('pk').get(slug=data).pk except ObjectDoesNotExist: msg = self.error_messages['does_not_exist'] % smart_text(data) raise serializers.ValidationError(msg) return super(SlugModelChoiceField, self).from_native(data)
def from_native(self, data): if isinstance(data, basestring): try: data = self.queryset.only('pk').get(slug=data).pk except ObjectDoesNotExist: msg = self.error_messages['does_not_exist'] % smart_text(data) raise ValidationError(msg) return super(SlugModelChoiceField, self).from_native(data)
def get_view_description(cls, html=False): """ Return a description for an `APIView` class or `@api_view` function. """ description = cls.__doc__ or '' description = _remove_leading_indent(smart_text(description)) if html: return markup_description(description) return description
def test_view_description_supports_unicode(self): """ Unicode in docstrings should be respected. """ self.assertEqual( get_view_description(ViewWithNonASCIICharactersInDocstring), smart_text(UTF8_TEST_DOCSTRING) )
def get_view_description(view_cls, html=False): """ Given a view class, return a textual description to represent the view. This name is used in the browsable API, and in OPTIONS responses. This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting. """ description = view_cls.__doc__ or '' description = formatting.dedent(smart_text(description)) if html: return formatting.markup_description(description) return description
def from_native(self, value): if isinstance(value, six.string_types): return value if value is None: if not self.allow_none: return '' else: # Return None explicitly because smart_text(None) == 'None'. See #1834 for details return None return smart_text(value)
def __init__(self, source=None, label=None, help_text=None): self.parent = None self.creation_counter = Field.creation_counter Field.creation_counter += 1 self.source = source if label is not None: self.label = smart_text(label) else: self.label = None if help_text is not None: self.help_text = strip_multiple_choice_msg(smart_text(help_text)) else: self.help_text = None self._errors = [] self._value = None self._name = None
def from_native(self, data, files=None): if not data or isinstance(data, dict): return super(FromPrivateKeyMixin, self).from_native(data, files) try: obj = self.opts.model.objects.get(pk=data) obj._from_pk = True return obj except ObjectDoesNotExist: raise ValidationError(self.error_messages['does_not_exist'] % smart_text(data)) except (TypeError, ValueError): received = type(data).__name__ raise ValidationError(self.error_messages['incorrect_type'] % received)
def from_native(self, data): if self.queryset is None: raise Exception('Writable related fields must include a `queryset` argument') try: return self.queryset.get(pk=data) except: try: return self.queryset.get(**{self.slug_field: data}) except ObjectDoesNotExist: msg = self.error_messages['does_not_exist'] % ('pk_or_slug', smart_text(data)) raise ValidationError(msg)
def from_native(self, data): if self.queryset is None: raise Exception('Writable related fields must include a `queryset` argument') try: return self.queryset.get(**{self.slug_field: data}) except ObjectDoesNotExist: raise ValidationError(self.error_messages['does_not_exist'] % (self.slug_field, smart_text(data))) except (TypeError, ValueError): msg = self.error_messages['invalid'] raise ValidationError(msg)
def from_native(self, data): if self.queryset is None: raise Exception('Writable related fields must include a `queryset` argument') try: return self.queryset.get(pk=data) except ObjectDoesNotExist: msg = self.error_messages['does_not_exist'] % smart_text(data) raise ValidationError(msg) except (TypeError, ValueError): received = type(data).__name__ msg = self.error_messages['incorrect_type'] % received raise ValidationError(msg)
def from_native(self, data): if self.queryset is None: raise Exception('Writable related fields must include a ' '`queryset` argument') try: return self.queryset.get(pk=data) except: try: return self.queryset.get(**{self.slug_field: data}) except ObjectDoesNotExist: msg = self.error_messages['does_not_exist'] % ( 'pk_or_slug', smart_text(data)) raise ValidationError(msg)
def to_native(self, value): """ Converts the field's value into it's simple representation. """ if is_simple_callable(value): value = value() if is_protected_type(value): return value elif hasattr(value, '__iter__') and not isinstance(value, (dict, six.string_types)): return [self.to_native(item) for item in value] elif isinstance(value, dict): return dict(map(self.to_native, (k, v)) for k, v in value.items()) return smart_text(value)
def from_native(self, data, files): ''' Almost direct copy of PrimaryKeyRelatedField's implementation of this method, with some changes since this is a Serializer field. ''' try: return self.Meta.model.objects.get(pk=data) except ObjectDoesNotExist: msg = self.error_messages['does_not_exist'] % smart_text(data) raise ValidationError(msg) except (TypeError, ValueError): received = type(data).__name__ msg = self.error_messages['incorrect_type'] % received raise ValidationError(msg)
def from_native(self, value): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. """ if value in validators.EMPTY_VALUES: return None value = smart_text(value).strip() try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid']) return value
def to_internal_value(self, data): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. """ data = smart_text(data).strip() if len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: value = decimal.Decimal(data) except decimal.DecimalException: self.fail('invalid') # Check for NaN. It is the only value that isn't equal to itself, # so we can use this to identify NaN values. if value != value: self.fail('invalid') # Check for infinity and negative infinity. if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')): self.fail('invalid') sign, digittuple, exponent = value.as_tuple() decimals = abs(exponent) # digittuple doesn't include any leading zeros. digits = len(digittuple) if decimals > digits: # We have leading zeros up to or past the decimal point. Count # everything past the decimal point as a digit. We do not count # 0 before the decimal point as a digit since that would mean # we would not allow max_digits = decimal_places. digits = decimals whole_digits = digits - decimals if self.max_digits is not None and digits > self.max_digits: self.fail('max_digits', max_digits=self.max_digits) if self.decimal_places is not None and decimals > self.decimal_places: self.fail('max_decimal_places', max_decimal_places=self.decimal_places) if self.max_digits is not None and self.decimal_places is not None and whole_digits > ( self.max_digits - self.decimal_places): self.fail('max_whole_digits', max_whole_digits=self.max_digits - self.decimal_places) return value
def _to_xml(self, xml, data): is_element = all([ 'name' in data, 'attrib' in data, 'children' in data, ]) is_text = 'text' in data if is_element: xml.startElement(data['name'], data['attrib']) if is_text: xml.characters(smart_text(data['text'])) else: for each in data['children']: self._to_xml(xml, each) xml.endElement(data['name'])
def to_internal_value(self, data): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. """ data = smart_text(data).strip() if len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: value = decimal.Decimal(data) except decimal.DecimalException: self.fail('invalid') # Check for NaN. It is the only value that isn't equal to itself, # so we can use this to identify NaN values. if value != value: self.fail('invalid') # Check for infinity and negative infinity. if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')): self.fail('invalid') sign, digittuple, exponent = value.as_tuple() decimals = abs(exponent) # digittuple doesn't include any leading zeros. digits = len(digittuple) if decimals > digits: # We have leading zeros up to or past the decimal point. Count # everything past the decimal point as a digit. We do not count # 0 before the decimal point as a digit since that would mean # we would not allow max_digits = decimal_places. digits = decimals whole_digits = digits - decimals if self.max_digits is not None and digits > self.max_digits: self.fail('max_digits', max_digits=self.max_digits) if self.decimal_places is not None and decimals > self.decimal_places: self.fail('max_decimal_places', max_decimal_places=self.decimal_places) if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places): self.fail('max_whole_digits', max_whole_digits=self.max_digits - self.decimal_places) return value
def to_native(self, value): """ Converts the field's value into it's simple representation. """ if is_simple_callable(value): value = value() if is_protected_type(value): return value elif hasattr(value, '__iter__') and not isinstance(value, (dict, six.string_types)): return [self.to_native(item) for item in value] elif isinstance(value, dict): # Make sure we preserve field ordering, if it exists ret = SortedDict() for key, val in value.items(): ret[key] = self.to_native(val) return ret return smart_text(value)
def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: xml.startElement("list-item", {}) self._to_xml(xml, item) xml.endElement("list-item") elif isinstance(data, dict): for key, value in six.iteritems(data): xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) elif data is None: # Don't output any value pass else: xml.characters(smart_text(data))
def _to_xml(self, xml, data): if isinstance(data, (list, tuple, types.GeneratorType, islice)): for item in data: xml.startElement("list-item", {}) self._to_xml(xml, item) xml.endElement("list-item") elif isinstance(data, dict): for key, value in six.iteritems(data): xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) elif isinstance(data, (geometry.LineString, geometry.MultiLineString, geometry.MultiPoint, geometry.MultiPolygon, geometry.Point, geometry.Polygon)): return self._to_xml(xml, data.__geo_interface__) elif data is None: # Don't output any value pass else: xml.characters(smart_text(data))
def get_description(self, view): try: return view.get_description(html=True) except AttributeError: return smart_text(view.__doc__ or '')
def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: # xml.startElement("property", {'lastupdated': str(date.today()),'test1':'testing'}) self._to_xml(xml, item) # xml.endElement("property") elif isinstance(data, dict): for key, value in six.iteritems(data): if key == 'property': xml.startElement(key, {'lastupdate': str(date.today())}) self._to_xml(xml, value) xml.endElement(key) # continue if key == 'reference_number': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + value + ' ]]>') xml.endElement(key) # continue if key == 'offering_type': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + value + ' ]]>') xml.endElement(key) # continue if key == 'property_type': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + value + ' ]]>') xml.endElement(key) # continue if key == 'price_on_application': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'price': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'service_charge': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'rental_period': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'cheques': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'city': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'community': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'sub_community': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'property_name': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'title_en': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'title_ar': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'description_en': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'description_ar': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'private_amenities': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'commercial_amenities': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'view': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'plot_size': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'size': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'bedroom': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'bathroom': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'agent': xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) # continue if key == 'name': xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) # continue if key == 'email': xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) # continue if key == 'phone': xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) # continue if key == 'photo': xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) # continue if key == 'info': xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) # continue if key == 'featured': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'developer': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'build_year': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue if key == 'floor': xml.startElement(key, {}) self._to_xml(xml, '<![CDATA[ ' + str(value) + ' ]]>') xml.endElement(key) # continue # else: # xml.startElement(key, {}) # self._to_xml(xml, value) # xml.endElement(key) elif data is None: # Don't output any value pass else: xml.characters(smart_text(data))
def label_from_instance(self, obj): return smart_text(obj)
def get_description(self, view): try: return view.get_description(html=True) except AttributeError: return smart_text(view.__doc__ or "")
def get_view_description(cls, html=False): description = cls.__doc__ or '' description = formatting.dedent(smart_text(description)) if html: return formatting.markup_description(description) return description
def from_native(self, value): """Return the appropriate model instance object based on the provided value. """ params = {} defaults = {} # If the user sent a non-dictionary, then we assume we got the # ID of the foreign relation as a primative. Convert this to a # dictionary. if not isinstance(value, dict): params[self.default_lookup_field] = value else: params = value # Remove any parameters that aren't unique values. # We are *only* able to use unique values to retrieve records # in this situation. rel_model = self.queryset.model for key in copy(params).keys(): # If this is `pk`, it's known good; move on. if key == 'pk': continue # If this key is in any `unique_together` specification, then # keep it. if any([key in ut for ut in rel_model._meta.unique_together]): continue # If this key corresponds to a unique field, keep it. try: field = rel_model._meta.get_field_by_name(key)[0] if field.unique or field.primary_key: continue except FieldDoesNotExist: # If this is a key in our serializer that simply # isn't a model field, that means it corresponds to the DRF # default output, and we can ignore it. serializer = self._get_serializer(rel_model()) if key in serializer.fields: params.pop(key) continue # This is a field we totally don't recognize; complain. raise exceptions.ValidationError('Unknown field: `%s`.' % key) # Okay, this isn't a key we should have in our lookup; # it's superfluous. # # Store it in defaults so that it can be used to update # the object if necessary. defaults[key] = params.pop(key) # Sanity check: Are there any parameters left? # If no unique parameters were provided, we have no basis on which # to do a lookup. if not len(params): raise exceptions.ValidationError('No unique (or jointly-unique) ' 'parameters were provided.') # Perform the lookup. try: return self.queryset.get(**params) except exceptions.ObjectDoesNotExist: error_msg = 'Object does not exist with: %s.' % smart_text(value) except exceptions.MultipleObjectsReturned: error_msg = 'Multiple objects returned for: {0}.'.format( smart_text(value), ) except (TypeError, ValueError): error_msg = 'Type mismatch.' raise exceptions.ValidationError(error_msg)
def get_notes(self): class_docs = self.callback.__doc__ or '' class_docs = smart_text(class_docs) class_docs = IntrospectorHelper.strip_yaml_from_docstring(class_docs) class_docs = IntrospectorHelper.strip_params_from_docstring(class_docs) return do_markdown(class_docs)