Tornado WEB服务器框架 Epoll-- 【Mysql数据库】
阅读原文时间:2023年07月08日阅读:1

5.1 数据库

与Django框架相比,Tornado没有自带ORM,对于数据库需要自己去适配。我们使用MySQL数据库。

在Tornado3.0版本以前提供tornado.database模块用来操作MySQL数据库,而从3.0版本开始,此模块就被独立出来,作为torndb包单独提供。torndb只是对MySQLdb的简单封装,不支持Python 3。

python2 : pip install torndb    python3:pip install torndb_for_python3

我们需要在应用启动时创建一个数据库连接实例,供各个RequestHandler使用。我们可以在构造Application的时候创建一个数据库实例并作为其属性,而RequestHandler可以通过self.application获取其属性,进而操作数据库实例。

import torndb_for_python3 as torndb
from tornado.web import RequestHandler,Application

class Application(Application):
'''重写应用,增加数据库连接功能'''
def __init__(self,handlers,**kwargs):
super(Application,self).__init__(handlers=handlers,**kwargs)
print(kwargs)
self.db = torndb.Connection(
host='192.168.135.29',
database='test',
user='admin',
password='Wyf@1314'
)

新建数据库与表:

create database `test` default character set utf8;

use test;

create table houses (
id bigint(20) unsigned not null auto_increment comment '房屋编号',
title varchar(64) not null default '' comment '标题',
position varchar(32) not null default '' comment '位置',
price int not null default 0,
score int not null default 5,
comments int not null default 0,
primary key(id)
)ENGINE=InnoDB default charset=utf8 comment='房屋信息表';

1. 执行语句

  • execute(query, _parameters, *_kwparameters) 返回影响的最后一条自增字段值
  • execute_rowcount(query, _parameters, *_kwparameters) 返回影响的行数

query为要执行的sql语句,parameters与kwparameters为要绑定的参数,如:

db.execute("insert into houses(title, position, price, score, comments) values(%s, %s, %s, %s, %s)", "独立装修小别墅", "紧邻文津街", 280, 5, 128)
或
db.execute("insert into houses(title, position, price, score, comments) values(%(title)s, %(position)s, %(price)s, %(score)s, %(comments)s)", title="独立装修小别墅", position="紧邻文津街", price=280, score=5, comments=128)

执行语句主要用来执行非查询语句。

insert 语句一般如果表结构有id字段会返回这个自增的唯一ID字段

class UseTorndbHandler(RequestHandler):def post(self, *args, **kwargs):
'''测试上传数据报保存到数据库'''
title = self.get_argument("title")
position = self.get_argument("position")
price = self.get_argument("price")
score = self.get_argument("score")
comments = self.get_argument("comments")
try:
ret = self.application.db.execute( "insert into houses(title, position, price, score, comments) values(%s, %s, %s, %s, %s)", title, position, price, score, comments)
except Exception as e:
self.write("DB error:%s" % e)
else:
self.write("OK %d" % ret)

2. 查询语句

  • get(query, _parameters, *_kwparameters) 返回单行结果或None,若出现多行则报错。返回值为torndb.Row类型,是一个类字典的对象,即同时支持字典的关键字索引和对象的属相访问。
  • query(query, _parameters, *_kwparameters) 返回多行结果,torndb.Row的列表。

以上一章节模板中的案例来演示,先修改一下 subblock_for_usedb_index.html 模板,将

<span class="house-title">{{title_join(house["titles"])}}</span>

改为

<span class="house-title">{{house["title"]}}</span>


Handler 测试:&nbsp;get、query查询测试代码Handler如下GET get()方法处理, 写入在POST  

class UseTorndbHandler(RequestHandler):
def get(self, *args, **kwargs):
'''测试从数据库获取数据做数量展示'''
limit = self.get_query_argument('query_limit',default='10')
house_id = self.get_query_argument('houseid',default=None)
if house_id:
try:
ret = self.application.db.get("select title,position,price,score,comments from houses where id=%s", house_id)
except Exception as e:
self.write("DB Error : %s" % e)
else:
print('ret type: ', type(ret))
print(ret)
print(ret.title)
print(ret['title'])
self.render('subblock_for_usedb_index_one_house.html', **ret,title_join=house_title_join)
else:
try:
sql = "select title,position,price,score,comments from houses limit %s" % limit
ret = self.application.db.query( sql)
except Exception as e:
self.write("DB Error : %s" % e)
else:
print('ret type: ',type(ret) )
print(ret)
# print(ret.title)
# print(ret['title'])
self.render('subblock_for_usedb_index.html', houses=ret,title_join=house_title_join)
def post(self, *args, **kwargs):
'''测试上传数据报保存到数据库'''
title = self.get_argument("title")
position = self.get_argument("position")
price = self.get_argument("price")
score = self.get_argument("score")
comments = self.get_argument("comments")
try:
ret = self.application.db.execute( "insert into houses(title, position, price, score, comments) values(%s, %s, %s, %s, %s)", title, position, price, score, comments)
except Exception as e:
self.write("DB error:%s" % e)
else:
self.write("OK %d" % ret)


一个house测试

  • {{price}}/晚
    {{title}} 整套出租 - {{score}}分/{{comments}}点评 - {{position}}
  • subblock_for_usedb_index_one_house.html

    {% extends "base.html" %}

    {% block page_title %}
    数据库,多个house模板index
    {% end %}

    {% block css_files %}

    {% end %}

    {% block js_files %}

    {% end %}

    {% block header %}


    {% end %}

    {% block body %}

      {% if len(houses) > 0 %} {% for house in houses %}
    • {{house["price"]}}/晚
      {{ house["title"]}} 整套出租 - {{house["score"]}}分/{{house["comments"]}}点评 - {{house["position"]}}
    • {% end %} {% else %} 对不起,暂时没有房源。 {% end %}

    {% end %}

    {% block footer %}

    爱家租房  享受家的温馨


    {% end %}

    subblock_for_usedb_index.html



    {% block page_title %}{% end %} {% block css_files %}{% end %}

    {% block header %}{% end %}

    {% block body %}{% end %}

    <script src="{{static\_url('js/jquery.min.js')}}"></script>  
    <script src="{{static\_url('plugins/bootstrap/js/bootstrap.min.js')}}"></script>  
    {% block js\_files %}{% end %}  


    base.html

    手机扫一扫

    移动阅读更方便

    阿里云服务器
    腾讯云服务器
    七牛云服务器

    你可能感兴趣的文章