sanic数据库、缓存、模板

from sanic import Sanic
from sanic.response import text, html, json
from jinja2 import Template
import uvloop
import asyncpg
import asyncio_redis

loop = uvloop.new_event_loop()

# 初始pg连接池
async def init_pgpool():
    return await asyncpg.create_pool(database="postgres", user="postgres", password="asdf", loop=loop)
conn_pool = loop.run_until_complete(init_pgpool())

# 初始redis连接池
async def init_rdspool():
    return await asyncio_redis.Pool.create(loop=loop)
redis = loop.run_until_complete(init_rdspool())



indexTpl = Template('hello {{ name }}')


app = Sanic(__name__)


@app.route('/')
async def index(req):
    name = req.args.get('name')
    if name is None:
        name = 'unknow'

    return html(indexTpl.render(name=name))


@app.route('/pg')
async def test(req):
    await redis.set('sanic_', "fuck")

    async with conn_pool.acquire() as conn:

        # async with conn.transaction():
        #     async for record in conn.cursor('select * from temp'):
        #         print(record)

        vs = await conn.fetch('select * from temp')

        page = ''
        for v in vs:
            page += 'name:{:8} value:{}\n'.format(v['name'], v['addr'])

        print(await redis.get('sanic_'))

        return text(page)


app.run(port=8089, loop=loop)

你可能感兴趣的:(sanic数据库、缓存、模板)