當前位置: 首頁>>代碼示例>>Python>>正文


Python web.html方法代碼示例

本文整理匯總了Python中tornado.web.html方法的典型用法代碼示例。如果您正苦於以下問題:Python web.html方法的具體用法?Python web.html怎麽用?Python web.html使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在tornado.web的用法示例。


在下文中一共展示了web.html方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: write_error

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [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,
                        }) 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:25,代碼來源:web.py

示例2: get_browser_locale

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [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) 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:25,代碼來源:web.py

示例3: write_error

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [as 別名]
def write_error(self, status_code: int, **kwargs: Any) -> None:
        """Override to implement custom error pages.

        ``write_error`` may call `write`, `render`, `set_header`, etc
        to produce output as usual.

        If this error was caused by an uncaught exception (including
        HTTPError), an ``exc_info`` triple will be available as
        ``kwargs["exc_info"]``.  Note that this exception may not be
        the "current" exception for purposes of methods like
        ``sys.exc_info()`` or ``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}
            ) 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:26,代碼來源:web.py

示例4: get_browser_locale

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [as 別名]
def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale:
        """Determines the user's locale from ``Accept-Language`` header.

        See 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) 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:25,代碼來源:web.py

示例5: write_error

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [as 別名]
def write_error(self, status_code, **kwargs):
        """Override to implement custom error pages.

        ``write_error`` may call `write`, `render`, `set_header`, etc
        to produce output as usual.

        If this error was caused by an uncaught exception (including
        HTTPError), an ``exc_info`` triple will be available as
        ``kwargs["exc_info"]``.  Note that this exception may not be
        the "current" exception for purposes of methods like
        ``sys.exc_info()`` or ``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,
                        }) 
開發者ID:tp4a,項目名稱:teleport,代碼行數:26,代碼來源:web.py

示例6: get_browser_locale

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [as 別名]
def get_browser_locale(self, default="en_US"):
        """Determines the user's locale from ``Accept-Language`` header.

        See 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) 
開發者ID:tp4a,項目名稱:teleport,代碼行數:25,代碼來源:web.py

示例7: clear

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [as 別名]
def clear(self):
        """重置這個響應的所有頭部和內容."""
        self._headers = httputil.HTTPHeaders({
            "Server": "TornadoServer/%s" % tornado.version,
            "Content-Type": "text/html; charset=UTF-8",
            "Date": httputil.format_timestamp(time.time()),
        })
        self.set_default_headers()
        self._write_buffer = []
        self._status_code = 200
        self._reason = httputil.responses[200] 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:13,代碼來源:web.py

示例8: set_cookie

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [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 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:41,代碼來源:web.py

示例9: write

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [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) 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:28,代碼來源:web.py

示例10: clear

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [as 別名]
def clear(self) -> None:
        """Resets all headers and content for this response."""
        self._headers = httputil.HTTPHeaders(
            {
                "Server": "TornadoServer/%s" % tornado.version,
                "Content-Type": "text/html; charset=UTF-8",
                "Date": httputil.format_timestamp(time.time()),
            }
        )
        self.set_default_headers()
        self._write_buffer = []  # type: List[bytes]
        self._status_code = 200
        self._reason = httputil.responses[200] 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:15,代碼來源:web.py

示例11: write

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [as 別名]
def write(self, chunk: Union[str, bytes, dict]) -> None:
        """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/2009/06/25/json-hijacking.aspx/ and
        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"  # noqa: E501
                )
            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) 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:33,代碼來源:web.py

示例12: clear

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [as 別名]
def clear(self):
        """Resets all headers and content for this response."""
        self._headers = httputil.HTTPHeaders({
            "Server": "TornadoServer/%s" % tornado.version,
            "Content-Type": "text/html; charset=UTF-8",
            "Date": httputil.format_timestamp(time.time()),
        })
        self.set_default_headers()
        self._write_buffer = []
        self._status_code = 200
        self._reason = httputil.responses[200] 
開發者ID:tp4a,項目名稱:teleport,代碼行數:13,代碼來源:web.py

示例13: write

# 需要導入模塊: from tornado import web [as 別名]
# 或者: from tornado.web import html [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/2009/06/25/json-hijacking.aspx/ and
        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) 
開發者ID:tp4a,項目名稱:teleport,代碼行數:31,代碼來源:web.py


注:本文中的tornado.web.html方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。