当前位置:网站首页>Tornado environment construction and basic framework construction -- familiar Hello World

Tornado environment construction and basic framework construction -- familiar Hello World

2022-06-11 16:45:00 InfoQ


  • tornado Official documents :
  • Official English documents
  • chinese 4.3

1. Project environment construction

In order to simulate project development in real work , The project development of this column also adopts local pycharm Develop by connecting remote virtual machines . Environment construction steps are the same django The construction steps of the project environment are the same ( The soup does not change the dressing , I have talked about it in detail before ):《2. Step by step, teach you how to use pycharm Run the first Django project 》 Back out !

  • In the virtual machine, create the python A virtual environment ( Appoint python Version is python3)ubuntu command :

mkvirtualenv -p python3 tudo

  • install tornado library ( Specify version as 5.1.1)ubuntu command :

pip install tornado==5.1.1

  • ubuntu View the installation package commands :

pip list

null

2.tornado The basic framework of the project is built

① conversant hello world

  • Code (hello.py):

# -*- coding: utf-8 -*-
"""
__author__ =  Lonely and cold
"""
#  function tornado The library of
import tornado.ioloop

import tornado.web


# HTTP Request processing   similar Django Class view in
class MainHandler(tornado.web.RequestHandler):
 def get(self):
 self.write("Hello, world")


#  Defining interfaces
application = tornado.web.Application(
 [(r'/',MainHandler)]
)


if __name__ == '__main__':
 #  Define port
 application.listen(8080)
 #  function tornado
 tornado.ioloop.IOLoop.current().start()

  • Run the top py After the file, the browser accesses the specified port (127.0.0.1:8080) The following response indicates that the test is successful —— Can carry out project development !

null

3. Construction of the basic framework of the project

① To write tornado Run the file (app.py):

  • If all the code is written together like test code , Will create a py The consequence of the file being too large —— It also contains all the code for defining interfaces and class views , And it's not easy to distinguish the functions of specific code blocks ( Of course , If you have to do that, it's not impossible ,tornado It's so casual ~);
  • therefore , Now use another way of writing —— Inherit and override the class that defines the interface tornado.web.Application, Make the definition interface written separately from the class view !!!

# -*- coding: utf-8 -*-
"""
__author__ =  Lonely and cold
"""
import tornado.ioloop
import tornado.web

import tornado.options

from tornado.options import define,options

from handlers import main

define('port',default='8000',help='Listeningport',type=int)

class Application(tornado.web.Application):
 def __init__(self):
 handlers = [
 ('/',main.IndexHandler),
 ('/explore',main.ExploreHandler),
 ('/post/(?P<post_id>[0-9]+)',main.PostHandler),
 ]
 settings = dict(
 debug=True,
 #  Configure template path
 template_path='templates',
 #  Configure static file path
 static_path='static'
 )
 
 super().__init__(handlers, **settings)
application = Application()


if __name__ == '__main__':
 tornado.options.parse_command_line()
 application.listen(options.port)
 print('Server start on port {}'.format(options.port))
 tornado.ioloop.IOLoop.current().start()

② establish handlers package , Created within main.py Document business logic :

null
# -*- coding: utf-8 -*-
&quot;&quot;&quot;
__author__ =  Lonely and cold
&quot;&quot;&quot;
import tornado.web


class IndexHandler(tornado.web.RequestHandler):
 def get(self, *args, **kwargs):
 self.render('index.html')


class ExploreHandler(tornado.web.RequestHandler):
 def get(self, *args, **kwargs):
 self.render('explore.html')


class PostHandler(tornado.web.RequestHandler):
 def get(self, post_id):
 #  Pass parameters to post.html
 self.render('post.html',post_id=post_id)

③ Create template file (templates Folder ):

  • The parent template —— Used for template inheritance (base.html):

<!DOCTYPE html>
<html lang=&quot;en&quot;>
<head>
 <meta charset=&quot;UTF-8&quot;>
 <title>{% block title %}Tornado Title{% end %}</title>
</head>
<body>
{% block content %}Default body of base {% end %}


</body>
</html>

  • home page (index.html):

{% extends 'base.html' %}


{% block title %} index page{% end %}

{% block content %}
I am index
{% end %}

  • Discovery page (explore.html):

{% extends 'base.html'%}

{% block title %}explore page{% end %}

{% block content %}
I am explore
{% end %}

  • Details page (post.html):【 Display the received parameters post_id

{% extends 'base.html' %}

{% block title %} post page {% end %}
{% block content %}
I am post {{ post_id }}
{% end %}

④ establish static The file is used to store js and css

⑤ Run the project :

null
null
null
  • Full column at CSDN to update , Those who are interested can go and see it ~
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111629190418.html