本文整理汇总了Python中tornado.locale.get方法的典型用法代码示例。如果您正苦于以下问题:Python locale.get方法的具体用法?Python locale.get怎么用?Python locale.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.locale
的用法示例。
在下文中一共展示了locale.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: initialize
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def initialize(self):
"""子类初始化(Hook).
作为url spec的第三个参数传递的字典, 将作为关键字参数提供给
initialize().
例子::
class ProfileHandler(RequestHandler):
def initialize(self, database):
self.database = database
def get(self, username):
...
app = Application([
(r'/user/(.*)', ProfileHandler, dict(database=database)),
])
"""
pass
示例2: decode_argument
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def decode_argument(self, value, name=None):
"""从请求中解码一个参数.
这个参数已经被解码现在是一个字节字符串(byte string). 默认情况下,
这个方法会把参数解码成utf-8并且返回一个unicode字符串, 但是它可以
被子类复写.
这个方法既可以在 `get_argument()` 中被用作过滤器, 也可以用来从url
中提取值并传递给 `get()`/`post()`/等.
如果知道的话参数的name会被提供, 但也可能为None
(e.g. 在url正则表达式中未命名的组).
"""
try:
return _unicode(value)
except UnicodeDecodeError:
raise HTTPError(400, "Invalid unicode in %s: %r" %
(name or "url", value[:40]))
示例3: write_error
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def write_error(self, status_code, **kwargs):
"""复写这个方法来实现自定义错误页.
``write_error`` 可能调用 `write`, `render`, `set_header`,等
来产生一般的输出.
如果错误是由未捕获的异常造成的(包括HTTPError), 三个一组的
``exc_info`` 将变成可用的通过 ``kwargs["exc_info"]``.
注意这个异常可能不是"当前(current)" 目的或方法的异常就像
``sys.exc_info()`` 或 ``traceback.format_exc``.
"""
if self.settings.get("serve_traceback") and "exc_info" in kwargs:
# in debug mode, try to send a traceback
self.set_header('Content-Type', 'text/plain')
for line in traceback.format_exception(*kwargs["exc_info"]):
self.write(line)
self.finish()
else:
self.finish("<html><title>%(code)d: %(message)s</title>"
"<body>%(code)d: %(message)s</body></html>" % {
"code": status_code,
"message": self._reason,
})
示例4: get_browser_locale
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def get_browser_locale(self, default="en_US"):
"""从 ``Accept-Language`` 头决定用户的位置.
参考 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
"""
if "Accept-Language" in self.request.headers:
languages = self.request.headers["Accept-Language"].split(",")
locales = []
for language in languages:
parts = language.strip().split(";")
if len(parts) > 1 and parts[1].startswith("q="):
try:
score = float(parts[1][2:])
except (ValueError, TypeError):
score = 0.0
else:
score = 1.0
locales.append((parts[0], score))
if locales:
locales.sort(key=lambda pair: pair[1], reverse=True)
codes = [l[0] for l in locales]
return locale.get(*codes)
return locale.get(default)
示例5: should_return_304
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def should_return_304(self):
"""如果头部表明我们应该返回304则返回True.
.. versionadded:: 3.1
"""
if self.check_etag_header():
return True
# Check the If-Modified-Since, and don't send the result if the
# content has not been modified
ims_value = self.request.headers.get("If-Modified-Since")
if ims_value is not None:
date_tuple = email.utils.parsedate(ims_value)
if date_tuple is not None:
if_since = datetime.datetime(*date_tuple[:6])
if if_since >= self.modified:
return True
return False
示例6: make_static_url
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def make_static_url(cls, settings, path, include_version=True):
"""为给定路径构造一个的有版本的url.
这个方法可以在子类中被复写(但是注意他是一个类方法而不是一个
实例方法). 子类只需实现签名
``make_static_url(cls, settings, path)``; 其他关键字参数可
以通过 `~RequestHandler.static_url` 传递, 但这不是标准.
``settings`` 是 `Application.settings` 字典. ``path``
是被请求的静态路径. 返回的url应该是相对于当前host的.
``include_version`` 决定生成的URL是否应该包含含有给定
``path`` 相对应文件的hash版本查询字符串.
"""
url = settings.get('static_url_prefix', '/static/') + path
if not include_version:
return url
version_hash = cls.get_version(settings, path)
if not version_hash:
return url
return '%s?v=%s' % (url, version_hash)
示例7: _decode_fields_v2
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def _decode_fields_v2(value):
def _consume_field(s):
length, _, rest = s.partition(b':')
n = int(length)
field_value = rest[:n]
# In python 3, indexing bytes returns small integers; we must
# use a slice to get a byte string as in python 2.
if rest[n:n + 1] != b'|':
raise ValueError("malformed v2 signed value field")
rest = rest[n + 1:]
return field_value, rest
rest = value[2:] # remove version number
key_version, rest = _consume_field(rest)
timestamp, rest = _consume_field(rest)
name_field, rest = _consume_field(rest)
value_field, passed_sig = _consume_field(rest)
return int(key_version), timestamp, name_field, value_field, passed_sig
示例8: test_cookie_special_char
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def test_cookie_special_char(self):
response = self.fetch("/special_char")
headers = sorted(response.headers.get_list("Set-Cookie"))
self.assertEqual(len(headers), 3)
self.assertEqual(headers[0], 'equals="a=b"; Path=/')
self.assertEqual(headers[1], 'quote="a\\"b"; Path=/')
# python 2.7 octal-escapes the semicolon; older versions leave it alone
self.assertTrue(headers[2] in ('semicolon="a;b"; Path=/',
'semicolon="a\\073b"; Path=/'),
headers[2])
data = [('foo=a=b', 'a=b'),
('foo="a=b"', 'a=b'),
('foo="a;b"', 'a;b'),
# ('foo=a\\073b', 'a;b'), # even encoded, ";" is a delimiter
('foo="a\\073b"', 'a;b'),
('foo="a\\"b"', 'a"b'),
]
for header, expected in data:
logging.debug("trying %r", header)
response = self.fetch("/get", headers={"Cookie": header})
self.assertEqual(response.body, utf8(expected))
示例9: get
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def get(self, *path_args):
# Type checks: web.py interfaces convert argument values to
# unicode strings (by default, but see also decode_argument).
# In httpserver.py (i.e. self.request.arguments), they're left
# as bytes. Keys are always native strings.
for key in self.request.arguments:
if type(key) != str:
raise Exception("incorrect type for key: %r" % type(key))
for value in self.request.arguments[key]:
if type(value) != bytes:
raise Exception("incorrect type for value: %r" %
type(value))
for value in self.get_arguments(key):
if type(value) != unicode_type:
raise Exception("incorrect type for value: %r" %
type(value))
for arg in path_args:
if type(arg) != unicode_type:
raise Exception("incorrect type for path arg: %r" % type(arg))
self.write(dict(path=self.request.path,
path_args=path_args,
args=recursive_unicode(self.request.arguments)))
示例10: get_and_head
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def get_and_head(self, *args, **kwargs):
"""Performs a GET and HEAD request and returns the GET response.
Fails if any ``Content-*`` headers returned by the two requests
differ.
"""
head_response = self.fetch(*args, method="HEAD", **kwargs)
get_response = self.fetch(*args, method="GET", **kwargs)
content_headers = set()
for h in itertools.chain(head_response.headers, get_response.headers):
if h.startswith('Content-'):
content_headers.add(h)
for h in content_headers:
self.assertEqual(head_response.headers.get(h),
get_response.headers.get(h),
"%s differs between GET (%s) and HEAD (%s)" %
(h, head_response.headers.get(h),
get_response.headers.get(h)))
return get_response
示例11: get_handlers
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def get_handlers(self):
test = self
self.server_error = None
# Manually set a content-length that doesn't match the actual content.
class TooHigh(RequestHandler):
def get(self):
self.set_header("Content-Length", "42")
try:
self.finish("ok")
except Exception as e:
test.server_error = e
raise
class TooLow(RequestHandler):
def get(self):
self.set_header("Content-Length", "2")
try:
self.finish("hello")
except Exception as e:
test.server_error = e
raise
return [('/high', TooHigh),
('/low', TooLow)]
示例12: get
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def get(self, *args, **kwargs):
raise HTTPError(405)
示例13: prepare
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def prepare(self):
"""在每个请求的最开始被调用, 在 `get`/`post`/等方法之前.
通过复写这个方法, 可以执行共同的初始化, 而不用考虑每个请求方法.
异步支持: 这个方法使用 `.gen.coroutine` 或 `.return_future`
装饰器来使它异步( `asynchronous` 装饰器不能被用在 `prepare`).
如果这个方法返回一个 `.Future` 对象, 执行将不再进行, 直到
`.Future` 对象完成.
.. versionadded:: 3.1
异步支持.
"""
pass
示例14: _get_arguments
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def _get_arguments(self, name, source, strip=True):
values = []
for v in source.get(name, []):
v = self.decode_argument(v, name=name)
if isinstance(v, unicode_type):
# Get rid of any weird control chars (unless decoding gave
# us bytes, in which case leave it alone)
v = RequestHandler._remove_control_chars_regex.sub(" ", v)
if strip:
v = v.strip()
values.append(v)
return values
示例15: send_error
# 需要导入模块: from tornado import locale [as 别名]
# 或者: from tornado.locale import get [as 别名]
def send_error(self, status_code=500, **kwargs):
"""给浏览器发送给定的HTTP 错误码.
如果 `flush()` 已经被调用, 它是不可能发送错误的, 所以这个方法将终止
响应. 如果输出已经被写但尚未flush, 它将被丢弃并被错误页代替.
复写 `write_error()` 来自定义它返回的错误页. 额外的关键字参数将
被传递给 `write_error`.
"""
if self._headers_written:
gen_log.error("Cannot send error response after headers written")
if not self._finished:
# If we get an error between writing headers and finishing,
# we are unlikely to be able to finish due to a
# Content-Length mismatch. Try anyway to release the
# socket.
try:
self.finish()
except Exception:
gen_log.error("Failed to flush partial response",
exc_info=True)
return
self.clear()
reason = kwargs.get('reason')
if 'exc_info' in kwargs:
exception = kwargs['exc_info'][1]
if isinstance(exception, HTTPError) and exception.reason:
reason = exception.reason
self.set_status(status_code, reason=reason)
try:
self.write_error(status_code, **kwargs)
except Exception:
app_log.error("Uncaught exception in write_error", exc_info=True)
if not self._finished:
self.finish()