tornado.web.Application類配置及使用

來源:互聯網
上載者:User

標籤:

Application configuration
class tornado.web. Application( handlers=Nonedefault_host=‘‘transforms=None**settings)[source]

A collection of request handlers that make up a web application.

Instances of this class are callable and can be passed directly to HTTPServer to serve the application:

application = web.Application([    (r"/", MainPageHandler),])http_server = httpserver.HTTPServer(application)http_server.listen(8080)ioloop.IOLoop.current().start()

The constructor for this class takes in a list of URLSpec objects or (regexp, request_class) tuples. When we receive requests, we iterate over the list in order and instantiate an instance of the first request class whose regexp matches the request path. The request class can be specified as either a class object or a (fully-qualified) name.

Each tuple can contain additional elements, which correspond to the arguments to the URLSpecconstructor. (Prior to Tornado 3.2, only tuples of two or three elements were allowed).

A dictionary may be passed as the third element of the tuple, which will be used as keyword arguments to the handler’s constructor and initialize method. This pattern is used for theStaticFileHandler in this example (note that a StaticFileHandler can be installed automatically with the static_path setting described below):

application = web.Application([    (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),])

We support virtual hosts with the add_handlers method, which takes in a host regular expression as the first argument:

application.add_handlers(r"www\.myhost\.com", [    (r"/article/([0-9]+)", ArticleHandler),])

You can serve static files by sending the static_path setting as a keyword argument. We will serve those files from the /static/ URI (this is configurable with the static_url_prefix setting), and we will serve /favicon.ico and /robots.txt from the same directory. A custom subclass ofStaticFileHandler can be specified with the static_handler_class setting.

settings

Additional keyword arguments passed to the constructor are saved in the settingsdictionary, and are often referred to in documentation as “application settings”. Settings are used to customize various aspects of Tornado (although in some cases richer customization is possible by overriding methods in a subclass of RequestHandler). Some applications also like to use the settings dictionary as a way to make application-specific settings available to handlers without using global variables. Settings used in Tornado are described below.

一般設定:

  • autoreload: 如果設定 True,如果檔案有變化進程將自動重啟, 在 Debug mode and automatic reloading(DeBug模式和自動裝載的情況下自動開啟).
  • debug: 幾種配置的集合, 具體查看 Debug mode and automatic reloading. 設定 debug=True 相當於設定 autoreload=True,compiled_template_cache=Falsestatic_hash_cache=Falseserve_traceback=True.
  • default_handler_class and default_handler_args: 在頁面沒有找到(404錯誤的時候)自訂404錯誤頁視圖動作類及參數
  • compress_response: 如果設定 True, responses(響應)將被自動壓縮
  • gzip: 在Tornado 4.0被compress_response代替
  • log_function: 這個函數用來回調 RequestHandler 對象的處理結果,預設主程式匯入logging並配置好的話會自動記錄.也可以定製Application.log_request這個方法.
  • serve_traceback: 如果設定 true,錯誤頁面將包含錯誤跟蹤
  • ui_modules and ui_methods: 配置 UIModule 或 UI methods配置模版可用的協助方法. 可以是一個模組、字典或一個模組或者字典的列表. 更多細節查看 UI modules

認證和安全設定:

  • cookie_secret: 被 RequestHandler.get_secure_cookie和set_secure_cookie用來配置cookie的標誌
  • key_version: 被 set_secure_cookie 用來配置cookie的標誌時cookie_secret的一個key
  • login_url: 如果沒有使用者登入這個 authenticated 裝飾器將被重新定義到. 可以進一步重寫 RequestHandler.get_login_url
  • xsrf_cookies: If true, Cross-site request forgery protection will be enabled.
  • xsrf_cookie_version: Controls the version of new XSRF cookies produced by this server. Should generally be left at the default (which will always be the highest supported version), but may be set to a lower value temporarily during version transitions. New in Tornado 3.2.2, which introduced XSRF cookie version 2.
  • xsrf_cookie_kwargs: May be set to a dictionary of additional arguments to be passed toRequestHandler.set_cookie for the XSRF cookie.
  • twitter_consumer_keytwitter_consumer_secretfriendfeed_consumer_key,friendfeed_consumer_secretgoogle_consumer_keygoogle_consumer_secretfacebook_api_key,facebook_secret: Used in the tornado.auth module to authenticate to various APIs.

模版設定:

  • autoescape: 制對模板的自動轉義. 可以被設定為 None 以禁止轉義, 或設定為一個所有輸出都該傳遞過數 name . 預設是 "xhtml_escape". 可以在每個模板中改變使用 {% autoescape %} 指令.
  • compiled_template_cache:  預設 True; 如果 False 每次請求將重新載入模版
  • template_path: 模版檔案目錄. 可以被 RequestHandler.get_template_path擷取進行重寫
  • template_loader: 分配一個 tornado.template.BaseLoader進行模版載入.如果設定了template_path和 autoescape將失效. 可以被 RequestHandler.create_template_loader進一步重寫.
  • template_whitespace: 對於模板中的空白處理; 詳細用法請看tornado.template.filter_whitespace

靜態檔案設定:

  • static_hash_cache: 預設 True; 如果 False 靜態 urls 將重新載入靜態檔案
  • static_path: 靜態檔案的目錄
  • static_url_prefix: 靜態檔案的Url首碼, 預設為 "/static/".
  • static_handler_classstatic_handler_args: 可以自訂處理靜態檔案的動作和參數,而不是預設的 tornado.web.StaticFileHandlerstatic_handler_args, 如果設定了,應該有一個字典被傳入到動作類的 initialize 方法中
listen( portaddress=‘‘**kwargs)[source]

Starts an HTTP server for this application on the given port.

This is a convenience alias for creating an HTTPServer object and calling its listen method. Keyword arguments not supported by HTTPServer.listen are passed to the HTTPServerconstructor. For advanced uses (e.g. multi-process mode), do not use this method; create anHTTPServer and call its TCPServer.bind/TCPServer.start methods directly.

Note that after calling this method you still need to call IOLoop.current().start() to start the server.

Returns the HTTPServer object.

Changed in version 4.3: Now returns the HTTPServer object.

add_handlers( host_patternhost_handlers)[source]

Appends the given handlers to our handler list.

Host patterns are processed sequentially in the order they were added. All matching patterns will be considered.

reverse_url( name*args)[source]

Returns a URL path for handler named name

The handler must be added to the application as a named URLSpec.

Args will be substituted for capturing groups in the URLSpec regex. They will be converted to strings if necessary, encoded as utf8, and url-escaped.

log_request( handler)[source]

Writes a completed HTTP request to the logs.

By default writes to the python root logger. To change this behavior either subclass Application and override this method, or pass a function in the application settings dictionary as log_function.

tornado.web.Application類配置及使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.