Coverage for human_requests/abstraction/http.py: 100%

51 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-13 21:41 +0000

1from dataclasses import dataclass, field 

2from enum import Enum 

3from typing import Optional 

4from urllib.parse import parse_qs, urlparse 

5 

6 

7class HttpMethod(Enum): 

8 """Represents an HTTP method.""" 

9 

10 GET = "GET" 

11 """Retrieves data from a server. 

12 It only reads data and does not modify it.""" 

13 POST = "POST" 

14 """Submits data to a server to create a new resource. 

15 It can also be used to update existing resources.""" 

16 PUT = "PUT" 

17 """Updates a existing resource on a server. 

18 It can also be used to create a new resource.""" 

19 PATCH = "PATCH" 

20 """Updates a existing resource on a server. 

21 It only updates the fields that are provided in the request body.""" 

22 DELETE = "DELETE" 

23 """Deletes a resource from a server.""" 

24 HEAD = "HEAD" 

25 """Retrieves metadata from a server. 

26 It only reads the headers and does not return the response body.""" 

27 OPTIONS = "OPTIONS" 

28 """Provides information about the HTTP methods supported by a server. 

29 It can be used for Cross-Origin Resource Sharing (CORS) request.""" 

30 

31 

32@dataclass(frozen=True) 

33class URL: 

34 """A dataclass containing the parsed URL components.""" 

35 

36 full_url: str 

37 """The full URL.""" 

38 base_url: str = "" 

39 """The base URL, without query parameters.""" 

40 secure: bool = False 

41 """Whether the URL is secure (https/wss).""" 

42 protocol: str = "" 

43 """The protocol of the URL.""" 

44 path: str = "" 

45 """The path of the URL.""" 

46 domain_with_port: str = "" 

47 """The domain of the URL with port.""" 

48 domain: str = "" 

49 """The domain of the URL.""" 

50 port: Optional[int] = None 

51 """The port of the URL.""" 

52 params: dict[str, list[str]] = field(default_factory=dict) 

53 """A dictionary of query parameters.""" 

54 

55 def __post_init__(self) -> None: 

56 parsed_url = urlparse(self.full_url) 

57 

58 object.__setattr__(self, "base_url", parsed_url._replace(query="").geturl()) 

59 object.__setattr__(self, "secure", parsed_url.scheme in ["https", "wss"]) 

60 object.__setattr__(self, "protocol", parsed_url.scheme) 

61 

62 object.__setattr__(self, "path", parsed_url.path) 

63 

64 full_domen = parsed_url.netloc.split(":") 

65 object.__setattr__(self, "domain_with_port", parsed_url.netloc) 

66 object.__setattr__(self, "domain", full_domen[0]) 

67 if len(full_domen) > 1: 

68 object.__setattr__(self, "port", int(full_domen[1])) 

69 

70 object.__setattr__(self, "params", parse_qs(parsed_url.query))