本文整理匯總了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()