]>
Commit | Line | Data |
---|---|---|
9137135a MT |
1 | #!/usr/bin/python |
2 | ||
3 | import httplib | |
4 | import time | |
5 | import tornado.locale | |
6 | import tornado.web | |
7 | ||
8 | import backend | |
9 | import backend.misc | |
10 | ||
11 | class BaseHandler(tornado.web.RequestHandler): | |
12 | def get_current_user(self): | |
13 | user = self.get_secure_cookie("user") | |
14 | if not user: | |
15 | return | |
16 | ||
17 | return self.pakfire.users.get_by_name(user) | |
18 | ||
19 | def get_user_locale(self): | |
20 | DEFAULT_LOCALE = tornado.locale.get("en_US") | |
21 | ALLOWED_LOCALES = \ | |
22 | [tornado.locale.get(l) for l in tornado.locale.get_supported_locales(None)] | |
23 | ||
24 | # One can append "?locale=de" to mostly and URI on the site and | |
25 | # another output that guessed. | |
26 | locale = self.get_argument("locale", None) | |
27 | if locale: | |
28 | locale = tornado.locale.get(locale) | |
29 | for locale in ALLOWED_LOCALES: | |
30 | return locale | |
31 | ||
32 | # Get the locale from the user settings. | |
33 | if self.current_user and self.current_user.locale: | |
34 | locale = tornado.locale.get(self.current_user.locale) | |
35 | if locale in ALLOWED_LOCALES: | |
36 | return locale | |
37 | ||
38 | # If no locale was provided we guess what the browser sends us | |
39 | locale = self.get_browser_locale() | |
40 | if locale in ALLOWED_LOCALES: | |
41 | return locale | |
42 | ||
43 | # If no one of the cases above worked we use our default locale | |
44 | return DEFAULT_LOCALE | |
45 | ||
46 | @property | |
47 | def render_args(self): | |
48 | return { | |
49 | "hostname" : self.request.host, | |
50 | "friendly_size" : backend.misc.friendly_size, | |
51 | "lang" : self.locale.code[:2], | |
52 | "year" : time.strftime("%Y"), | |
53 | } | |
54 | ||
55 | def render(self, *args, **kwargs): | |
56 | kwargs.update(self.render_args) | |
57 | tornado.web.RequestHandler.render(self, *args, **kwargs) | |
58 | ||
59 | def render_string(self, *args, **kwargs): | |
60 | kwargs.update(self.render_args) | |
61 | return tornado.web.RequestHandler.render_string(self, *args, **kwargs) | |
62 | ||
63 | def get_error_html(self, status_code, **kwargs): | |
64 | if status_code in (404, 500): | |
65 | render_args = ({ | |
66 | "code" : status_code, | |
67 | "exception" : kwargs.get("exception", None), | |
68 | "message" : httplib.responses[status_code], | |
69 | }) | |
70 | return self.render_string("error-%s.html" % status_code, **render_args) | |
71 | else: | |
72 | return tornado.web.RequestHandler.get_error_html(self, status_code, **kwargs) | |
73 | ||
74 | @property | |
75 | def pakfire(self): | |
76 | return self.application.pakfire | |
77 |