①初始化数据库连接,默认创建一个Book表
# coding=utf-8
from sqlalchemy import Column, create_engine, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 初始化数据库连接:
engine = create_engine('mysql+mysqlconnector://root:root@localhost:3306/dbName?charset=utf8',
encoding="utf-8",
echo=True)
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
# 生成orm基类
Base = declarative_base()
class Book(Base):
__tablename__ = 'book'
id = Column(Integer, primary_key=True)
book_name = Column(String(200))
author = Column(String(200))
Base.metadata.create_all(engine)
②定义一个BaseHandle用来操作数据库
# coding=utf-8
import tornado.web
from db import DBSession
class Base_handle(tornado.web.RequestHandler):
def initialize(self):
self.db = DBSession()
③一个简单的restful风格的web小程序,这里就不多说了。。。
# coding=utf-8
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import os.path
from tornado.options import define, options
from baseHandle import Base_handle
from db import Book
define("port", default=8000, help="run on the given port", type=int)
class MainHandler(Base_handle):
def get(self, book_name):
books = self.db.query(Book).filter(Book.book_name == book_name).all()
self.render("book.html", books=books)
def post(self, book_name):
self.get(book_name)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/book/([0-9a-zA-Z\-\_]+)", MainHandler),
]
settings = dict(
cookie_secret="43oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
login_url="/login",
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
xsrf_cookies=True,
)
tornado.web.Application.__init__(self, handlers, **settings)
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
④页面代码。。。没啥代码。。。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Tornado Book Demo</title>
</head>
<body>
<div id="body">
<table>
<thead>
<tr>
<th>编号</th>
<th>书本名称</th>
<th>书本作者</th>
</tr>
</thead>
<tbody>
{% for bk in books %}
<tr>
<td>{{bk.id}}</td>
<td>{{bk.book_name}}</td>
<td>{{bk.author}}</td>
</tr>
{% end %}
</tbody>
</table>
</div>
</body>
</html>
⑤项目的结构
⑥数据库数据
之后就可以通过页面访问这个web接口了: