Coverage for sm / utils.py: 49%

39 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-03-24 12:43 +0000

1import os 

2from stat import S_ISDIR, ST_MODE 

3 

4try: 

5 from .settings import DEBUG 

6except Exception: 

7 DEBUG = False 

8 

9import random 

10import string 

11import hashlib 

12from libravatar import libravatar_url 

13 

14 

15def get_libravatar_url(email, size=80, default="mm"): 

16 """ 

17 Get Libravatar URL for an email address 

18 """ 

19 return libravatar_url(email=email, size=size, default=default) 

20 

21 

22def get_email_hash(email): 

23 """ 

24 Returns MD5 hash of lowercase email for avatar services. 

25 """ 

26 if not email: 

27 return "00000000000000000000000000000000" 

28 return hashlib.md5(email.lower().encode("utf-8")).hexdigest() 

29 

30 

31def random_string(len=10): 

32 return "".join( 

33 random.SystemRandom().choice(string.ascii_lowercase + string.digits) 

34 for _ in range(10) 

35 ) 

36 

37 

38def random_number(start=0, end=10): 

39 return random.randint(start, end) 

40 

41 

42def modules_with_urls(): 

43 """ 

44 Simple function that automatically adds/loads urls from app directories 

45 (eg. myapp/urls.py will be automatically added) 

46 This is best called from your projects urls.py 

47 """ 

48 path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..")) 

49 selfmod = os.path.basename(os.path.realpath(os.path.dirname(__file__))) 

50 if DEBUG: 

51 print("Searching in %s" % path) # pragma: no cover 

52 installed = [] 

53 for module in os.listdir(path): 

54 mode = os.stat(module)[ST_MODE] 

55 # Skip files 

56 if not S_ISDIR(mode): 

57 continue 

58 # Skip 'self' 

59 if selfmod == module: 

60 continue 

61 

62 if os.path.isfile(os.path.join(module, "__init__.py")): 

63 if os.path.isfile(os.path.join(module, "urls.py")): 

64 if DEBUG: # pragma: no cover 

65 print("Found '%s' module with urls" % module) # pragma: no cover 

66 installed.append(module) 

67 else: 

68 if DEBUG: # pragma: no cover 

69 print( 

70 "%s doesn't have urls defined (yet)" % module 

71 ) # pragma: no cover 

72 return installed 

73 

74 

75def add_to_installed(INSTALLED_APPS): 

76 for mod in modules_with_urls(): 

77 if mod not in INSTALLED_APPS: 

78 INSTALLED_APPS.append(mod)