vibora icon indicating copy to clipboard operation
vibora copied to clipboard

What is the proper way to integrate a database?

Open brizzbane opened this issue 5 years ago • 2 comments

I am wanting to integrate 'GINO' (https://github.com/fantix/gino). They have an extension for sanic, flask, and a couple of others, but not yet vibora.

I'm wanting to use Vibora because it is faster than sanic, and the templating is built in. I am not sure how to integrate the database. If there was an 'ioloop' parameter that was specified when starting the server...I would know what to do, but since there is not, I am not sure how to go about it.

Here is a very basic example...

@app.route('/')
async def home(request: Request):
    await db.set_bind('localhost/gino')
    users = await User.query.where(User.nickname.contains('x')).gino.all()
    return JsonResponse({'hello': users[0].nickname})

I think that I should be moving "await db.set_bind('localhost/gino')", outside of the request, so that it is not done every request. Is this possible?

Thank you for your help!

brizzbane avatar Aug 28 '18 15:08 brizzbane

I think we will need to wait for #155 .

stop5 avatar Sep 01 '18 10:09 stop5

I did it using components.add function

from vibora import Vibora, JsonResponse, Response
from asyncpg import create_pool
from vibora.hooks import Events
import logging


app = Vibora(log_handler=None)

DB_CONFIG = {
    "host": "127.0.0.1",
    "user": "gustavo",
    "password": "test",
    "port": "5432",
    "database": "test",
}

# Config will be a new component.


class Config:
    def __init__(self):
        self.name = "Vibora Component postgresql"

    def set_pool(self, pool):
        self.pool = pool


def jsonify(records):
    """
    Parse asyncpg record response into JSON format
    """
    # print(records)
    list_return = []

    for r in records:
        itens = r.items()
        list_return.append(
            {i[0]: i[1].rstrip() if type(i[1]) == str else i[1] for i in itens}
        )
    return list_return


@app.handle(Events.BEFORE_SERVER_START)
async def before_start():
    pool = await create_pool(**DB_CONFIG, max_size=20)
    cfg = Config()
    cfg.set_pool(pool)
    app.components.add(cfg)


@app.route("/db2", methods=["GET"])
async def home(postg: Config):
    async with postg.pool.acquire() as conn:
        results = await conn.fetch(
            "SELECT salary,address,age,id,name FROM test.company"
        )
        results = jsonify(results)
    return JsonResponse(results)


@app.route("/", methods=["GET"])
async def home2():
    return Response(b"hello world!")


if __name__ == "__main__":

    app.run(debug=False, host="0.0.0.0", port=5000, workers=4)`

I was using 0.1.0 branch.

For more information: https://github.com/vibora-io/vibora/issues/176

sharkguto avatar Sep 03 '18 11:09 sharkguto