1、app.py
import random
import time
import datetime
import tornado.web
import tornado.ioloop
from tornado.options import options, define, parse_command_line
define('port', default=8080, type=int, help="运行端口")
class FirstHandler(tornado.web.RequestHandler):
def get(self):
self.write("<h1><span style='color:red'>这是首页面</span></h1>")
class PictureHandler(tornado.web.RequestHandler):
def get(self):
self.write("<html><body><img src='/static/images/1.jpg'></body></html>")
#这里satic前面加上/(正斜杆)是代表绝对路径,如果不加,则代表相对路径,但是在多个路由的时候就会报错。
def initialize(self):
print('对象{}被创建了'.format(self))
class TemplateHandler(tornado.web.RequestHandler):
def get(self):
username = '小龙'
items = ["Item 1", "Item 2", "Item 3"]
line = "====="*6
time_now = time.time()
atga = "<a href='http://www.baidu.com' target='_blank'>_百度_</a><br>"
student_list = [
{'name': '小红', 'age': 18, 'hobby': '打篮球', 'web': 'http://www.baidu.com'},
{'name': '小明', 'age': 16, 'hobby': '打篮球', 'web': 'http://www.jianshu.com'},
{'name': '小浩', 'age': 20, 'hobby': '打羽毛球', 'web': 'http://www.baidu.com'},
]
self.render('1demo.html', username=username, title="基础模板", items=items, students=student_list, line=line, time=time_now, atga=atga)
def post(self):
username = self.get_argument('name', 'no')
number = int(random.random()*100 + 1)
self.render('2demo.html', username=username, num=number)
def make_app():
handlers = [
(r'/', FirstHandler),
(r'/picture', PictureHandler),
(r'/template', TemplateHandler)
]
settings = \
{'debug': True,
'static_path': 'static',
'template_path': 'templates'
}#直接写staic这里是相对路径,这是相对与这个脚本的路径而言的
app = tornado.web.Application(handlers=handlers, **settings)
return app
if __name__ == '__main__':
app = make_app()
# app.listen(8000)
parse_command_line()
port_new = options.port
app.listen(port_new)
print(type(port_new))
print("Tornado server running at %s port" % port_new)
tornado.ioloop.IOLoop.current().start()
2、1demo.html
<!DOCTYPE html>
<br lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title}}</title>
</head>
{{ linkify("Hello http://tornadoweb.org!") }}
{% autoescape None%}
{# 当前时间{{time}}<br>#}
{{ escape(atga) }}<br>
{% raw atga %}
大家好!我是{{ username }} </br>
传过来的数据是{{items}} </br>
{% if len(items) > 2 %}
传过来的数据长度是{{len(items)}}<br>
第一个数据为{{items[0]}}
{% else%}
传过来的数据长度小于2
{%end%}
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% end %}
</ul>
{% set a=5 %}
{{ line }}<br>
{% while a < 10%}
{{ a }}<br>
{% set a +=1 %}
{% end %}
<br>
{{ line }}<br>
{% for student in students%}
名字为{{student['name']}}<br>
年龄为{{student['age']}}<br>
爱好为{{student['hobby']}}<br>
个人网址为<a href=" {{ student['web'] }}"> {{ student['web'] }}</a> <br>
{{line}}<br>
{%end%}
<img src="/static/images/1.jpg" width="250" height="250"/>
<img src="{{ static_url('images/1.jpg') }}" width="250" height="250"/>
</body>
</html>
3、2demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Torando</title>
</head>
<br>
欢迎{{username}}!!!</br>
是第{{num}}号
</body>
</html>
网友评论