Today's theme:
The Tornado framework of Python belongs to a Web framework of Python. It is a Web server and Web application framework written by python.
Step 1: what is Tornado
Tornado is a Python based Web services framework and asynchronous network library.
It was first developed by FriendFeed. By using non blocking network I/O, Tornado can carry thousands of active connections and perfectly realize long connections, WebSockets and other programs that need long connections for every user.
Step 2: what are the advantages of Tornado
What are the advantages of Tornado and why should we use it?
• lightweight Web framework
• asynchronous non blocking IO processing mode
• excellent load resistance
• excellent processing performance, independent of multi process / multithreading, solves C10K problem to a certain extent
• WSGI is a full stack alternative product. It is recommended to use its Web framework and HTTP server at the same time
Step 3: how to install Tornado
pip install tornado [Install the latest stable version] pip install tornado==version [[specify version installation]
Step 4: Tornado core content
4.1 Tornado.Web: tornado's basic web framework
• RequestHandler: encapsulates all information and processing methods for request processing
• get/post/..: Encapsulate the corresponding request mode
• write(): a method of encapsulating response information and writing response information
4.2 Tornado.ioloop: core IO loop module, encapsulating Epoll of Linux and kqueue of BSD, and the core of tornado high-performance processing.
• current() returns the IOLoop instance object of the current thread
• start() starts the IO cycle of the IOLoop object and starts listening
4.3 HttpServer listening port
• tornado.httpserver.HTTPServer(app)
• httpserver.listen(port)
4.4 HttpServer realizes multi process operation
• tornado.httpserver.HTTPServer(app)
• httpserver.bind(port)
• httpserver.start(0/None/<0/num)
Step 5: program structure and description
Config.py profile:
import os #parameter param={ 'port':9992, } #to configure setting={ "template_path":os.path.join(os.path.dirname(__file__), "templates"), #Define the address of the view page and put it in the html file "static_path":os.path.join(os.path.dirname(__file__), "static"), #Define static templates and put them in {css,js and other files # "debug":True, #Is it in debug mode "autoescape":None, #Do not set escape character "autoreload":True, "cookie_secret":"QjyutYf0RBW9DRweq4s+TozDU7esgEUTqQy0M6c5II8=", #Security cookie "xsrf_cookies": False, "login_url": "/login", }
Application.py routing profile:
import tornado.web import Python_Tornoda.config as config from Python_Tornoda.util import mysqldb from Python_Tornoda.view.views import MainHandler from Python_Tornoda.view.views import LoginHandler from tornado.web import StaticFileHandler import os current_path = os.path.dirname(__file__) class Appliction(tornado.web.Application): def __init__(self): handers=[ (r"/index/(?P<page>\d*)", MainHandler), (r"/login",LoginHandler), (r'^/(.*?)$', StaticFileHandler,{"path": os.path.join(current_path, "templates"), "default_filename": "main.html"}), ] super(Appliction,self).__init__(handers,**config.setting)
Views.py view function file, take "login" as an example:
from Python_Tornoda.util.bussiness import get_data,execute_sql from Python_Tornoda.util.Pagination import Pagination from tornado.web import RequestHandler import time page_num=5 #Number of items displayed per page #Home page after login class MainHandler(RequestHandler): def get(self,page): sql1 = "select id,pms_name,content,status,mark,create_time from tornado_info order by create_time desc" itemList = get_data(sql1) print(page) if(int(page)>len(itemList)//page_num): pages=len(itemList)//page_num+1 elif(int(page)<1): pages=1 else: pages=int(page) print("ad") page_obj = Pagination(pages, len(itemList), page_num) current_list = itemList[page_obj.start:page_obj.end] print("00000000000") print(current_list) str_pageCtrl = page_obj.pageCtrl('/index/') self.render('info.html', items=current_list, current_page=page_obj.currentPage, pageCtrl=str_pageCtrl, ) class LoginHandler(RegisterHandler): def set_default_headers(self): print('-----set_default_headers:default setting----') self.set_header('Content-Type', 'application/json') def initialize(self): print("-----_initialize Initialization operation-----") print("-----_Initialize database connection-----") print("-----_Initialize open file-----") def prepare(self): print("-----prepare Do some preparatory work-----") print("-----Load configuration item-----") def get(self, *args, **kwargs): print("----get Request processing---") print("----Here you need to click Yes according to the page get Request to process---") username=self.get_query_argument("username") password=self.get_query_argument("password") self.set_secure_cookie(username,password) if(username=="1" and password=="1"): self.redirect("/index/1") else: self.render('main.html') def post(self,*args,**kwargs): print("----post Request processing---") print("----Here you need to click Yes according to the page post Request to process---") username = self.get_body_argument("username") password = self.get_body_argument("password") self.set_secure_cookie(username, password) if (username == "1" and password == "1"): self.redirect("/index/1") else: self.render('main.html') def write_error(self, status_code: int, **kwargs): if(status_code==500): self.write("the server is wrong") elif(status_code==404): self.write("it's not found") else: self.write("the other of error") def on_finish(self): print("----Processing ends and resources are released----") print("----release db connect----") print("----close a file handle----")
Server.py program entry file:
import tornado.ioloop import tornado.web import Python_Tornoda.application as app import Python_Tornoda.config as config if __name__ == '__main__': print("starting tornado...") app = app.Appliction() httpServer = tornado.httpserver.HTTPServer(app) httpServer.bind(config.param['port']) httpServer.start(1) tornado.ioloop.IOLoop.current().start()
Step 6: front end code
Login.html: login page code
You can see in the red box how to submit / login
Index.html: home page code after login
Step7: page effect
7.1 the login page is displayed as follows:
7.2 after login, the main page is displayed as follows:
Note: Although the page is a little simple, the sparrow is small and has all kinds of internal organs. Ha ha~
Welcome to the "test of quantity" official account, reply [resource]
Python+Unittest framework API automation
Python+Unittest framework API automation
Python+Pytest framework API automation
Python + pandas + pyechards big data analysis
Python+Selenium framework Web UI automation
UI automation of Python+Appium framework APP
Python Programming learning resources dry goods
Resources and code are free~
Below the official account is a two-dimensional code, which can be swept directly by WeChat.
Remarks: my official account has been officially opened and dedicated to sharing IT Internet technology.
Including: data analysis, big data, machine learning, test development, API interface automation, test operation and maintenance, UI automation, performance test, code detection, programming technology, etc.
The official account of WeChat search: "the way of testing without quantity", or the following two-dimensional code is scanned:
Add attention, let's grow together!