hello.py
"""__author__ = song"""
import os
import tornado.ioloop
import tornado.web
from tornado.options import define, options, parse_command_line
import pymysql
# 定义默认启动的端口为80
define('port', default=8080, type=int)
class MainHandler(tornado.web.RequestHandler):
# 必须继承RequestHandler
def get(self):
# 渲染响应给浏览器的数据
name = self.get_argument('name')
self.write('hello tornado')
def post(self):
# self.write('hello tornado post')
name = self.get_argument('name')
class ResHandler(tornado.web.RequestHandler):
def get(self):
self.write('<h2>zzz</h2>')
self.set_status(404)
self.set_cookie('zzz', '123',expires_days=1)
# self.clear_cookie('zzz')
self.redirect('/')
class DaysHandler(tornado.web.RequestHandler):
# def get(self, year, month, day):
def get(self, month, day, year): # http://127.0.0.1/days/2019/03/11/:11年2019月03日
self.write('%s年%s月%s日' %(year , month, day))
class Days2Handler(tornado.web.RequestHandler):
# def get(self, year, month, day):
def get(self, month, day, year): # 2019年03月11日
# 用了参数P之后则就一一对应起来,不受一开始get里参数的顺序影响
self.write('%s年%s月%s日day' %(year , month, day))
def post(self, month, day, year):
self.write('post: 只负责新增数据')
def delete(self, month, day, year):
self.write('delete: 只负责删除')
def patch(self, month, day, year):
self.write('patch: 修改全部属性')
def put(self,month, day, year):
self.write('put: 修改全部属性')
class EntryHandler(tornado.web.RequestHandler):
def initialize(self):
self.conn = pymysql.Connection(host='127.0.0.1',user='root',password='root',port=3306,database='flask9')
self.cursor = self.conn.cursor()
print('initialize')
# self.write('initialize')
def prepare(self):
print('prepare')
def get(self):
print('get')
# 查询flask9数据库 查询所有学生信息
sql = 'select * from stu;'
self.cursor.execute(sql)
data = self.cursor.fetchall()
print(data)
self.write('查询数据')
def post(self):
pass
def on_finish(self):
# 最后执行的方法
print('on_finish')
self.conn.close()
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
def make_app():
# handlers里参数中定义路由匹配地址
return tornado.web.Application(handlers=[
(r'/', MainHandler),
(r'/res/', ResHandler),
(r'/days/(\d{4})/(\d{2})/(\d{2})/', DaysHandler),
(r'/days2/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/', Days2Handler),
(r'/entry_point/', EntryHandler),
(r'/index/', IndexHandler)
],
# D:\workspace\tornado\day01\templates
template_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'templates')
)
if __name__ == '__main__':
# 解析启动命令 python xxx.py --port=端口号
parse_command_line()
# 启动
app = make_app()
app.listen(options.port)
# 监听IO实例
tornado.ioloop.IOLoop.current().start()
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% block title %}
{% end %}
</head>
<body>
{% block content%}
{% end %}
</body>
</html>
index.html
{% extends 'base.html' %}
{% block title %}
首页(子模板)
{% end %}
{% block content %}
<p>hello 模板继承</p>
{% end %}
网友评论