Passed
Push — main ( 2e04c3...4e4ece )
by Jochen
05:30
created

byceps.util.l10n.get_current_user_locale()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 0
dl 0
loc 7
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
c 0
b 0
f 0
1
"""
2
byceps.util.l10n
3
~~~~~~~~~~~~~~~~
4
5
Localization.
6
7
:Copyright: 2006-2021 Jochen Kupperschmidt
8
:License: Revised BSD (see `LICENSE` file for details)
9
"""
10
11 1
from __future__ import annotations
12 1
import locale
13 1
from typing import Optional
14 1
import warnings
15
16 1
from babel import Locale
17 1
from flask import current_app, g
18 1
from wtforms import Form
19
20
21 1
def set_locale(locale_str: str) -> None:
22 1
    try:
23 1
        locale.setlocale(locale.LC_ALL, locale_str)
24 1
    except locale.Error:
25 1
        warnings.warn(f'Could not set locale to "{locale_str}".')
26
27
28 1
def get_current_user_locale() -> Optional[str]:
29
    """Return the locale for the current user, if available."""
30 1
    user = getattr(g, 'user')
31 1
    if user is None:
32
        return None
33
34 1
    return user.locale
35
36
37 1
BASE_LOCALE = Locale('en')
38
39
40 1
def get_locales() -> list[Locale]:
41
    """List available locales."""
42 1
    return [BASE_LOCALE] + current_app.babel_instance.list_translations()
43
44
45 1
class LocalizedForm(Form):
46
47 1
    def __init__(self, *args, **kwargs):
48 1
        locales = current_app.config['LOCALES_FORMS']
49 1
        kwargs['meta'] = {'locales': locales}
50
        super().__init__(*args, **kwargs)
51