-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
executable file
·90 lines (74 loc) · 2.45 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python3
"""A Basic Flask app with internationalization support.
"""
import pytz
from typing import Union, Dict
from flask_babel import Babel, format_datetime
from flask import Flask, render_template, request, g
class Config:
"""Represents a Flask Babel configuration.
"""
LANGUAGES = ["en", "fr"]
BABEL_DEFAULT_LOCALE = "en"
BABEL_DEFAULT_TIMEZONE = "UTC"
app = Flask(__name__)
app.config.from_object(Config)
app.url_map.strict_slashes = False
babel = Babel(app)
users = {
1: {"name": "Balou", "locale": "fr", "timezone": "Europe/Paris"},
2: {"name": "Beyonce", "locale": "en", "timezone": "US/Central"},
3: {"name": "Spock", "locale": "kg", "timezone": "Vulcan"},
4: {"name": "Teletubby", "locale": None, "timezone": "Europe/London"},
}
def get_user() -> Union[Dict, None]:
"""Retrieves a user based on a user id.
"""
login_id = request.args.get('login_as', '')
if login_id:
return users.get(int(login_id), None)
return None
@app.before_request
def before_request() -> None:
"""Performs some routines before each request's resolution.
"""
user = get_user()
g.user = user
@babel.localeselector
def get_locale() -> str:
"""Retrieves the locale for a web page.
"""
queries = request.query_string.decode('utf-8').split('&')
query_table = dict(map(
lambda x: (x if '=' in x else '{}='.format(x)).split('='),
queries,
))
locale = query_table.get('locale', '')
if locale in app.config["LANGUAGES"]:
return locale
user_details = getattr(g, 'user', None)
if user_details and user_details['locale'] in app.config["LANGUAGES"]:
return user_details['locale']
header_locale = request.headers.get('locale', '')
if header_locale in app.config["LANGUAGES"]:
return header_locale
return app.config['BABEL_DEFAULT_LOCALE']
@babel.timezoneselector
def get_timezone() -> str:
"""Retrieves the timezone for a web page.
"""
timezone = request.args.get('timezone', '').strip()
if not timezone and g.user:
timezone = g.user['timezone']
try:
return pytz.timezone(timezone).zone
except pytz.exceptions.UnknownTimeZoneError:
return app.config['BABEL_DEFAULT_TIMEZONE']
@app.route('/')
def get_index() -> str:
"""The home/index page.
"""
g.time = format_datetime()
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)