Xena
Xena

Reputation: 39

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.TypeError' is not mapped

When executing the code, it displays the error "sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.TypeError' is not mapped"

engine = create_engine('mysql+pymysql://root:[email protected]/exchanges')
Session = sessionmaker(bind=engine)
session = Session()

async def response_to_sql(table):
    for k1, v1 in data.items():
        for t in table:
            if table.__tablename__ == k1:     
                for k2, v2 in v1.items():
                    ins = t(symbol=v2['symbol'], ask=v2['ask'], bid=v2['bid'])
                    return ins


async def handler(tables):
    input_coroutines = [response_to_sql(table) for table in tables]
    response = await asyncio.gather(*input_coroutines, return_exceptions=True)
    session.add_all(response)
    session.commit()
    await session.close()

async def async_client(exchange):
    client = getattr(ccxta, exchange)()
    tickers = await client.fetch_tickers()

    global data
    data = {exchange:tickers}
    
    await client.close()
    return tickers

async def multi_tickers(exchanges):
    input_coroutines = [async_client(exchange) for exchange in exchanges]
    tickers = await asyncio.gather(*input_coroutines, return_exceptions=True)
    a = print("async call spend:", time.time() - tic)
    await handler(tables)
    return tickers

if __name__ == '__main__':
    exchanges = ['binance', 'bitget', 'bitmart', 'bitvavo', 'bybit', 'gate', 'huobi', 'kucoin', 'mexc', 'okx']
    tables = [Binance, Bitget, Bitmart, Bitvavo, Bybit, Gate, Huobi, Kucoin, Mexc, Okx]
    tic = time.time()
    asyncio.run(multi_tickers(exchanges))

Can someone tell me what is causing the error and how can i fix it?

Thanks.

Error:

async call spend: 13.642300844192505
<sql.Gate object at 0x000001D4F0C12410>
Traceback (most recent call last):
  File "c:\Users\Wende\Desktop\arbitr\.venv\Lib\site-packages\sqlalchemy\orm\session.py", line 2636, in add
    state = attributes.instance_state(instance)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute '_sa_instance_state'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\Users\Wende\Desktop\arbitr\main.py", line 50, in <module>
    asyncio.run(multi_tickers(exchanges))
  File "c:\Users\Wende\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "c:\Users\Wende\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\Wende\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "c:\Users\Wende\Desktop\arbitr\main.py", line 43, in multi_tickers
    await handler(tables)
  File "c:\Users\Wende\Desktop\arbitr\main.py", line 25, in handler
    session.add_all(response)
  File "c:\Users\Wende\Desktop\arbitr\.venv\Lib\site-packages\sqlalchemy\orm\session.py", line 2663, in add_all
    self.add(instance, _warn=False)
  File "c:\Users\Wende\Desktop\arbitr\.venv\Lib\site-packages\sqlalchemy\orm\session.py", line 2638, in add
    util.raise_(
  File "c:\Users\Wende\Desktop\arbitr\.venv\Lib\site-packages\sqlalchemy\util\compat.py", line 211, in raise_
    raise exception
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.NoneType' is not mapped
bybit requires to release all resources with an explicit call to the .close() coroutine. If you are using the exchange instance with async coroutines, add `await exchange.close()` to your code into a place when you're done with the exchange and don't need the exchange instance anymore (at the end of your async coroutine).
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001D4EB190F90>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000001D4EAA66740>, 1409138.843), (<aiohttp.client_proto.ResponseHandler object at 0x000001D4EAA66890>, 1409141.328)]']
connector: <aiohttp.connector.TCPConnector object at 0x000001D4EB190D50>

Upvotes: 0

Views: 521

Answers (1)

ljmc
ljmc

Reputation: 5264

Your function response_to_sql will return None if the for k1, v1 in data.items(): loop finishes successfully and the interpreter leaves the function without an explicit return (that's Python's default behaviour).

If that case should never be reached, investigate what data and tables contains.

Either way, this function which has to return a SQLAlchemy mapped Object can return a None and that's a bug.

async def response_to_sql(table):
    for k1, v1 in data.items():
        for t in table:
            if table.__tablename__ == k1:     
                for k2, v2 in v1.items():
                    ins = t(symbol=v2['symbol'], ask=v2['ask'], bid=v2['bid'])
                    return ins

Upvotes: 1

Related Questions