Home >Backend Development >Python Tutorial >Using Python's Tornado framework to implement a Web-side book display page
First of all, why choose Tornado:
1. High-performance network library, which can be paired with gevent, twisted, libevent, etc.
Provides asynchronous io support, timeout event processing, and on this basis provides tcpserver, httpclient, especially curlhttpclient,
It definitely ranks first among existing http clients. It can be used for crawlers and game servers. As far as I know, the industry has used tornado as a game server
2. Web framework, which can be compared with django and flask.
Provides essential components of web frameworks such as routing and templates. The difference from others is that tornado is asynchronous and naturally suitable for long-round training,
This is also the reason why friendfeed invented tornado. Currently, flask can also support it, but it must use gevent, etc.
3. A relatively complete http server, which can be compared with nginx and apache,
But it only supports http1.0, so using nginx for the frontend is not only to make better use of multi-core, but also to support http1.1
4. Complete wsgi server, this can be compared with gunicore, gevent wsgi server,
In other words, flask can be run on tornado, and tornado can speed up flask
5. Provides complete websocket support, which facilitates HTML5 games, etc.
For example, Zhihu long rotation training uses websocket, but websocket mobile phone support is not very good,
Some time ago, I had to use scheduled ajax to send a large number of requests. I hope mobile browsers will catch up soon
Use tornado to create a simple book introduction page
Okay, let’s get down to business, let’s take a look at the code implementation of this book introduction page:
1. Create a web service entry file 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'<h1>I am yyx and this is an information from module hello!</h1>' 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 '<script>document.write("Hello!")</script>' 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 basic MVC concepts:
Tornado also uses the pathinfo mode to match the user's input to obtain parameters, and then calls the corresponding processing function. It is processed by setting corresponding class classes for various matching modes. For example, I use class MainHandler to process the data from / get request
MainHandler renders the request to index.html, and the parameters are called through {{parameters}} in index.html
2. Create the corresponding template. First create a basic parent class main.html template, create the templates directory, and create main.html under it. This template only defines the most basic web page framework, and the specific content inside is inherited from Its subclasses to implement specifically
<html> <head> <title>{{ page_title }}</title> <link rel="stylesheet" href="{{ static_url("css/style.css") }}" /> </head> <body> <div id="container"> <header> {% block header %}<h1>Burt's Books</h1>{% end %} </header> <div id="main"> <div id="content"> {% block body %}{% end %} </div> </div> <footer> {% set mailLink = '<a href="mailto:contact@burtsbooks.com">Contact Us</a>' %} {% set script = '<script>alert("hello")</script>' %} {% block footer %} <p> For more information about our selection, hours or events, please email us at{% raw mailLink %} <!-- {% raw script %} 这里将原样输出,也就是会弹一个框--> </p> {% end %} </footer> </div> <script src="{{ static_url("js/script.js") }}"></script> </body> </html>
Here is a main framework defined, in which {% block header %}4a249f0d628e2318394fd9b75b4636b1Burt's Books473f0a7621bec819994bb5020d29372a{% end %} is a block for inheritance of subclass templates. When subclasses inherit This main.html, the specific content written in this block is implemented by the subclass. If it is not implemented, the default value of the parent class will be used. For example, here 4a249f0d628e2318394fd9b75b4636b1Burt's Books473f0a7621bec819994bb5020d29372a, the MainHandler class is rendered to a index.html, then write an index.html to inherit this parent class
{% extends "main.html" %} {% block header %} <h1>{{ header_text }}</h1> {% end %} {% block body %} <div id="hello"> <p>Welcome to Burt's Books!</p> {% module Hello() %} {% for book in books %} {% module Book(book) %} {% end %} <p>...</p> </div> {% end %}
Simple and concise, this is also the benefit of using inheritance. You don’t need to repeat the parent class, you only need to implement the block content of the parent class
Parameters in the render method in the MainHandler class
page_title = "Burt's Books | Home", header_text = "Welcome to Burt's Books!", books = ['细说php','python','PHP','小时代']
will be sent here via parameters
You can use python code in the tornado template, and add {% %}. When using if for while, etc., use {% end %} at the end
In the code, {% module Book(book) %} will call the definition in the entry service file and the module corresponding to 'Book'
ui_modules={'Hello':HelloModule,'Book':BookModule} is BookModule, check 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 inherits from tornado.web.UIModule. The use of UI module is the final render_string() method to render an object into a template. I simply used Douban’s book api here and first searched for the key. The book information of Ci, returns the ID of the first book, then uses the book api to query the specific information of the book, and renders the information of this specific book to the corresponding template
Create the modules directory under the templates directory, and then create a book.html. Here is the specific content framework to be displayed in the book
<div class="book"> <h3 class="book_title">{{ book["title"] }}</h3> <a href="{{book['alt']}}" target="_blank"><p>点击查看详情</p></a> {% if book["subtitle"] != "" %} <h4 class="book_subtitle">{{ book["subtitle"] }}</h4> {% end %} <img src="{{ book["images"]["large"] }}" class="book_image"/> <div class="book_details"> <div class="book_date_released">Released: {{ book["pubdate"]}}</div> <h5>Description:</h5> <div class="book_body">{% raw book["summary"] %}</div> </div> </div>
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 like this:
First use the MainHandler class to access index.html through the path '/'---->index.html inherits from main.html---->{% module Book(book) %} in index.html and vice versa. Find the ui_modules corresponding to the Book in blockmain.py---->Render the queried book object content in ui_modules to book.html under modules, so that the complete content is presented without doing the front end... Start the service through python blockmain.py and access the following web page through http://localhost:8000