


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 id="I-am-yyx-and-this-is-an-information-from-module-hello">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 id="Burt-s-Books">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 %}
Burt's Books
{% 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, hereBurt's Books
, 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 id="header-text">{{ 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 id="book-title">{{ book["title"] }}</h3> <a href="{{book['alt']}}" target="_blank"><p>点击查看详情</p></a> {% if book["subtitle"] != "" %} <h4 id="book-subtitle">{{ book["subtitle"] }}</h4> {% end %} <img class="book_image lazy" src="/static/imghwm/default1.png" data-src="http://files.jb51.net/file_images/article/201607/2016711175031811.png?2016611175040?x-oss-process=image/resize,p_40" images"]["large"] }}"/ alt="Using Python's Tornado framework to implement a Web-side book display page" > <div> <div>Released: {{ book["pubdate"]}}</div> <h5 id="Description">Description:</h5> <div>{% 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

Implementing factory pattern in Python can create different types of objects by creating a unified interface. The specific steps are as follows: 1. Define a basic class and multiple inheritance classes, such as Vehicle, Car, Plane and Train. 2. Create a factory class VehicleFactory and use the create_vehicle method to return the corresponding object instance according to the type parameter. 3. Instantiate the object through the factory class, such as my_car=factory.create_vehicle("car","Tesla"). This pattern improves the scalability and maintainability of the code, but it needs to be paid attention to its complexity

In Python, the r or R prefix is used to define the original string, ignoring all escaped characters, and letting the string be interpreted literally. 1) Applicable to deal with regular expressions and file paths to avoid misunderstandings of escape characters. 2) Not applicable to cases where escaped characters need to be preserved, such as line breaks. Careful checking is required when using it to prevent unexpected output.

In Python, the __del__ method is an object's destructor, used to clean up resources. 1) Uncertain execution time: Relying on the garbage collection mechanism. 2) Circular reference: It may cause the call to be unable to be promptly and handled using the weakref module. 3) Exception handling: Exception thrown in __del__ may be ignored and captured using the try-except block. 4) Best practices for resource management: It is recommended to use with statements and context managers to manage resources.

The pop() function is used in Python to remove elements from a list and return a specified position. 1) When the index is not specified, pop() removes and returns the last element of the list by default. 2) When specifying an index, pop() removes and returns the element at the index position. 3) Pay attention to index errors, performance issues, alternative methods and list variability when using it.

Python mainly uses two major libraries Pillow and OpenCV for image processing. Pillow is suitable for simple image processing, such as adding watermarks, and the code is simple and easy to use; OpenCV is suitable for complex image processing and computer vision, such as edge detection, with superior performance but attention to memory management is required.

Implementing PCA in Python can be done by writing code manually or using the scikit-learn library. Manually implementing PCA includes the following steps: 1) centralize the data, 2) calculate the covariance matrix, 3) calculate the eigenvalues and eigenvectors, 4) sort and select principal components, and 5) project the data to the new space. Manual implementation helps to understand the algorithm in depth, but scikit-learn provides more convenient features.

Calculating logarithms in Python is a very simple but interesting thing. Let's start with the most basic question: How to calculate logarithm in Python? Basic method of calculating logarithm in Python The math module of Python provides functions for calculating logarithm. Let's take a simple example: importmath# calculates the natural logarithm (base is e) x=10natural_log=math.log(x)print(f"natural log({x})={natural_log}")# calculates the logarithm with base 10 log_base_10=math.log10(x)pri

To implement linear regression in Python, we can start from multiple perspectives. This is not just a simple function call, but involves a comprehensive application of statistics, mathematical optimization and machine learning. Let's dive into this process in depth. The most common way to implement linear regression in Python is to use the scikit-learn library, which provides easy and efficient tools. However, if we want to have a deeper understanding of the principles and implementation details of linear regression, we can also write our own linear regression algorithm from scratch. The linear regression implementation of scikit-learn uses scikit-learn to encapsulate the implementation of linear regression, allowing us to easily model and predict. Here is a use sc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
