Skip to content

functions

utilities.functions ¤

Attributes¤

menu_item_divider_html = '<div class="dropdown-divider"></div>' module-attribute ¤

menu_item_html = '<a class="dropdown-item" href="{url}">{name}</a>' module-attribute ¤

menu_tab_html = '\n<li class="nav-item dropdown">\n <a class="nav-link dropdown-toggle" href="#" id="navbarInfoRed" role="button"\n data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">\n {tab}\n </a>\n <div class="dropdown-menu" aria-labelledby="navbarDropdown">\n {items}\n </div>\n</li>\n' module-attribute ¤

Classes¤

objdict ¤

Bases: dict

Dictionary whose content can be manipulated as attributes.

NOTE: Might be a better option to do this. Needs deeper analysis. NOTE: To be moved to a separates 'utilities' module.

Functions¤

dictfetchall(cursor) ¤

Return all rows from a cursor as a list of dict.

TODO: This is used to process low level SQL requests, so chances are it will not be needed once we are done with this. NOTE: To be moved to a separates 'utilities' module.

Parameters:

Name Type Description Default
cursor ?

?

required

Returns:

Type Description
list[dict]

List[Dict]: ?

Source code in utilities/functions.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def dictfetchall(cursor) -> list[dict]:
    """Return all rows from a cursor as a list of dict.

    TODO: This is used to process low level SQL requests, so chances are it will not be
    needed once we are done with this.
    NOTE: To be moved to a separates 'utilities' module.

    Args:
        cursor (?): ?

    Returns:
        List[Dict]: ?
    """
    columns = [col[0] for col in cursor.description]
    return [dict(zip(columns, row)) for row in cursor.fetchall()]

get_menu(user) ¤

Generate the user menu in HTML, depending on its permissions.

Parameters:

Name Type Description Default
user User

The user to generate the menu for.

required

Returns:

Name Type Description
str str

An HTML string with the menu items.

Source code in utilities/functions.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def get_menu(user: User) -> str:
    """Generate the user menu in HTML, depending on its permissions.

    Args:
        user (User): The user to generate the menu for.

    Returns:
        str: An HTML string with the menu items.
    """
    if user.is_anonymous:  # TODO check this new logic if this function is ever used
        perms = Permission.objects.filter(Q(user=user) | Q(group__in=user.groups.all()))
        is_superuser = False
    else:
        perms = Permission.objects.filter(Q(user=user) | Q(group__in=user.groups.all()))
        is_superuser = user.is_superuser

    menu = ""
    for tab in menu_struct():
        items = ""
        last_is_divider = True
        i = 0

        for elements in tab.items:
            if elements.name == "":
                if last_is_divider:
                    continue
                items += menu_item_divider_html
                last_is_divider = True
                continue

            app, codename = elements.permission.split(".")
            if (
                perms.filter(content_type__app_label=app, codename=codename).exists()
                or is_superuser
            ):
                try:
                    url = reverse(elements.url_name)
                except Exception:
                    msg = f"URL '{elements.url_name}' not found when creating menu."
                    getLogger().debug(msg)
                    continue

                items += menu_item_html.format(url=url, name=elements.name)
                last_is_divider = False
                i += 1

        if i > 0:
            menu += menu_tab_html.format(tab=tab.name, items=items)

    return menu

menu_struct(filename=None) cached ¤

Returns the menu structure.

As the function is cached, it will be called only once when the webapp is launched.

Parameters:

Name Type Description Default
filename str

Name of the file to load

None

Returns:

Type Description
list[Tab]

List[Tab]: A list of tabs to include.

Source code in utilities/frontend_menu/constants.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@lru_cache
def menu_struct(filename: Path | None = None) -> list[Tab]:
    """Returns the menu structure.

    As the function is cached, it will be called only once when the webapp is launched.

    Args:
        filename (str): Name of the file to load

    Returns:
        List[Tab]: A list of tabs to include.
    """
    if filename is None:
        filename = Path(__file__).parent / "menu.json"

    with filename.open("r") as f:
        struct = json.load(f)

    formatted: list[Tab] = []
    for tab, details in struct.items():
        entries: list[Entry] = []
        for entry in details.get("items", []):
            entries.append(Entry(**entry))
        formatted.append(Tab(tab, details.get("permission", ""), entries))

    return formatted

modelo_a_tabla_html(modelo, col_extra) ¤

Extracts the entries in a query as an HTML table.

NOTE: To be moved to a separates 'utilities' module. NOTE: There's no need to do this manually, we should use django-tables2 for this: https://django-tables2.readthedocs.io/en/latest/

Parameters:

Name Type Description Default
modelo QuerySet

Objects to extract as HTML

required
col_extra bool

If an extra column need to be included at the end.

required

Returns:

Name Type Description
str str

Table in HTML with the contents of a model

Source code in utilities/functions.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def modelo_a_tabla_html(modelo: QuerySet, col_extra: bool) -> str:
    """Extracts the entries in a query as an HTML table.

    NOTE: To be moved to a separates 'utilities' module.
    NOTE: There's no need to do this manually, we should use django-tables2 for
                this: https://django-tables2.readthedocs.io/en/latest/

    Args:
        modelo (QuerySet): Objects to extract as HTML
        col_extra (bool): If an extra column need to be included at the end.

    Returns:
        str: Table in HTML with the contents of a model
    """
    html_cola = "</td></tr>"
    if col_extra:
        html_cola = "</td><td></td></tr>"
    html = ""
    for row in modelo:
        html += "<tr><td>" + "</td><td>".join([str(i or "") for i in row]) + html_cola
    return html