Tornado学习笔记1
1.Tornado的hello world
from threading import main_thread
from tornado import web,ioloop,httpserver
class MainPageHandler(web.RequestHandler):
def get(self,*args,**kwargs):
self.write("Hello")
app=web.Application(
[
(r"/",MainPageHandler),
]
)
if __name__=='__main__':
http_server=httpserver.HTTPServer(app)
http_server.listen(8000)
ioloop.IOLoop.current().start()
2.留言板Demo
from tornado import web,ioloop,httpserver
import time
class MainPageHandler(web.RequestHandler):
def get(self,*args,**kwargs):
self.render('index.html',name='Home',messages=MESSAGES)
class WishHandler(web.RequestHandler):
def get(self,*args,**kwargs):
self.render("wish.html")
def post(self,*args,**kwargs):
content=self.get_argument("content")
name=self.get_argument("name")
if content:
MESSAGES.append({
"name":name,
"content":content,
"id":len(MESSAGES)+1,
"num":len(MESSAGES)+1,
"time":time.strftime('%Y-%m-%d %H:%M:%S')
})
self.redirect("/")
else:
self.write("内容不能为空!")
settings={
"template_path":"templates", # 配置模板目录
"static_path":"statics", # 配置静态文件目录
"debug":True, # 配置Debug模式
}
app=web.Application(
[ # 注册路由
(r"/",MainPageHandler),
(r'/wish',WishHandler)
],**settings
)
MESSAGES = [
{'id':1,'name':'韩信','time':'2020-05-20 05:21:00','content':'张三,我喜欢你','num':1},
{'id':2,'name':'李白','time':'2020-05-20 05:21:00','content':'来干来干','num':2}
]
if __name__=='__main__':
http_server=httpserver.HTTPServer(app)
http_server.listen(8000)
ioloop.IOLoop.current().start()
前台页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{ name }}</h1>
<form action="/wish" method="post">
<p>Name : <input type="text" name="name" id=""></p>
<p>Content:</p>
<textarea name="content" id="" cols="50" rows="10"></textarea>
<p><input type="submit" value="submit"></p>
</form>
{% for message in messages %}
<p>{{ message["id"] }} | {{ message["time"] }} | {{ message["num"] }} |{{ message["name"] }} : {{ message["content"]}}</p>
<p>------------------------------</p>
{% end %}
</body>
</html>