|
6 | 6 |
|
7 | 7 |
|
8 | 8 | class URLShortener(BaseModel):
|
9 |
| - url: str |
10 |
| - _shortener: Optional[pyshorteners.Shortener] = PrivateAttr() |
| 9 | + url: str |
| 10 | + _shortener: Optional[pyshorteners.Shortener] = PrivateAttr() |
11 | 11 |
|
12 |
| - class Config: |
13 |
| - arbitrary_types_allowed = True |
| 12 | + class Config: |
| 13 | + arbitrary_types_allowed = True |
14 | 14 |
|
15 |
| - def __init__(self, **data): |
16 |
| - shortener = data.pop("shortener", None) or pyshorteners.Shortener() |
17 |
| - super().__init__(**data) |
18 |
| - self._shortener = shortener |
| 15 | + def __init__(self, **data): |
| 16 | + """ |
| 17 | + Initialize the URLShortener. If no 'shortener' is provided in data, |
| 18 | + a new pyshorteners.Shortener instance is created. |
| 19 | + """ |
| 20 | + shortener = data.pop("shortener", None) or pyshorteners.Shortener() |
| 21 | + super().__init__(**data) |
| 22 | + self._shortener = shortener |
19 | 23 |
|
20 |
| - def shorten_url(self) -> Union[str, Exception]: |
21 |
| - if self._shortener is None: |
22 |
| - raise ValueError("Shortener is not initialized.") |
| 24 | + def shorten_url(self) -> Union[str, Exception]: |
| 25 | + if self._shortener is None: |
| 26 | + raise ValueError("Shortener is not initialized.") |
23 | 27 |
|
24 |
| - try: |
25 |
| - return str(self._shortener.tinyurl.short(self.url)) |
26 |
| - except (ParsingError, ValidationError) as error: |
27 |
| - return error |
28 |
| - except Exception as generic_error: |
29 |
| - return generic_error |
| 28 | + try: |
| 29 | + return str(self._shortener.tinyurl.short(self.url)) |
| 30 | + except (ParsingError, ValidationError) as error: |
| 31 | + return error |
| 32 | + except Exception as generic_error: |
| 33 | + return generic_error |
0 commit comments