About Python Tornado

Source: Internet
Author: User

Tornado installation

PIP3 Install tornado

First knowledge of tornado

First open the Pycharm, create a clean project

Create a new py file:

ImportTornado.ioloopImportTornado.webclassMainHandler (Tornado.web.RequestHandler):#similar to the CBV inside Django.    defGet (self):#Get MethodSelf.write ("Hello, World") Application= Tornado.web.Application ([#similar to the routing system inside Django(r"/index", MainHandler),])if __name__=="__main__": Application.listen (8888) tornado.ioloop.IOLoop.instance (). Start ()#Start
app.py

Run the file and open the browser access URL:

Run the script, and then click Execute:

    • Create a Application object and pass in a regular expression '/' and class name MainHandler to the constructor: Tornado.web.Application (...)
    • Executes the listen (...) of the Application object. method, i.e.: Application.listen (8888)
    • The start () method that executes the class of the Ioloop class, namely: Tornado.ioloop.IOLoop.instance (). Start ()

The whole process is to create a socket server and listen to port 8888, when the request arrives, according to the URL and request in the request (post, get or put, etc.) to specify the method in the corresponding class to process the request, In the demo above, only the request for URL Http://127.0.0.1:8888/index is specified for processing class MainHandler(see below for details). So, in the browser petition asked: Http://127.0.0.1:8888/index, the server to the browser will return Hello,world, otherwise return 404:not Found(tornado internally defined values), The HTTP request and response is completed once.

From the above analysis, we divide the entire web framework into two parts:
    • Pending Request phase: Create a server socket and listen for ports
    • Process the request phase, that is, when there is a client connection, accept the request, and according to the different requests to make corresponding corresponding

The classic login case

First, create a template folder and template file:

login.html file

<! DOCTYPE html>"en">"UTF-8"> <title>Title</title>"POST"action="/login"> <input type="text"Name="username"/> <input type="Submit"Value="Submit"/> </form></body>

Create a new route:

    (r "/login", Loginhandler),

New CBV:

classLoginhandler (tornado.web.RequestHandler):defGet (self): Self.render ("login.html")    defPost (self, *args, * *Kwargs):#gets the data that is passed in the URL in the Get formself.get_query_argument () self.get_query_arguments ( )#to get the data passed in the request bodyself.get_body_argument () self.get_body_arguments ( )#go to Get&post to fetch the data .user = Self.get_argument ('username')        Print(user) Self.redirect ('www.baidu.com')

Registered template file path:

# declaration settings, dictionary format settings = {    'template_path'tmp  '}#  register into tornado internal application = tornado.web.Application ([    (R " /index " , MainHandler),    (R"/login"**settings)

Overall app File:

#!/usr/bin/env Python3#Encoding:utf-8#Author:dandyImportTornado.ioloopImportTornado.webclassMainHandler (tornado.web.RequestHandler):defGet (self): Self.write ("Hello, World")classLoginhandler (tornado.web.RequestHandler):defGet (self): Self.render ("login.html")    defPost (self, *args, * *Kwargs):#gets the data that is passed in the URL in the Get formself.get_query_argument () self.get_query_arguments ( )#to get the data passed in the request bodyself.get_body_argument () self.get_body_arguments ( )#go to Get&post to fetch the data .user = Self.get_argument ('username')        Print(user) Self.redirect ('www.baidu.com') Settings= {    'Template_path':'tmp'}application=Tornado.web.Application ([(R"/index", MainHandler), (R"/login", Loginhandler),],**settings)if __name__=="__main__": Application.listen (8888) tornado.ioloop.IOLoop.instance (). Start ()
View Code

This can be done

About static files

First add a static folder and put in a picture

Static path registration:

Settings = {    'template_path'tmp',     'static_path'statics'}

Login page to add pictures, Note the following path is static, standard usage

<! DOCTYPE html>"en">"UTF-8"> <title>Title</title>"POST"action="/login"> <input type="text"Name="username"/> <input type="Submit"Value="Submit"/> </form> "/static/. JPEG"/></body>

Visit the page at this time

Can you use static as the name of the folder?

The answer, of course, is yes, but only if you register:

 settings = {  '  template_path  " :  " tmp   "  Span style= "COLOR: #800000" > " static_path   ' :  '  statics   '  

It's good to change the login page again.

About Python Tornado

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.