tornado图片:百度脑图
manage.py 启动文件
import os import tornado.web import tornado.ioloop from tornado.options import define, options, parse_command_line from app.views import IndexHandler from app.views import XindexHandler from app.views import DbHandler from app.views import DropDbHandler from app.views import AddStuHandler from app.views import StusHandler # 定义默认的启动端口port为80 define('port', default=8080, type=int) def make_app(): # handlers参数中定义路由匹配地址 return tornado.web.Application(handlers=[ (r'/index/', IndexHandler), (r'/xindex/',XindexHandler), (r'/init_db/', DbHandler), (r'/drop_db/', DropDbHandler), (r'/add_stu/', AddStuHandler), (r'/stus/', StusHandler) ], # 模板文件 template_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'templates'), # 静态文件 static_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'static') ) if __name__ == '__main__': # 解析启动命令 python xxx.py --port=端口号 parse_command_line() # 启动/生成Application对象 app = make_app() # 监听端口 app.listen(options.port) # 监听启动的IO实例 tornado.ioloop.IOLoop.current().start()
app/views.py 视图文件
import tornado.web from app.models import create_db from app.models import drop_db from utils.conn import session from app.models import Student from sqlalchemy import not_, or_, and_ class IndexHandler(tornado.web.RequestHandler): def get(self): self.write('hello day2 tornado') class XindexHandler(tornado.web.RequestHandler): def get(self): # 页面渲染 items = ['Python', 'Php', 'C++', '精通'] self.render('index.html',items=items) class DbHandler(tornado.web.RequestHandler): def get(self): create_db() self.write('创建表成功') class DropDbHandler(tornado.web.RequestHandler): def get(self): drop_db() self.write('删除表成功') class AddStuHandler(tornado.web.RequestHandler): def post(self): # 创建单条数据 # stu = Student() # stu.s_name = '大爷灰' # session.add(stu) # session.commit() # 创建多条数据 stus = [] for i in range(10): stu = Student() stu.s_name = '大爷灰_%s' % i stus.append(stu) session.add_all(stus) session.commit() self.write('新增数据成功') class StusHandler(tornado.web.RequestHandler): def get(self): # stu = session.query(Student).filter(Student.s_name == '大爷灰').all() stu = session.query(Student).filter_by(s_name = '大爷灰').all() print(stu) self.write('查询数据成功') def delete(self): # 实现删除,第一种,session.delete() stu = session.query(Student).filter_by(s_name = '大爷灰').first() if stu: session.delete(stu) session.commit() # 第二种, 调用delete()方法 session.query(Student).filter(Student.s_name == '大爷灰_1').delete() session.commit() self.write('删除成功') def patch(self): # 实现修改部分的属性 # 第一种方法 # stu = session.query(Student).filter(Student.s_name == '大爷灰_0').first() # stu.s_name = '大爷灰' # session.add(stu) # session.commit() # 第二种方法 session.query(Student).filter(Student.s_name == '大爷灰_2').update({'s_name':'赵大爷'}) session.commit() self.write('修改数据成功')
templates/index.html 模板文件
{% extends 'base.html' %} {% block css %} <!--第一种加载方式:直接定义静态文件的路径--> <!--<link rel="stylesheet" href="/static/css/style.css">--> <!--第二种加载方式--> <link rel="stylesheet" href="{{ static_url('css/style.css')}}"> {% end %} {% block content %} <p>好开心</p> <!-- 变量的解析, 使用{# {{ 变量名 }} #}--> {{ items }} {# for标签,使用{% for %} {% end %} #} {% for i in items %} {% if i == 'Python' %} <p style="color:red;">{{ i }}</p> {% elif i == 'Php' %} <p style="color:green;">{{ i }}</p> {% else %} <p>{{ i }}</p> {% end %} {% end %} {{ items[0] }} {% while len(items) %} <p>{{ items.pop() }}</p> {% end %} <!--如果通过下标取items的元素,如果下标超过了items的长度--> {% try %} <p>{{ items[0] }}</p> {% except %} <p>下标越界</p> {% finally %} <p>必须执行的操作</p> {% end %} {% set n=1 %} <p>{{ n }}</p> {% end %}
templates/base.html 模板文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> {% block title %} {% end %} </title> {% block css %} {% end %} {% block js %} {% end %} </head> <body> {% block content %} {% end %} </body> </html>
static/css/style.css 静态文件
p { font-weight: bold; font-family: '微软雅黑'; font-size: 20px; }
app.models.py 模型表
from sqlalchemy import Column, Integer, String from utils.conn import Base def create_db(): # 创建模型映射的表 Base.metadata.create_all() def drop_db(): # 删除模型映射的表 Base.metadata.drop_all() class Student(Base): # 定义自增,int类型的主键 id = Column(Integer, primary_key=True, autoincrement=True) # 定义不能为空的唯一姓名字段 s_name = Column(String(10), unique=True, nullable=False) s_age = Column(Integer,default=18) __tablename__ = 'student' # def repr(self):
utils/conn.py 连接数据库
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # 连接数据库 # mysql+pymysql://root:12345@127.0.0.1:3306/tornado9 db_url = 'mysql+pymysql://root:123@127.0.0.1:3306/tornado9' # 创建引擎,建立连接 engine = create_engine(db_url) # 模型与数据库表进行关联的基类,模型必须继承Base Base = declarative_base(bind=engine) # 创建session会话 DbSession = sessionmaker(bind=engine) session = DbSession()