async support in django shell

hi
as you know python interactive shell can be called as python -m asyncio which alows awaiting in the shell
but django doesn’t seems to support that, which makes testing async stuff hard

is there any plans to add this feature?
is is feasible?

1 Like

Hey!

I think it would be feasible to add asyncio as a supported interface, selectable with -i asyncio.

Other interfaces, at least IPython, support asyncio by default. So you may want to use that. I love it and all of its other features :slight_smile:

Adam

3 Likes

I spent some time trying to figure out how to add asyncio as a supported interface and my conclusion is that there isn’t a way to drop into an asyncio-enabled shell from an existing python process. There definitely isn’t a supported mechanism (maybe we should file an upstream issue against python to enable that) but even if we exclude official and try and use the existing interface unofficially it doesn’t work without crazy hacks that should not be upstreamed to Django.

What we could do is duplicate the existing cpython implementation but I’m more in favor of getting a “real” interface landed to cpython and then just calling that.

2 Likes

I did ./manage.py shell and import asyncio in it, and awaitables just work with await my_coroutine(). Python 3.13.1, Django 5.1.4.

hi
i’m not sure what you have seen exactly
but it doesn’t work for me

>>> import asyncio
>>> async def a():
...     return 1
... 
>>> await a()
  File "<console>", line 1
    await a()
    ^^^^^^^^^
SyntaxError: 'await' outside function
>>> 

python 3.13.1t
django 5.1.4

I believe you need to use one of the alternative shells such as ipython to do this as mentioned above:

Python 3.12.6 (main, Sep 10 2024, 00:05:17) [GCC 11.4.0]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.26.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import asyncio

In [2]: async def a():
   ...:     return 1
   ...: 

In [3]: await a()
Out[3]: 1

In [4]: 

See the docs at Asynchronous in REPL: Autoawait — IPython 8.31.0 documentation

hi, yes
i was answering about the default shell.

thanks to people here i got ipython working
thank you :pray:

You can use the -i parameter if you want the Django shell (or shell_plus if you use the django extensions package) to use ipython. That’s how I do it.