orm: Unable to create models

Checklist

  • The bug is reproducible against the latest release and/or master.
  • There are no similar issues or pull requests to fix it yet.

Describe the bug

Unable to create models due to a RuntimeError caused by anyio.

To reproduce

database = databases.Database("url")
models = orm.ModelRegistry(database = database)
models.create_all()

Expected behavior

Models getting created. Successfully connecting to the database.

Actual behavior

The models don’t get created due to the RuntimeError being raised by anyio and it fails to connect to the database.

Debugging material

Traceback from ipython

    RuntimeError                         Traceback (most recent call last)
<ipython-input-1-3765cc235a53> in <module>
     16
     17 # Create the tables
---> 18 models.create_all()
     19
     20 await Note.objects.create(text="Buy the groceries.", completed=False)

/data/data/com.termux/files/usr/lib/python3.9/site-packages/orm/models.py in create_all(self)
     31     def create_all(self):
     32         url = self._get_database_url()
---> 33         anyio.run(self._create_all, url)
     34
     35     def drop_all(self):

/data/data/com.termux/files/usr/lib/python3.9/site-packages/anyio/_core/_eventloop.py in run(func, backend, backend_options, *args)
     40         pass
     41     else:
---> 42         raise RuntimeError(f'Already running {asynclib_name} in this thread')
     43
     44     try:

RuntimeError: Already running asyncio in this thread

Environment

  • OS: Linux aarch64 Android
  • Python version: 3.9.7
  • ORM version: 0.2.0

Additional context

I fixed it by making create_all an async function and using await self._create_all(url) instead of anyio.run(self._create_all, url) although I don’t think that’s the best way to fix this.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 1
  • Comments: 38 (16 by maintainers)

Most upvoted comments

First is that, you can still run your migrations independently, it’s just up to caller to set up the asyncio and cleanup when done in any script.

Ill come back with a pytest reproducible example on this point.

I think that misses a few imports and stuff, I could reproduce it with this example:

app.py

import databases
import orm
from fastapi import FastAPI

database = databases.Database("sqlite:///db.sqlite")

models = orm.ModelRegistry(database=database)


app = FastAPI()

@app.on_event("startup")
async def startup():
    models.create_all()

and running uvicorn app:app causes:

RuntimeError: Already running asyncio in this thread

@aminalaee Oh sure, I’ll give you an update on this once I try that. Thanks for all the help and you can close this issue now.