Home Backend Development Python Tutorial Using Python's Tornado framework to implement a Web-side book display page

Using Python's Tornado framework to implement a Web-side book display page

Aug 04, 2016 am 08:55 AM
python tornado

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&#63;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()

Copy after login

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>

Copy after login

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, here

Burt'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>{{ 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 %}

Copy after login

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','小时代']
Copy after login

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&#63;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)
Copy after login

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>
Copy after login

The final file directory structure should be like this

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

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

2016711175031811.png (913×639)

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles