Tornado Learning Essentials

Source: Internet
Author: User
Tags define function mongodb client mongodb example mongodb server

The simplest application at the top of the program, we imported some tornado modules. Although Tornado has some other useful modules, in this case we must include at least these four modules.
  
12341234 includes a useful module (tornado.options) to read the settings from the command line. We use this module here to specify the port on which our app listens for HTTP requests.
  
1212 Workflow: If a setting with the same name in the Define statement is given on the command line, it becomes a property of the global options.
  
If the user runs the program using the Help option, the program prints out all the options you have defined and the text you specified in the Help parameter of the Define function.
  
If the user does not specify a value for this option, the value of default is used instead. Tornado uses the type parameter for basic parameter type validation, and throws an exception when an inappropriate type is given.
  
Therefore, we allow the port parameter of an integer to access the program as a options.port. If the user does not specify a value, the default is 8000.
  
Several modules include a useful module (tornado.options) to read the settings from the command line. We use this module here to specify the port on which our app listens for HTTP requests. Its workflow is as follows: If a setting with the same name in the Define statement is given on the command line, it becomes a property of the global options. If the user runs the program using the Help option, the program prints out all the options you have defined and the text you specified in the Help parameter of the Define function. If the user does not specify a value for this option, the value of default is used instead.
  
The RequestHandler class has a number of useful built-in methods, including Get_argument, where we get the value of the parameter greeting from a query string. (if this parameter does not appear in the query string, the second parameter of Get_argument is used as the default value.) )
  
Another useful method is write, which takes a string as a parameter to the function and writes it to the HTTP response. Here, we use the value provided by the greeting parameter in the request to insert into the greeting and write back to the response.
  
Start 12341234 This is the statement that really makes the tornado run. First, we use the Tornado options module to parse the command line. We then created an instance of the Tornado application class. The most important parameter passed to the application class Init method is handlers. It tells the Tornado which class should be used in response to the request.
  
123123 the code that starts here will be reused: Once the Application object is created, we can pass it to the Httpserver object of Tornado and then listen (out of the options object) using the port we specified on the command line. Finally, after the program is ready to receive the HTTP request, we create an instance of the Tornado Ioloop.
  
Base get information from an incoming HTTP request (using Get_argument and parameters passed in to get and post) and write HTTP response (using the Write method)
  
The extension supports any legitimate HTTP requests (GET, POST, PUT, DELETE, HEAD, OPTIONS). You can easily define the behavior of any of these methods by simply using a method of the same name in the RequestHandler class.
  
Status code in some cases, Tornado automatically sets the status code:: The requested path cannot match any of the RequestHandler classes: a get_argument function with no default value is called. And there is no parameter for the given name: the incoming request uses an HTTP method that is not defined in RequestHandler: When the program encounters any error that cannot be exited: If the response succeeds and no other return code is set when any of these errors occur, Tornado will send a short snippet with the status code and error message to the client by default. If you want to use your own method instead of the default error response, you can override the Write_error method in your RequestHandler class.
  
The database is a simple wrapper for the MongoDB Client API Pyth www.yyzx66.cn/on Library to create the connection first, you need to import the Pymongo library and create a connection to the MongoDB database.
  
1212 The preceding code shows us how to connect a MongoDB server running on the default port (27017) on your local machine. If you are using a remote MONGODB server, replace localhost and 27017 for the appropriate value.
  
The collection object allows you to access any database on the server you are connected to. You can use objects in object properties or as dictionaries to get objects that represent a particular database. If the database does not exist, it is automatically established.
  
A database can have any number of collections. A collection is where some related documents are placed. Most of the operations we do with MongoDB (find documents, save documents, delete documents) are performed on a collection object. You can call the Collection_names method on a database object to get a list of the collections in the database.
  
[]1212 Of course, we haven't added any collections to our database, so this list is empty.]
  
Inserting a document When we insert the first document, MongoDB automatically creates the collection. You can get the object representing the collection on the database object by accessing the property of the collection name, and then call the Insert method of the object to specify a python dictionary to insert the document. For example, in the following code, we inserted a document in the collection widgets. Because the Widgets collection does not exist, MongoDB is created automatically when the document is added.
  
The 1234512345 (System.indexes collection is used internally by MongoDB. For the purposes of this chapter, you can ignore it. )
  
In the code shown earlier, you can either use the properties of the database object to access the collection, or you can think of the database object as a dictionary and access the collection name as a key. For example, if DB is a Pymongo database object, then db.widgets and db[' Widge www.yinbaovip.cn/ts '] can also access this collection.
  
The processing document is a "modeless" Database: Documents in the same collection typically have the same structure, but do not enforce the use of the same structure. Internally, the document is stored in a JSON-like binary form called Bson. Pymongo allows us to write and remove documents in the form of a Python dictionary.
  
Search documents since the document is in the database, we can use the Find_one method of the collection object to remove the document. You can tell Find_one to find a specific document by passing a key for the document name and a dictionary of the expression that you want to match. For example, we want to return the document Name field name value equals Flibnip document (that is, the document we just created), you can call the Find_oen method as follows: 12341234 note the _id domain. When you create any document, MongoDB automatically adds the field. Its value is a Objectid, a Bson object that guarantees that the document is unique.
  
The value returned by the processing method of the return value is a simple python dictionary. You can access individual items from it, iterate over its key-value pairs, or modify values as you would with other Python dictionaries.
  
123456123456 However, changes to the dictionary are not automatically saved to the database. If you want to save the dictionary changes, you need to call the collection's Save method, and pass the modified dictionary as a parameter: 123456123456 Let's add more documents to the collection: 1234512345 we can get a list of all the documents in the collection by invoking the Find method of the collection, and then iterate over their results: 1212 Finally, We can use the Remove method of the collection to remove a document from the collection. The Remove method, like Find, Find_one, can also use a dictionary parameter to specify which document needs to be deleted. For example, to remove all documents with the name key value of Flipnip, enter: 11 The JSON module for the document and JSON does not know how to convert the Objectid type of MongoDB to JSON.
  
The simplest way (and the method we use in this chapter) is to simply remove the _id key from the dictionary before we serialize it.
  
The 123,412,341 more complex approach is to use Pymongo's Json_util library, which also helps you serialize other MongoDB specific data types to JSON.
  
A simple persistent web service now we know that writing a Web service can access the data in the MongoDB database. First, we're going to write a Web service that reads data from MongoDB only. Then, we write a service that can read and write data.
  
Code 1-1 read-only dictionary 12345678910111213141516171819202122232425262728293031www.lxinyul.cc 3233123456789101112131415161718192021222324252627282930313233 run the program in the command line as follows: Now use curl or your browser to send a request to the app.
  
1212 If we request a word that is not added to a database, we get a 404 error and an error message: www.hsl85.cn 1212 explanation We instantiate a Pymongo connection object in the Init method of our Tornadoapplication object. We created a DB attribute in the Application object that points to the MongoDB example database.
  
Once we have added the DB attribute to the Application object, we can use self.application.db to access it in any RequestHandler object. In fact, this is exactly what we did in the Get method in Wordhandler in order to take out the Pymongo words collection object, and after we assign the collection object to the variable coll, we use the word that the user requested in the HTTP path to call the Find_one method. If we find this word, remove the _id key from the dictionary (so that Python's JSON library can serialize it) and pass it to the RequestHandler's write method. The Write method will automatically serialize the dictionary to JSON format.
  
The Code 1-2 writable dictionary mainly adds the post () method: 123456789101112123456789101112 Principle explanation The first thing we do is to use the Get_argument method to get the definition parameters passed in the POST request.
  
Just like in the Get method, we try to use the Find_one method to load the document of a given word from the database.
  
If a document of this word is found, we set the value of the definition entry to the value obtained from the post parameter, and then call the Save method of the collection object to write the change to the database. If no document is found, a new document is created and saved to the database using the Insert method.
  
In either case, after the database operation is executed, we write the document in the response (note that the _id attribute is deleted first)
  
Asynchronous Web requests give us a better way to handle this situation: when the application waits for the first processing to complete, it lets the I/O loop open to serve other clients until a request is started and feedback is received while processing is complete, instead of suspending the process while waiting for the request to complete.
  
A simple Web application that sends HTTP requests to the Twitter API first synchronizes the core code of the version: 12341234 related explanations Here we instantiate a Tornado HttpClient class, and then invoke the fetch method of the result object. The synchronous version of the Fetch method uses the URL you want to get as a parameter.
  
Here, we build a URL to crawl the search results for the Twitter Search API (the RPP parameter specifies that we want to get 100 tweets for the first page of the search results, and the Result_type parameter specifies that we want only the most recent tweets for matching searches).
  
The HttpResponse method returns an object whose Body property contains any data that we get from the remote URL. Twiwww.yghrcp88.cn Tter will return a JSON-formatted result, so we can use Python's JSON module to create a python data structure from the results.
  
Note: The HttpResponse object returned by the Fetch method allows you to access any part of the HTTP response, not just the body.
  
The rest of the processing function is concerned with calculating the number of tweets per second. We use the difference between the oldest tweet in the search results and the latest tweet timestamp to determine when the search was overwritten, and then use this number to divide the number of tweets obtained by the search to get our final result. Finally, we wrote a simple HTML page with this result to the browser.
  
Blocking although the application itself responds fairly quickly, there is considerable lag between sending a request to Twitter and getting the returned search data. In sync (so far, we assume a single-threaded) app, which means that only one request can be provided at the same time. So, if your app involves a 2-second API request, you'll be able to provide it every second (max!). ) a request.
  
The underlying asynchronous call contains a Asynchttpclient class that can execute an asynchronous HTTP request.
  
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647123456789101112131415161718192021222 The 3242526272829303132333435363738394041424344454647 fetch method does not return the result of the call. Instead, it specifies a callback parameter, and the method or function that you specify will be called when the HTTP request completes, using HttpResponse as its argument.
  
12341234 In this example, we specify the On_response method as the callback function. Before we used the desired output to convert the Twitter Search API request to the Web page all the logic was moved into the On_response function. It is also important to note the use of the @tornado.web.asynchronous adorner (before the definition of the Get method) and the Self.finish () called at the end of the callback method.
  
The async adorner asynchronous and finish methods default to close the client's connection when function processing returns. In general, this is exactly what you want. But when we are dealing with an asynchronous request that requires a callback function, we need the connection to remain open until the callback function is finished. You can use the @tornado.web.asynchronous adorner on the method you want to change its behavior to tell the hold connection to open, as we did in the Get method Indexhandler in the asynchronous version of the push rate example. Here's the code snippet: 123456123456 Remember that when you use the @tornado.web.asynchonous adorner, Tornado never closes the connection yourself. You must call the Finish method in your RequestHandler object to explicitly tell tornado to close the connection. (Otherwise, the request may hang, and the browser may not show the data that we have sent to the client.) In the previous async example, we called the finish method after write of the On_response function: 1234567812345678 Async Generator Unfortunately, the previous is a bit of a hassle: in order to process the request, We had to split our code into two different ways. When we have two or more asynchronous requests to execute, coding and maintenance are very difficult, and each relies on the preceding call: soon you will find yourself invoking the callback function of a callback function.
  
The version introduces the Tornado.gen module, which provides a cleaner way to perform asynchronous requests.
  
The following is the relevant Code section: 1234512345 The main difference is how we invoke the Fetch method of the asynchronous object.
  
We use the yield keyword of Python and an instance of the Tornado.gen.Task object to pass the call we want and the arguments passed to the calling function to that function.
  
Here, the use of yield returns the control of the program to the tornado, allowing other tasks to be performed in the HTTP request.
  
When the HTTP request is complete, the RequestHandler method resumes where it stopped. The beauty of this build is that it returns the HTTP response in the request handler, not the callback function. As a result, the code is easier to understand: All request-related logic is in the same location. The HTTP request is still executed asynchronously, so we use Tornado.gen to achieve the same performance as the asynchronous request version using the callback function.
  
Note: Remember that the use of the @tornado.gen.engine adorner needs to be just before the definition of the Get method; This will remind tornado that this method will use the Tornado.gen.Task class.
  
The main attraction of long polling HTTP long polling with Tornado is that it greatly reduces the load on the Web server. The server side handles connections only when it receives an initial request and sends a response again, relative to the client making a large number of short and frequent requests (and the overhead incurred each time the HTTP header is processed). Most of the time there is no new data, and the connection does not consume any processor resources.
  
Browser compatibility is another great benefit. Any browser that supports AJAX requests can perform push requests. No browser plugins or other add-ons are required. In contrast to other server-side push Technologies, HTTP long polling has become one of the few feasible scenarios that are widely used.
  
Example: Live inventory report This app provides an HTML book detail page with an "ADD to Cart" button and a count of the remaining inventory for the book. After a shopper adds a book to the cart, other visitors to the site can immediately see a reduction in inventory.
  
To provide an inventory update, we need to write a RequestHandler subclass that does not immediately close the HTTP connection after the initialization of the processing method call. We use the tornado built-in asynchronous decorator to do the work, as shown in the Code:]} 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 6667686970717273747576777879808182838485868788899091929394951234567891011121314151617181920212223242526272829303132333435 363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 and A Websockethandler class is provided in the WebSocket module. This class provides hooks for websocket events and methods that communicate with connected clients. When a new WebSocket connection is opened, the open method is called, while the On_message and On_close methods are called when the connection receives a new message and the client shuts down.
  
In addition, the Websockethandler class provides a Write_message method for sending messages to clients, and the Close method is used to close the connection.
  
12345671234567 as you can see in our Echohandler implementation, the Open method simply sends the string "connected!" to the client using the Write_message method provided by the Websockethandler base class. Each time the handler receives a new message from the client, the On_message method is called, and our implementation returns the client-provided message to the client as is.
  
It is also important to note that the Tornado.websocket module is required in order to obtain the functionality of the Websockethandler.
  
Example: Using WebSockets real-time inventory in the ShoppingCart class, we only need to make a slight change in the way the callback function is notified. Since WebSockets remains open after a message is sent, we do not need to remove the internal callback function list after they are notified. We only need to iterate the list and invoke the callback function with the current inventory: 123123 Another change is the addition of the unregisted method. Statushandler will call this method to remove a callback function when the WebSocket connection is closed.
  
123123 Most of the changes are in the Statushandler class that inherits from Tornado.websocket.WebSocketHandler. The WebSocket handler implements the open and On_message methods, which are called when the connection opens and receives the message, rather than implementing the handler for each HTTP method. Additionally, the On_close method is called when the connection is closed by the remote host.
  
Pass

Tornado Learning Essentials

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.