Coverage for requests_tracker/templatetags/style_tags.py: 100%
55 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-18 22:19 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-18 22:19 +0000
1import colorsys
2from typing import List
4from django import template
5from django.template.defaultfilters import stringfilter
7from requests_tracker.sql.dataclasses import SQLQueryInfo
9register = template.Library()
12@register.filter("method_class")
13@stringfilter
14def method_bulma_color_class(method: str) -> str:
15 """Takes in HTTP method and returns a bulma class for colorization"""
16 if method == "GET":
17 return "is-info"
18 elif method == "POST":
19 return "is-success"
20 elif method == "PUT":
21 return "is-warning"
22 elif method == "PATCH":
23 return "is-warning is-light"
24 elif method == "DELETE":
25 return "is-danger"
26 else:
27 return ""
30@register.filter("status_code_class")
31@stringfilter
32def status_code_bulma_color_class(status_code_str: str) -> str:
33 """Takes in HTTP status code and returns a bulma class for colorization"""
35 try:
36 status_code = int(status_code_str)
37 except ValueError:
38 status_code = 0
40 if 200 > status_code >= 100:
41 return "is-info"
42 elif 300 > status_code >= 200:
43 return "is-success"
44 elif 400 > status_code >= 300:
45 return "is-link"
46 elif 500 > status_code >= 400:
47 return "is-warning"
48 elif status_code >= 500:
49 return "is-danger"
51 return "is-dark"
54@register.simple_tag
55def contrast_color_from_number(color_number: int) -> str:
56 starting_color = 0.6 # Blue ish color
57 shift = 0.1 * (color_number // 4) # Shift by 10% for every 4 numbers
58 color_addition = 0.25 * color_number # Cycle the color scheme 25% at a time
60 hue = (starting_color + color_addition + shift) % 1 # Only want decimal part
61 saturation = 0.65
62 value = 0.7
64 hsv_tuple = (hue, saturation, value)
66 return "#" + "".join(
67 f"{int(color * 255):02x}" for color in colorsys.hsv_to_rgb(*hsv_tuple)
68 )
71@register.simple_tag
72def timeline_bar_styles(
73 queries: List[SQLQueryInfo],
74 total_sql_time: float,
75 current_index: int,
76) -> str:
77 current_query = queries[current_index]
78 percentage = (current_query.duration / total_sql_time) * 100
79 offset_percentage = (
80 sum(query.duration for query in queries[:current_index]) / total_sql_time * 100
81 )
83 color = contrast_color_from_number(current_index + 100)
84 return (
85 f"width: {percentage:.3f}%; "
86 f"margin-left: {offset_percentage:.3f}%; "
87 f"background-color: {color};"
88 )