|
| 1 | +"""Property classes for web-related concepts""" |
| 2 | +from six.moves.urllib.parse import ParseResult, urlparse #pylint: disable=import-error |
| 3 | + |
| 4 | +from .. import basic |
| 5 | + |
| 6 | +class URL(basic.String): |
| 7 | + """String property that only accepts valid URLs |
| 8 | +
|
| 9 | + This property type uses :code:`urllib.parse` to validate |
| 10 | + input URLs and possibly remove fragments and query params. |
| 11 | +
|
| 12 | + **Available keywords** (in addition to those inherited from |
| 13 | + :class:`String <properties.String>`): |
| 14 | +
|
| 15 | + * **remove_parameters** - Query params are stripped from input URL (default |
| 16 | + is False). |
| 17 | + * **remove_fragment** - Fragment is stripped from input URL (default |
| 18 | + is False). |
| 19 | + """ |
| 20 | + |
| 21 | + class_info = 'a URL' |
| 22 | + |
| 23 | + @property |
| 24 | + def remove_parameters(self): |
| 25 | + """Should path and query parameters be stripped""" |
| 26 | + return getattr(self, '_remove_parameters', False) |
| 27 | + |
| 28 | + @remove_parameters.setter |
| 29 | + def remove_parameters(self, value): |
| 30 | + self._remove_parameters = bool(value) |
| 31 | + |
| 32 | + @property |
| 33 | + def remove_fragment(self): |
| 34 | + """Should fragment be stripped""" |
| 35 | + return getattr(self, '_remove_fragment', False) |
| 36 | + |
| 37 | + @remove_fragment.setter |
| 38 | + def remove_fragment(self, value): |
| 39 | + self._remove_fragment = bool(value) |
| 40 | + |
| 41 | + def validate(self, instance, value): |
| 42 | + """Check if input is valid URL""" |
| 43 | + value = super(URL, self).validate(instance, value) |
| 44 | + parsed_url = urlparse(value) |
| 45 | + if not parsed_url.scheme or not parsed_url.netloc: |
| 46 | + self.error(instance, value) |
| 47 | + parse_result = ParseResult( |
| 48 | + scheme=parsed_url.scheme, |
| 49 | + netloc=parsed_url.netloc, |
| 50 | + path=parsed_url.path, |
| 51 | + params='' if self.remove_parameters else parsed_url.params, |
| 52 | + query='' if self.remove_parameters else parsed_url.query, |
| 53 | + fragment='' if self.remove_fragment else parsed_url.fragment, |
| 54 | + ) |
| 55 | + parse_result = parse_result.geturl() |
| 56 | + return parse_result |
| 57 | + |
| 58 | + @property |
| 59 | + def info(self): |
| 60 | + info = 'a URL string' |
| 61 | + if self.remove_parameters: |
| 62 | + info += ', path or query params removed' |
| 63 | + if self.remove_fragment: |
| 64 | + info += ', fragment removed' |
0 commit comments