5 Building Tornado website app

Source: Internet
Author: User
Tags error status code stack trace

A tornado Web site application typically consists of one or more Requesthanlde subclasses, a application responsible for routing requests to handlers, and a main () function that initiates the server.

One of the smallest "Hello World" Examples:

 fromTornado.ioloopImportIoloop fromTornado.webImportrequesthandler, application, urlclassHellohandler (requesthandler):defGet (self): Self.write ("Hello, World")defMake_app ():returnapplication ([url (r"/", Hellohandler),])defMain (): App=Make_app () App.listen (8888) ioloop.current (). Start ()
Application Object

Application This object is responsible for the global configuration, including mapping requests to the handlers routing table.

A routing Table Urlspec object collection (or tuple) that contains a regular expression and a handler class. If the regular expression contains capturing groups, these groups will be path parameters (path arguments), and the values of these captured groups will be passed in the parameters of the Hanlder HTTP method. If the Dictionary object is passed as the third argument, the value of the parameter is passed to the Initialize parameter of the RequestHandler. Finally, Urlspec can have a name that can be obtained by Request.reverse_url.

Example:

#-*-coding:utf-8-*- fromTornado.ioloopImportIoloop fromTornado.webImportapplication, URL, RequestHandler__author__='Administrator'classMainhanlder (requesthandler):defGet (self): Self.write ('<a href= "%s" >link to Story 1</a>'%Self.reverse_url (" Story","1"))classStoryhanlder (requesthandler):defInitialize (self, db): Self.db=DBdefget (Self, story_id): Self.write ("This was story %s"%story_id) DB= 1app=application ([url (r"/", mainhanlder), url (r"/story/([0-9]+)", Storyhanlder, Dict (db=db), name=" Story")])defMain (): App.listen (8888) ioloop.current (). Start ()if __name__=="__main__": Main ()

The root path is mapped to Mainhanlder. and the "/story/number" format request is mapped to Storyhandler. This number is treated as a Get method that the string is passed to the Storyhanlder.

Enter http://localhost:8888/in the Tour viewer

After clicking "Link to Story 1",

The application constructor has a number of keyword parameters that are used to customize the behavior of the application. Please refer to Application.settings for a complete set of parameter lists.

Requesthanlder sub-class

Tornado Web applications Most of the work is done by RequestHandler subclasses. This is primarily handled by methods such as Get (), post (), and so on. Each handler defines one or more of these methods to handle different HTTP requests. As mentioned above, the values of these method parameters are passed in according to the value after the routing regular expression matches.

In Hanlder, methods such as Requesthanlder.render or requesthanlder.write are called to produce a response. The render () method loads a template by name and renders the template. The write () method instead takes parameters such as strings, bytes, and dictionaries (the dictionary must be encoded in JSON format) for output to non-templates.

In the RequestHandler class, a number of methods that can be overloaded with a quilt are defined. So when developing your own applications, you typically define a Basehanlder class that overrides methods such as Write_error and Get_current_user, and then subclasses inherit Basehanlder rather than Requesehanlder.

Processing Request Input

The requested Hanlder can access the object representing the current request by invoking the Self.request property. Please see the detailed property definitions for the Httpserverrequest class.

Example

classMyformhandler (requesthandler):defGet (self): Self.write (''                   '<input type= "text" name= "message" >'                   '<input type= "Submit" value= "Submit" >'                   '</form></body>')    defpost (self): Self.set_header ("Content-type","Text/plain") Self.write ("You wrote"+ Self.get_body_argument ("message"))

Request data in HTML form format is parsed and can be obtained by calling methods, such as the Get_query_argument and Get_body_argument methods.

You can call the Get_query_arguments and Get_body_argumens methods if the fields in the form have multiple values.

The uploaded file of the form can be obtained by self.request.files. Each object is a dictionary in the format {"filename": ..., "content_type": ..., "Body": ...}. The Files property value exists only if the file is uploaded by means of form wrapper (for example, Content-type type is multipart/form). If the form wrapper format is used, the uploaded data can be obtained through the Self.request.body property. By default, uploaded files are cached in memory. If you are working with a file that is too large to be stored well in memory, look at the Stream_request_body class adorner.

Because of the quirks of HTML form encoding, Tornado does not combine different types of input parameters. In certain cases, we will not parse the JSON request body. Application if you prefer to use JSON instead of form encoding (form-encoding), you can rewrite the prepare method to parse the request. As follows:

def Prepare (self):     if self.request.headers["content-type"].startswith ("  Application/json"):        = json.loads (self.request.body)    Else  :        = None

rewrite Requesthanlder Method

In addition to methods such as Get ()/post (), other methods can be overridden in the quilt class when necessary. In each request, the following sequence of calls is executed:

1. A new RequestHandler object is created

2. Initialize () is called, and the value of the parameter is obtained from the configuration of the Application object. Initialize typically only store these parameters in the member variable, without producing any output or calling methods such as Send_error.

3. Prepare () is called. This implementation is best shared in the underlying class for other subclasses to inherit, because the prepare method is called regardless of any HTTP method being used, prepare can produce output, and if the finish (or redirect, etc.) method is called, the request processing ends.

4. Get (), post (), put () any of the one by one methods are called, if the URL regular expression contains a capturing group, the values of these captured groups are passed to the parameters of these methods;

5. When the request processing is finished, the On_finish () method is called. For synchronous handler, the On_finish method is called immediately after the Get () (for example) method returns.

Typically, the most overridden methods are:

    • L Write_error. HTML for the user to output the error page;
    • L On_connection_close When a user client disconnects is called. The application can choose to listen to disconnect and then go to stop some process. 、
    • L Get_current_user. Gets the current user.
    • L Get_user_locale. Returns the locale object for the current user
    • L set_default_headers. Add additional headers to the response. (such as a custom Service header)

Error Handling

If an exception occurs in Hanlder, Tornado will call Request.write_error to generate the error page. Tornado.web.HTTPError can be used to generate a specific error status code, and all other exceptions return 500 of the status code.

In debug mode, the default error page includes a stack trace, which in other cases returns a description of a single line of error (for example, "500:internal Server error"). In order to produce a custom error page, override the Request.write_error method (which may be placed in a base class for other handlers to inherit). When an error is caused by an exception, Exc_info is passed as a keyword parameter (note that this exception is not guaranteed to be the current exception in Sys.exc_info, so write_error must use such as Traceback.format_exception instead of Traceback.format_exc).

Another way to produce an error page is to call the Set_status method instead of Write_error, then write the response and return it. A special Tornado.web.Finish exception is triggered to terminate Hanlder without calling Write_error.

For 404 errors, use the Default_handler_class in application setting to process. This handler must override the Prepare method. According to the above description, this will result in an error page, either triggering the Httperror (404) Error and overriding the Write_error, or calling Self.set_status (404) and then generating a response directly in prepare.

redirect

Tornado There are two main ways to redirect requests, one is to call the Requesthanlder.redirect method, and the other is to use the Redirecthandler class directly.

Use the Self.redirect method in the implemented Hanlder to redirect to anywhere. This method also has a parameter, permanent, to indicate whether the redirect is permanent. The default value of this parameter is false, which results in a response of the 302 found status number, and is particularly suitable for redirects such as post () request processing succeeds. If permanent this parameter value is true, 301 Moved permanetly State encoding is returned to the user.

Redirecthandler, which allows the user to configure the redirect link in the Application routing table. For example, a single static redirect is configured.

App = tornado.web.Application ([    URL (r"/app", Tornado.web.RedirectHandler,        dict (url="http://itunes.apple.com/my-app-id" )),    ])

Redirecthanlder also supports the case of regular expressions. The following rule definition enables a request that begins with/pictures/to be redirected to a request prefixed with/photos/.

App = tornado.web.Application ([    URL (r"/photos/(. *)", Myphotohandler),    URL (r"/pictures/(. *)", Tornado.web.RedirectHandler,        dict (url =r"/photos/\1")),    ])

Unlike the Requesthanlder.redirect method, Redirecthandler defaults to permanent redirection, that is, the permanent property is true. This is a route table that should not be changed at run time, while the redirect address used in Hanlder can be logically changed. If you want to send a temporary redirect with Redirecthandler, set the permanent to false in the Redirecthandler initialization parameter.

Asynchronous handler

By default, Hanlders is synchronized. When the Get ()/post () method returns, the request is considered ended and then the response is sent. When handler is running, other requests will be blocked. Any long-running hanlder must be set to asynchronous so that the operation does not block.

The simplest way to make a hanlder asynchronous is to use the coroutine adorner. Use the yield keyword to perform non-blocking I/O operations until Coroutine has returned to return the response to the client.

In some cases, coroutines is not a convenient way to use callbacks, which is a callback method using the Tornado.web.asynchrounous adorner. When this adorner is used, the response is not sent automatically, and the request remains open until the callback function calls the Requesthandler.finish method. The application must ensure that this method is called, otherwise the user's browser will simply pause.

The following is an example of using the built-in asynchttpclient to invoke the FriendFeed Api.

classMainHandler (Tornado.web.RequestHandler): @tornado. web.asynchronousdefGet (self): HTTP=tornado.httpclient.AsyncHTTPClient () Http.fetch ("Http://friendfeed-api.com/v2/feed/bret", Callback=self.on_response)defOn_response (Self, Response):ifResponse.error:RaiseTornado.web.HTTPError (500) JSON=Tornado.escape.json_decode (response.body) self.write ("fetched"+ STR (len (json["Entries"])) +"Entries"                   "From the FriendFeed API") self.finish ()

When the Get () method returns, the request does not end. This request is always open until the last call to the On_response method, and the response is not sent to the client until the Self.finish method is called.

In order to compare, the following method is implemented by Coroutine.

classMainHandler (Tornado.web.RequestHandler): @tornado. Gen.coroutinedefGet (self): HTTP=tornado.httpclient.AsyncHTTPClient () response=yieldHttp.fetch ("Http://friendfeed-api.com/v2/feed/bret") JSON=Tornado.escape.json_decode (response.body) self.write ("fetched"+ STR (len (json["Entries"])) +"Entries"                   "From the FriendFeed API")

5 Building Tornado website app

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.