前几天写东西时候,就想看看tornado连接数据库方面的东西,看了一些东西,还是觉得挺麻烦的,如果有比较好的方法,希望大家给我推荐一下,谢谢
我的application
import tornado.web
import redis
from utils.mysql_helper import DBcontroller
import asyncio
class MyApplication(tornado.web.Application):
def __init__(self,*args, **kwargs):
super(MyApplication, self).__init__(*args, **kwargs)
self.db = DBcontroller()
setting文件
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
setting = dict(
static_path = os.path.join(BASE_DIR, "static"),
template_path = os.path.join(BASE_DIR, "template"),
#redis配置
redis_port = 6379,
redis_host = "127.0.0.1",
#mysql配置
mysql_port = 3306,
mysql_host = "127.0.0.1",
mysql_db = "test2",
mysql_user = "root",
mysql_password = "abcd@1234",
)
handler
class MainHandler(BaseHandler):
@gen.coroutine
def get(self):
username = self.get_argument("name","")
password = self.get_argument("password","")
yield self.application.db.insert(admin_table.user,{"username":username,"password":password})
self.write("ok")
runserver文件
import tornado.web
import tornado.ioloop
from config.urls import urls
from tornado.options import define,options
from config.setting import setting
from config.my_application import MyApplication
define("port",default=8080,type=int,help="run on the given port")
def main():
tornado.options.parse_command_line()
app = MyApplication(urls,**setting)
app.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
创建table
from sqlalchemy import (Table, MetaData, create_engine,
Column, Integer, String, SmallInteger, DateTime)
from datetime import datetime
metadata = MetaData()
user = Table("user", metadata,
Column("password", String(20), nullable=False),
Column("username", String(40), nullable=False),
)
mysql连接工具类
import aiomysql
from config.setting import setting
import asyncio
from aiomysql.sa import create_engine
from tables import admin_table
class DBcontroller:
__isinstance = False
def __new__(cls, *args, **kwargs):
if cls.__isinstance: # 如果被实例化了
return cls.__isinstance # 返回实例化对象
print('connecting to database...')
loop = asyncio.get_event_loop()
loop.run_until_complete(DBcontroller.connect(loop))
cls.__isinstance = object.__new__(cls) # 否则实例化
return cls.__isinstance # 返回实例化的对象
@staticmethod
async def connect(loop):
__engine = await create_engine(user=setting.get("mysql_user","root"),db=setting.get("mysql_db","test"),host=setting.get("mysql_host","127.0.0.1"),password=setting.get("mysql_password","123456"),loop=loop)
if __engine:
DBcontroller.__engine = __engine
DBcontroller.connectStatue =True
print('connect to mysql success!')
else:
raise ("connect to mysql error ")
async def insert(self,table,values):
async with DBcontroller.__engine.acquire() as conn:
trans = await conn.begin()
await conn.execute(table.insert(),values)
await trans.commit()
DBcontroller.__engine.release(conn)
我使用的tornado的版本是6.0以上的版本,有不对的地方希望大家提点建议,一起学习,一起提升一下自己的能力,谢谢。