Sanic template装饰器

Sanic

tools.py

制作可以直接返回模板的装饰器

from jinja2 import Environment, PackageLoader
from functools import wraps
from sanic.response import html

env = Environment(loader=PackageLoader(__name__), enable_async=True)


class Lem:
    @staticmethod
    def template(template_name):
        def wrapper(func):
            @wraps(func)
            async def inner(request, *args, **kwargs):
                template = env.get_template(template_name)
                content = await func(request, *args, **kwargs)  # 注意视图函数是异步的需要await
                return html(await template.render_async(content))

            return inner

        return wrapper

app.py

from sanic import Sanic
from tools import Lem

app = Sanic(__name__)

lm = Lem()

@app.route('/')
@lm.template('index.html')
async def index(request):
    title = 'sanic学习'
    content = '内容'
    return {'title': title, 'content': content}


@app.route('/lis')
@lm.template('lis.html')
async def lis(request):
    title = 'sanic学习1111'
    content = '内容11111'
    return {'title': title, 'content': content}


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8000)

使用dbutils连接数据库提升效率

# config/base/mysql.py


import pymysql
from dbutils.pooled_db import PooledDB





# 数据库线程池单重态
'''
这里的作用就是不用反复建立数据库连接,想用的时候直接从连接池里拿就行了,连接池里有20个连接
'''


class Singleton(object):
    def __new__(cls, conf):
        db = conf.get('db', '')
        if hasattr(cls, '__obj'):
            if db not in cls.__obj:
                obj = super(Singleton, cls).__new__(cls)
                obj.POOL = PooledDB(pymysql, maxconnections=20, setsession=["SET GLOBAL time_zone = '+8:00'"], **conf)
                cls.__obj[db] = obj
        else:
            obj = super(Singleton, cls).__new__(cls)
            obj.POOL = PooledDB(pymysql, maxconnections=20, setsession=["SET GLOBAL time_zone = '+8:00'"], **conf)
            cls.__obj = {db: obj}
        return cls.__obj[db]


class MysqlHelper(Singleton):
    def __new__(cls, conf):
        return super(MysqlHelper, cls).__new__(cls, conf)

    def createConn(self):
        # 创建一个连接
        conn = self.POOL.connection()
        # 得到一个可以执行SQL语句并且将结果作为字典返回的游标
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        return conn, cursor

    # 执行
    def executeParam(self, cursor, sql, param):
        try:
            if param:
                return cursor.execute(sql, param)
            else:
                return cursor.execute(sql)
        except Exception as e:
            raise Exception(e.args[:])

    def close(self, conn, cursor):
        # 关闭游标
        cursor.close()
        # 释放连接
        conn.close()

    def selectOne(self, sql='', *param):
        conn, cursor = self.createConn()
        try:
            self.executeParam(cursor, sql, param)
            res = cursor.fetchone()
            return res
        except Exception as e:
            return None
        finally:
            self.close(conn, cursor)

    def selectAll(self, sql='', *param):
        conn, cursor = self.createConn()
        try:
            self.executeParam(cursor, sql, param)
            res = cursor.fetchall()
            return res
        except Exception as e:
            return None
        finally:
            self.close(conn, cursor)

    def insert(self, sql, *param):
        conn, cursor = self.createConn()
        try:
            res = self.executeParam(cursor, sql, param)
            # 提交
            conn.commit()
            return res
        except Exception as e:
            # 回滚
            conn.rollback()
            return False
        finally:
            self.close(conn, cursor)

    def update(self, sql, *param):
        conn, cursor = self.createConn()
        try:
            res = self.executeParam(cursor, sql, *param)
            return res
        except Exception as e:
            conn.rollback()
            return False
        finally:
            self.close(conn, cursor)

    def delete(self, sql, *param):
        conn, cursor = self.createConn()
        try:
            res = self.executeParam(cursor, sql, param)
            return res
        except Exception as e:
            conn.rollback()
            return False
        finally:
            self.close(conn, cursor)
            
            
# config/settings.py
mysql_config = {"host": 'localhost', "user": 'root', "password": '123456', 'port': 3306, 'db': 'sanic'}


# tools.py
from config.base.mysql import MysqlHelper
from config import settings

mysql_conf = settings.mysql_config
# dbutils 连接mysql数据库
mysql = MysqlHelper(mysql_conf)


# app.py
from tools import Lem, mysql
def select(sql):
    return mysql.selectAll(sql)
    
@app.route('/')
@lm.template('index.html')
async def index(request):
    res = select('SELECT * FROM books ORDER BY RAND() LIMIT 20')
    title = 'sanic学习'
    content = '内容'
    return {'title': title, 'content': content, 'res': res}
# 程序启动前执行
# @app.listener('before_server_start')
# async def set_up(app, loop):
    # app.imgs = get_imgs(app.config.get('IMG_PATH'))
    # app.mysql = MysqlHelper(settings.mysql_config)
posted @ 2021-04-26 16:14  橘丶阳菜  阅读(316)  评论(0编辑  收藏  举报