本文整理匯總了Python中tornado.escape方法的典型用法代碼示例。如果您正苦於以下問題:Python tornado.escape方法的具體用法?Python tornado.escape怎麽用?Python tornado.escape使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類tornado
的用法示例。
在下文中一共展示了tornado.escape方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: set_status
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def set_status(self, status_code, reason=None):
"""設置響應的狀態碼.
:arg int status_code: 響應狀態碼. 如果 ``reason`` 是 ``None``,
它必須存在於 `httplib.responses <http.client.responses>`.
:arg string reason: 用人類可讀的原因短語來描述狀態碼.
如果是 ``None``, 它會由來自
`httplib.responses <http.client.responses>` 的reason填滿.
"""
self._status_code = status_code
if reason is not None:
self._reason = escape.native_str(reason)
else:
try:
self._reason = httputil.responses[status_code]
except KeyError:
raise ValueError("unknown status code %d", status_code)
示例2: set_status
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def set_status(self, status_code: int, reason: str = None) -> None:
"""Sets the status code for our response.
:arg int status_code: Response status code.
:arg str reason: Human-readable reason phrase describing the status
code. If ``None``, it will be filled in from
`http.client.responses` or "Unknown".
.. versionchanged:: 5.0
No longer validates that the response code is in
`http.client.responses`.
"""
self._status_code = status_code
if reason is not None:
self._reason = escape.native_str(reason)
else:
self._reason = httputil.responses.get(status_code, "Unknown")
示例3: render_linked_js
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def render_linked_js(self, js_files: Iterable[str]) -> str:
"""Default method used to render the final js links for the
rendered webpage.
Override this method in a sub-classed controller to change the output.
"""
paths = []
unique_paths = set() # type: Set[str]
for path in js_files:
if not is_absolute(path):
path = self.static_url(path)
if path not in unique_paths:
paths.append(path)
unique_paths.add(path)
return "".join(
'<script src="'
+ escape.xhtml_escape(p)
+ '" type="text/javascript"></script>'
for p in paths
)
示例4: xsrf_form_html
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def xsrf_form_html(self) -> str:
"""An HTML ``<input/>`` element to be included with all POST forms.
It defines the ``_xsrf`` input value, which we check on all POST
requests to prevent cross-site request forgery. If you have set
the ``xsrf_cookies`` application setting, you must include this
HTML within all of your HTML forms.
In a template, this method should be called with ``{% module
xsrf_form_html() %}``
See `check_xsrf_cookie()` above for more information.
"""
return (
'<input type="hidden" name="_xsrf" value="'
+ escape.xhtml_escape(self.xsrf_token)
+ '"/>'
)
示例5: set_status
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def set_status(self, status_code, reason=None):
"""Sets the status code for our response.
:arg int status_code: Response status code. If ``reason`` is ``None``,
it must be present in `httplib.responses <http.client.responses>`.
:arg string reason: Human-readable reason phrase describing the status
code. If ``None``, it will be filled in from
`httplib.responses <http.client.responses>`.
"""
self._status_code = status_code
if reason is not None:
self._reason = escape.native_str(reason)
else:
try:
self._reason = httputil.responses[status_code]
except KeyError:
raise ValueError("unknown status code %d", status_code)
示例6: write
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def write(self, chunk):
"""Writes the given chunk to the output buffer.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set
the Content-Type of the response to be ``application/json``.
(if you want to send JSON as a different ``Content-Type``, call
set_header *after* calling write()).
Note that lists are not converted to JSON because of a potential
cross-site security vulnerability. All JSON output should be
wrapped in a dictionary. More details at
http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
"""
if self._finished:
raise RuntimeError("Cannot write() after finish(). May be caused "
"by using async operations without the "
"@asynchronous decorator.")
if isinstance(chunk, dict):
chunk = escape.json_encode(chunk)
self.set_header("Content-Type", "application/json; charset=UTF-8")
chunk = utf8(chunk)
self._write_buffer.append(chunk)
示例7: set_status
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def set_status(self, status_code, reason=None):
"""Sets the status code for our response.
:arg int status_code: Response status code.
:arg str reason: Human-readable reason phrase describing the status
code. If ``None``, it will be filled in from
`http.client.responses` or "Unknown".
.. versionchanged:: 5.0
No longer validates that the response code is in
`http.client.responses`.
"""
self._status_code = status_code
if reason is not None:
self._reason = escape.native_str(reason)
else:
self._reason = httputil.responses.get(status_code, "Unknown")
示例8: render_linked_js
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def render_linked_js(self, js_files):
"""Default method used to render the final js links for the
rendered webpage.
Override this method in a sub-classed controller to change the output.
"""
paths = []
unique_paths = set()
for path in js_files:
if not is_absolute(path):
path = self.static_url(path)
if path not in unique_paths:
paths.append(path)
unique_paths.add(path)
return ''.join('<script src="' + escape.xhtml_escape(p) +
'" type="text/javascript"></script>'
for p in paths)
示例9: render_linked_css
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def render_linked_css(self, css_files: Iterable[str]) -> str:
"""Default method used to render the final css links for the
rendered webpage.
Override this method in a sub-classed controller to change the output.
"""
paths = []
unique_paths = set() # type: Set[str]
for path in css_files:
if not is_absolute(path):
path = self.static_url(path)
if path not in unique_paths:
paths.append(path)
unique_paths.add(path)
return "".join(
'<link href="' + escape.xhtml_escape(p) + '" '
'type="text/css" rel="stylesheet"/>'
for p in paths
)
示例10: set_cookie
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""設置給定的cookie 名稱/值還有其他給定的選項.
另外的關鍵字參數在Cookie.Morsel直接設置.
參見 https://docs.python.org/2/library/cookie.html#morsel-objects
查看可用的屬性.
"""
# The cookie library only accepts type str, in both python 2 and 3
name = escape.native_str(name)
value = escape.native_str(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if not hasattr(self, "_new_cookie"):
self._new_cookie = Cookie.SimpleCookie()
if name in self._new_cookie:
del self._new_cookie[name]
self._new_cookie[name] = value
morsel = self._new_cookie[name]
if domain:
morsel["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(
days=expires_days)
if expires:
morsel["expires"] = httputil.format_timestamp(expires)
if path:
morsel["path"] = path
for k, v in kwargs.items():
if k == 'max_age':
k = 'max-age'
# skip falsy values for httponly and secure flags because
# SimpleCookie sets them regardless
if k in ['httponly', 'secure'] and not v:
continue
morsel[k] = v
示例11: write
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def write(self, chunk):
"""把給定塊寫到輸出buffer.
為了把輸出寫到網絡, 使用下麵的flush()方法.
如果給定的塊是一個字典, 我們會把它作為JSON來寫同時會把響應頭
設置為 ``application/json``. (如果你寫JSON但是設置不同的
``Content-Type``, 可以調用set_header *在調用write()之後* ).
注意列表不能轉換為JSON 因為一個潛在的跨域安全漏洞. 所有的JSON
輸出應該包在一個字典中. 更多細節參考
http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ 和
https://github.com/facebook/tornado/issues/1009
"""
if self._finished:
raise RuntimeError("Cannot write() after finish()")
if not isinstance(chunk, (bytes, unicode_type, dict)):
message = "write() only accepts bytes, unicode, and dict objects"
if isinstance(chunk, list):
message += ". Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write"
raise TypeError(message)
if isinstance(chunk, dict):
chunk = escape.json_encode(chunk)
self.set_header("Content-Type", "application/json; charset=UTF-8")
chunk = utf8(chunk)
self._write_buffer.append(chunk)
示例12: xsrf_form_html
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def xsrf_form_html(self):
"""一個將被包含在所有POST表單中的HTML ``<input/>`` 標簽.
它定義了我們在所有POST請求中為了預防偽造跨站請求所檢查的
``_xsrf`` 的輸入值. 如果你設置了 ``xsrf_cookies`` application設置,
你必須包含這個HTML 在你所有的HTML表單.
在一個模板中, 這個方法應該使用 ``{% module xsrf_form_html() %}``
這種方式調用
查看上麵的 `check_xsrf_cookie()` 了解更多信息.
"""
return '<input type="hidden" name="_xsrf" value="' + \
escape.xhtml_escape(self.xsrf_token) + '"/>'
示例13: reverse
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def reverse(self, *args):
assert self._path is not None, \
"Cannot reverse url regex " + self.regex.pattern
assert len(args) == self._group_count, "required number of arguments "\
"not found"
if not len(args):
return self._path
converted_args = []
for a in args:
if not isinstance(a, (unicode_type, bytes)):
a = str(a)
converted_args.append(escape.url_escape(utf8(a), plus=False))
return self._path % tuple(converted_args)
示例14: _unquote_or_none
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def _unquote_or_none(s):
"""None-safe wrapper around url_unescape to handle unamteched optional
groups correctly.
Note that args are passed as bytes so the handler can decide what
encoding to use.
"""
if s is None:
return s
return escape.url_unescape(s, encoding=None, plus=False)
示例15: __call__
# 需要導入模塊: import tornado [as 別名]
# 或者: from tornado import escape [as 別名]
def __call__(self, request):
data = {}
response = []
def start_response(status, response_headers, exc_info=None):
data["status"] = status
data["headers"] = response_headers
return response.append
app_response = self.wsgi_application(
WSGIContainer.environ(request), start_response)
try:
response.extend(app_response)
body = b"".join(response)
finally:
if hasattr(app_response, "close"):
app_response.close()
if not data:
raise Exception("WSGI app did not call start_response")
status_code, reason = data["status"].split(' ', 1)
status_code = int(status_code)
headers = data["headers"]
header_set = set(k.lower() for (k, v) in headers)
body = escape.utf8(body)
if status_code != 304:
if "content-length" not in header_set:
headers.append(("Content-Length", str(len(body))))
if "content-type" not in header_set:
headers.append(("Content-Type", "text/html; charset=UTF-8"))
if "server" not in header_set:
headers.append(("Server", "TornadoServer/%s" % tornado.version))
start_line = httputil.ResponseStartLine("HTTP/1.1", status_code, reason)
header_obj = httputil.HTTPHeaders()
for key, value in headers:
header_obj.add(key, value)
request.connection.write_headers(start_line, header_obj, chunk=body)
request.connection.finish()
self._log(status_code, request)