I was using MySQL database before, and now I've migrated to PostgreSQL.
Looks like it is very hard to refactor my code for Postgres.
I am experiencing some troubles with find_and_lock_token()
method.
async def init_db_connection():
global conn
conn = await asyncpg.connect(
user=await get_username(),
password=await get_pass(),
host=await get_host(),
port=await get_port(),
database=await get_username()
)
# Working with table named "Tokens", Column names: "Token", "Status", "Name", "ActivityToken"
# Content of the columns | "Token": random token; "Status": 'Busy'/'Free'; "Name": random name; "ActivityToken": random token
async def find_and_lock_token(conn):
while True:
try:
token = await conn.fetchrow(
'SELECT "Token" FROM "Tokens" WHERE "Status" = $1 LIMIT 1 FOR UPDATE SKIP LOCKED',
'Free'
)
if token is not None:
token = token['Token']
await conn.execute(
'UPDATE "Tokens" SET "Status" = $1 WHERE "Token" = $2',
'Busy', token
)
return token
else:
await asyncio.sleep(5)
except Exception as e:
logging.error(f"Error finding and locking token: {e}")
await init_db_connection()
token = await find_and_lock_token(conn)
I have tried bunch of different variations using fetchrow()
, fetchval()
etc.
Everything throws me this 'NoneType'error.
I need this find_and_lock_token
method to work as follows:
All these columns have 'TEXT' type.
I got few 'onLaunch' checks saying that I am connected to the database (very quickly, approx 1-2 seconds.) meaning this is not the trouble.
I checked, by adding delay after connection that con
could not be NoneType
(as nicomp said in comments). Or it is but by different cause, I don't understand why.
None is the type you get when something goes wrong and you need a placeholder. Your issue is before you are trying to use the thing that is of the None type. Look in the code where that thing is initialized, because it's not initialized to what you think of should be. It looks like your connection attempt is failing or is just taking too long. – @nicomp
Have you tried returning conn from the init_db_connection function instead of setting it as a global? – @snakecharmerb
The answer was to make some much advanced logging.
I got a**'NoneType'
** error, meaning that the conn
OBJECT of asyncpg.connect()
had a value of None
. And so when fetchrow()
was trying to access conn | asyncpg.connect()
object it could not do that because my credentials were built by asynchronous methods. Never overuse async.
Conclusion. Never do little logging. If you have done logging, you have done little logging. Always do as much logging as possible. ;) <3