tornado template模块运用的简单示例

学习tornado框架,在零基础的前提下,短时间内不可能达到精通tornado模块,因此对初学者最重要的是了解从前端到后台的一整套开发流程。

本文主要是template模块的简单运用。main.py代码如下:

import os.path
import random
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import  options,define
define("port",default=8000,help="on the given help", type="int")

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

class MungedPageHandler(tornado.web.RequestHandler):
     def map_by_first_letter(self,text):
           mapped=dict()
           for line in text.split('\r\n'):
                    for word in [ x for x in line if len(x)>0 ]:
                           if word[0] not in mapped:
                                  mapped[word[0]]=[]
                           mapped[word[0]].append(word)
           return mapped

     def post(self):
           source_map=self.get_argument('source')
           text_change=self.get_argument('change')
           source_map=self.map_by_first_letter(source)
           change_lines =text_change.split('\r\n')
           self.render('munged.html',source_map=source_map,change_lines=text_change_line,choice=random.choice)

if __name__ == '__main__':
         tornado.options.parse_command_line()
         app = tornado.web.Application(
             handlers=[(r'/', IndexHandler), (r'/poem', MungedPageHandler)],
             template_path=os.path.join(os.path.dirname(__file__), "templates"),
             static_path=os.path.join(os.path.dirname(__file__), "static"),
             debug=True
         )
         http_server = tornado.httpserver.HTTPServer(app)
         http_server.listen(options.port)
         tornado.ioloop.IOLoop.instance().start()

for line in text.split('\r\n'):#line代表文本的一行
for word in [ x for x in line if len(x)>0 ]:#word是line的一个元素,[]中的x代表word因此可等效于if   len(word)>0 and for word in line:

debug属性设置为true,调试结束,再把debug属性设置为false。


 在template 文件夹下包含3个html程序,分别是indext.html  、poem.html和  munged.html.

如下为index.html

torn<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="{{ static_url("style.css") }}">
        <title>The Alpha Munger</title>
    </head>
    <body>
        <h1> The Alpha Munger</h1>
        <p>Enter two texts below. The replacement text will have its words
            replaced by words beginning with the same letter in the source text.
            </p>
        <form method="post" action="/poem">   
        <p>Source text<br>    
            <textarea rows=4 cols=55 name="source"></textarea></p>
        <p>Text for replacement<br>
            <textarea rows=4 cols=55 name="change"></textarea></p>
        <input type="submit">
        </form>
    </body>
</html>

 如下为munged.html

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="{{ static_url("style.css") }}">
        <title>The Alpha Munger</title>
    </head>
    <body>
        <h1>Your text</h1>
        <p>
{% for line in change_lines %}
    {% for word in line.split(' ') %}
        {% if len(word) > 0 and word[0] in source_map %}
            <span class="replaced"
                    title="{{word}}">{{ choice(source_map[word[0]]) }}</span>
        {% else %}
            <span class="unchanged" title="unchanged">{{word}}</span>
        {% end %}
    {% end %}
            <br>
{% end %}
        </p>
    </body>
</html>

main.py 中self.render('munged.html',source_map=source_map,change_lines=text_change_line,choice=random.choice)

 change_lines中对应munged.html第10行的change_lines,source_map对应munged.html第12行的change_lines。

如下为poem.html 

<!DOCTYPE html>
<html>
    <head><title>Poem Maker Pro</title></head>
    <body>
        <h1>Your poem</h1>
        <p>Two {{roads}} diverged in a {{wood}}, and I—<br>
I took the one less travelled by,<br>
And that has {{made}} all the {{difference}}.</p>
    </body>
</html>

 新建一个static文件夹,里面存放文件style.css

body{
    font-family: Helvetica,Arial,sans-serif;
    width: 600px;
    margin: 0 auto;
}
.replaced:hover { color: #00f; }

Source text:

Twas two texts below.and the slithy toves 
did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrade

Text for replacement

When in the course of human events it becomes necessary for one people to dissolve the political bands which have connected them with another and to assume among the powers of the earth  ,the separates and equal station  to which the Laws of Nature and of Nature's God

而后用浏览器打开链接http://localhost:8000/

图1:

 图2:

 图3:

猜你喜欢

转载自blog.csdn.net/weixin_42528089/article/details/83044609