Coverage for an_website/whats_my_ip/ip.py: 89.474%

19 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-06-10 18:56 +0000

1# This program is free software: you can redistribute it and/or modify 

2# it under the terms of the GNU Affero General Public License as 

3# published by the Free Software Foundation, either version 3 of the 

4# License, or (at your option) any later version. 

5# 

6# This program is distributed in the hope that it will be useful, 

7# but WITHOUT ANY WARRANTY; without even the implied warranty of 

8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

9# GNU Affero General Public License for more details. 

10# 

11# You should have received a copy of the GNU Affero General Public License 

12# along with this program. If not, see <https://www.gnu.org/licenses/>. 

13 

14"""A page that tells users their IP address.""" 

15 

16from ipaddress import ip_address 

17 

18from ..utils.request_handler import APIRequestHandler, HTMLRequestHandler 

19from ..utils.utils import ModuleInfo 

20 

21 

22def get_module_info() -> ModuleInfo: 

23 """Create and return the ModuleInfo for this module.""" 

24 return ModuleInfo( 

25 handlers=( 

26 (r"/ip", IP), 

27 (r"/api/ip", IPAPI), 

28 ), 

29 name="IP-Informationen", 

30 description="Erfahre deine IP-Adresse", 

31 path="/ip", 

32 keywords=( 

33 "IP-Adresse", 

34 "Was ist meine IP?", 

35 ), 

36 ) 

37 

38 

39class IPAPI(APIRequestHandler): 

40 """The request handler for the IP API.""" 

41 

42 async def get(self, *, head: bool = False) -> None: 

43 """Handle GET requests to the IP API.""" 

44 if head: 

45 return 

46 

47 if geoip := await self.geoip(): 

48 return await self.finish_dict( 

49 ip=self.request.remote_ip, 

50 country=geoip.get("country_flag"), 

51 ) 

52 

53 return await self.finish_dict(ip=self.request.remote_ip) 

54 

55 

56class IP(HTMLRequestHandler): 

57 """The request handler for the IP page.""" 

58 

59 async def get(self, *, head: bool = False) -> None: 

60 """Handle GET requests to the IP page.""" 

61 if head: 

62 return 

63 

64 if not self.request.remote_ip: 

65 return await self.render( 

66 "pages/empty.html", 

67 text="IP-Adresse konnte nicht ermittelt werden.", 

68 ) 

69 

70 await self.render( 

71 "pages/ip.html", 

72 ip=self.request.remote_ip, 

73 flag=( 

74 "🔁" 

75 if ip_address(self.request.remote_ip).is_loopback 

76 else (await self.geoip() or {}).get("country_flag") or "❔" 

77 ), 

78 )