Can't check if user exist in Postgres DB aiohttp

186 views Asked by At

Here you can see model of User with its methods

class User:

    def __init__(self, db, data, *kw):
        self.db = db
        self.username = data[0]
        self.pass_hash = argon2.argon2_hash(data[1], salt=b'salty salt')

    async def check_user(self, **kw):
        async with self.db.acquire() as conn:
            user = await conn.execute(users.select().where(users.c.username == self.username))
        return user

    async def create_user(self, **kw):
        user = await self.check_user()
        if not user:
            async with self.db.acquire() as conn:
                await conn.execute(
                    users.insert().values(username=self.username,
                                          pass_hash=self.pass_hash))
            result = 'Success'
        else:
            result = 'User exists'
        return result

There are a two functions, the first is checking if user exists in db, the second add a new user to db. So the main problem is create_user function work correct, but if i add there a check_user, nothing happens. Look down below for view method in which i call this function

async def signin(request):
    data = [request.rel_url.query['username'],
            request.rel_url.query['pass_hash']]

    user = User(request.app['db'], data)
    result = await user.create_user()
    if isinstance(result, ObjectId):
        return web.Response(content_type='application/json', text=convert_json(result))

Can someone tell me what's wrong? The logs are empty, i haven't receive any errors, but nothing happens too. Fell free to answer. Thanks everyone

1

There are 1 answers

0
Lilly On BEST ANSWER

So, the main question is that all i need to do is change query and add an attribute to ResultProxy object which returned in check_user

    async def check_user(self, **kw):
        async with self.db.acquire() as conn:
            s = sa.select([users]).where(users.c.username == self.username)
            return await conn.execute(s)

    async def create_user(self, **kw):
        user = await self.check_user()
        if not user.rowcount:
            async with self.db.acquire() as conn:
                await conn.execute(
                    users.insert().values(username=self.username,
                                          pass_hash=self.pass_hash))
            result = 'Success'
        else:
            result = 'User exists'
        return result