2

I'm working on a Python app for a university project, that uses Kivy as the UI framework. We're using the async event-loop like this:

import asyncio
from ui.app import SuperhirnApp

app = SuperhirnApp()

loop = asyncio.get_event_loop()
loop.run_until_complete(app.async_run(async_lib="asyncio"))
loop.close()

This works perfectly fine. I'm now trying to add FastAPI to the application to send and receive network requests, to make the game multiplayer-capable. I've installed FastAPI and uvicorn to run a webserver, but I'm struggling to make Kivy and uvicorn run at the same time. Here's what I tried:

import asyncio
from fastapi import FastAPI
from ui.app import SuperhirnApp
import uvicorn

api = FastAPI()
app = SuperhirnApp(api=api)

uvicorn.run("main:api", host="0.0.0.0", port=8000)

loop = asyncio.get_event_loop()
loop.run_until_complete(app.async_run(async_lib="asyncio"))
loop.close()

When running this with python src/main.py, it crashes right away with the following error:

 RuntimeError: asyncio.run() cannot be called from a running event loop
 sys:1: RuntimeWarning: coroutine 'Server.serve' was never awaited

How can I make asyncio run Kivy and FastAPI/uvicorn run in parallel?

henrik-dmg
  • 1,448
  • 16
  • 23
  • 2
    Please have a look at [this answer](https://stackoverflow.com/a/70873984/17865804) and [this answer](https://stackoverflow.com/a/76148361/17865804) as well. – Chris Jul 01 '23 at 09:39
  • 1
    The second answer worked for me, thank you so much! – henrik-dmg Jul 01 '23 at 10:00

1 Answers1

1

As mentioned by Chris, this answer solved it for me:

api = FastAPI()
app = SuperhirnApp()

@api.get('/')
def main():
    return 'Hello World!'


def start_kivyapp(loop):
    loop.run_until_complete(app.async_run(async_lib="asyncio"))


def start_uvicorn_server(loop):
    config = uvicorn.Config(api, loop=loop)
    server = uvicorn.Server(config)
    loop.create_task(server.serve())


loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
start_uvicorn_server(loop)
start_kivyapp(loop)
henrik-dmg
  • 1,448
  • 16
  • 23