一个简单的python(tornado + sqlalchemy)web小例子

本文介绍了一个使用Python的Tornado框架实现的简单RESTful风格Web应用,并演示了如何利用SQLAlchemy ORM与MySQL数据库进行交互,包括创建数据库表、查询书籍信息等。

①初始化数据库连接,默认创建一个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>

⑤项目的结构

104258_KjYe_3505336.png

⑥数据库数据

104435_oZ4C_3505336.png

之后就可以通过页面访问这个web接口了:

104554_AUHQ_3505336.png

转载于:https://my.oschina.net/MinghanSui/blog/988731

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值