Use Python's tornado framework to implement a web-side book Presentation page

Source: Internet
Author: User
First, why Choose Tornado:
1. High-performance network library, which can be done with gevent,twisted,libevent and so on.
Provides asynchronous IO support, time-out event handling, based on tcpserver,httpclient, especially Curlhttpclient,
Definitely ranked first in the existing HTTP client. Can be used to do crawler, game server, as far as I know the industry has used tornado as a game server





2.web frame, which can and django,flask pair.
Provides web framework prerequisites such as routing, templates, and so on. And the other difference is that Tornado is asynchronous, natural fit for long rotation,
This is also FriendFeed invented tornado reason, the current flask can also support, but must rely on gevent, etc.



3. A more complete HTTP server, this can be compared with Nginx,apache,
But only support http1.0, so using Nginx to do the first paragraph is not only to better utilize multicore, but also to support http1.1



4. Complete WSGI server, which can be compared with gunicore,gevent WSGI server,
That means you can let the flask run above Tornado and let tornado accelerate flask



5. Provide complete websocket support, which makes HTML5 's games and so on convenient.
Like the long rotation is the use of WebSocket, but WebSocket mobile phone support is not very good,
Some time ago had to use timed Ajax to send a large number of requests, expect the mobile browser quickly catching up



Use Tornado to create a simple book introduction page
Well, let's take a look at the code implementation of this book introduction page:
1. Create a portal file for a Web service blockmain.py


#
#coding:utf-8
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
import os.path
import json
import urllib2

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class MainHandler(tornado.web.RequestHandler):
  def get(self):
    self.render(
      "index.html",
      page_title = "Burt's Books ¦ Home",
      header_text = "Welcome to Burt's Books!",
      books = ['细说php','python','PHP','小时代']
    )


class HelloModule(tornado.web.UIModule):
  def render(self):
    return'
I am yyx and this is an information from module hello!
'

class BookModule(tornado.web.UIModule):
  def render(self,bookname):
    doubanapi = r'https://api.douban.com/v2/book/'
    searchapi = r'https://api.douban.com/v2/book/search?q='
    searchurl = searchapi+bookname
    searchresult = urllib2.urlopen(searchurl).read()
    bookid = json.loads(searchresult)['books'][0]['id']
    bookurl = doubanapi+bookid
    injson = urllib2.urlopen(bookurl).read()
    bookinfo = json.loads(injson)
    return self.render_string('modules/book.html',book = bookinfo)

  def embedded_javascript(self):
    return "document.write(\"hi!\")"

  def embedded_css(self):
    return '''.book {background-color:#F5F5F5}
         .book_body{color:red}
    '''

  def html_body(self):
    return ''

if __name__ == "__main__":
  tornado.options.parse_command_line()
  app = tornado.web.Application(
    handlers = [
      (r'/',MainHandler),

    ],
    template_path = os.path.join(os.path.dirname(__file__),'templates'),
    static_path = os.path.join(os.path.dirname(__file__),'static'),
    debug = True,
    ui_modules={'Hello':HelloModule,'Book':BookModule}


    )
  http_server = tornado.httpserver.HTTPServer(app)
  http_server.listen(options.port)
  tornado.ioloop.IOLoop.instance().start()





Explain some of the basic MVC concepts:
Tornado also uses the PathInfo pattern to match the user's input to get the parameters, and then calls the corresponding handler function, which is handled by setting the corresponding class class for the various matching patterns, such as I am here to handle from the class MainHandler The GET Request
MainHandler renders the request render to index.html, and the parameter is called by {{parameter}} in index.html.



2. Set up the corresponding template, first create a base of the parent class main.html template, create the Templates directory, under it to create main.html, this template just defines the most basic Web page framework, the content of which is inherited from its subclasses to implement the concrete


  {{Page_title}}{% Block header%}

Burt ' s Books

{% END%}{% block body%} {% END%}{% Set MailLink = ' contact Us '%} {% set script = '%} {% block footer%}

For more information on our selection, hours or events, please email us at{% raw MailLink%}

{% END%}





Here is the definition of a main frame, where the {% block header%}



Burt ' s Books


{% End} is the inherited block for the subclass template, and when the subclass inherits the Main.html, what is written in this block is implemented by subclasses, and the default value of the parent class is used if it is not implemented.


Burt ' s Books


, the MainHandler class is render to a index.html, then write a index.html to inherit the parent class.




{% extends "main.html"%} {% Block header%}

{{Header_text}}

{% END%} {% block body%}

Welcome to Burt ' s books!

{% Module Hello ()%} {% for book in books%} {% module book%} {% END%}

...

{% END%}





Simple and concise, this is also the use of inheritance benefits, do not have to repeat the contents of the parent class, as long as the implementation of the parent block content can be
Parameters in the Render method in the MainHandler class


Page_title = "Burt's Books | Home",
Header_text = "Welcome to Burt's Books!" .
Books = [' detailed PHP',' python','PHP',' tiny times ']





will be passed through the parameters here.
Tornado template can use Python code, plus {%} when using the if for and so on to use {% END%} end
The {% module book%} in the code will invoke the definition in the Portal service file and the module corresponding to ' book '
ui_modules={' Hello ': Hellomodule, ' book ': Bookmodule} that is Bookmodule, view the bookmodule definition above


class BookModule(tornado.web.UIModule):
  def render(self,bookname):
    doubanapi = r'https://api.douban.com/v2/book/'
    searchapi = r'https://api.douban.com/v2/book/search?q='
    searchurl = searchapi+bookname
    searchresult = urllib2.urlopen(searchurl).read()
    bookid = json.loads(searchresult)['books'][0]['id']
    bookurl = doubanapi+bookid
    injson = urllib2.urlopen(bookurl).read()
    bookinfo = json.loads(injson)
    return self.render_string('modules/book.html',book = bookinfo)





Bookmodule inherited from the use of the Tornado.web.uimodule,ui module is the last Render_string () method to render an object into a template, I have a simple use of the Watercress Book API, First, search to find the information containing the key words of the book, return the first book ID, and then use the book API to query the specific information, the specific book to render the information to the corresponding template
Create the Modules directory under the Templates directory, then create a book.html, here is the specific book to display the content frame


  

{{book["title"]}}

Click to view Details

{% if book["subtitle"]! = ""%}

{{book["subtitle"]}}

{% END%} Released: {{book["pubdate"]}}

Description:

{% raw book["summary"]%}





The final file directory structure should be like this


├── blockmain.py
└── templates
  ├── index.html
  ├── main.html
  └── modules
    └── book.html


The execution of the program is this:
Use the MainHandler class to access index.html---->index.html inherit from the main.html---->index.html {% module book%} In turn, find the book corresponding to the blockmain.py in the ui_modules---->ui_modules the contents of the book object in the query will be Dye to the modules under the book.html, so that the full content of the present, did not do the front-end ... Start the service via Python blockmain.py and access the following Web page via http://localhost:8000





  • Related Article

    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.