.. automethod:: RequestHandler.get_status
.. automethod:: RequestHandler.get_template_path
.. automethod:: RequestHandler.get_user_locale
+ .. autoattribute:: RequestHandler.locale
.. automethod:: RequestHandler.log_exception
.. automethod:: RequestHandler.on_connection_close
.. automethod:: RequestHandler.require_setting
from tornado.escape import json_decode, utf8, to_unicode, recursive_unicode, native_str, to_basestring
from tornado.httputil import format_timestamp
from tornado.iostream import IOStream
+from tornado import locale
from tornado.log import app_log, gen_log
from tornado.simple_httpclient import SimpleAsyncHTTPClient
from tornado.template import DictLoader
import os
import re
import socket
-import sys
try:
import urllib.parse as urllib_parse # py3
@wsgi_safe
-class SetCurrentUserTest(SimpleHandlerTestCase):
+class SetLazyPropertiesTest(SimpleHandlerTestCase):
class Handler(RequestHandler):
def prepare(self):
self.current_user = 'Ben'
+ self.locale = locale.get('en_US')
+
+ def get_user_locale(self):
+ raise NotImplementedError()
+
+ def get_current_user(self):
+ raise NotImplementedError()
def get(self):
- self.write('Hello %s' % self.current_user)
+ self.write('Hello %s (%s)' % (self.current_user, self.locale.code))
- def test_set_current_user(self):
+ def test_set_properties(self):
# Ensure that current_user can be assigned to normally for apps
# that want to forgo the lazy get_current_user property
response = self.fetch('/')
- self.assertEqual(response.body, b'Hello Ben')
+ self.assertEqual(response.body, b'Hello Ben (en_US)')
@wsgi_safe
@property
def locale(self):
- """The local for the current session.
+ """The locale for the current session.
Determined by either `get_user_locale`, which you can override to
set the locale based on, e.g., a user preference stored in a
database, or `get_browser_locale`, which uses the ``Accept-Language``
header.
+
+ .. versionchanged: 4.1
+ Added a property setter.
"""
if not hasattr(self, "_locale"):
self._locale = self.get_user_locale()
assert self._locale
return self._locale
+ @locale.setter
+ def locale(self, value):
+ self._locale = value
+
def get_user_locale(self):
"""Override to determine the locale from the authenticated user.