


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

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
