Difficulty with Synchronous Code Running in Asynchronous Context Using Python 3.11 and Flask
I'm working on a Flask application using Python 3.11 and I'm working with issues when trying to integrate synchronous code into an asynchronous route. Specifically, I'm trying to call a synchronous blocking function from an async route handler, and it seems to be causing my server to hang, or I get a runtime behavior. The function fetches data from an external API, and here's a simplified version of my code: ```python from flask import Flask, jsonify import asyncio import requests app = Flask(__name__) def blocking_call(): response = requests.get('https://api.example.com/data') return response.json() @app.route('/data') async def get_data(): loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, blocking_call) return jsonify(result) ``` When I hit the `/data` endpoint, I sometimes get the following behavior: ``` RuntimeError: There is no current event loop ``` I tried adding `asyncio.set_event_loop(asyncio.new_event_loop())` at the beginning, but that didn't help. I've also checked if the event loop is already set before calling `run_in_executor`, but it seems that the execution context is not correct. How can I properly call this synchronous function in an asynchronous Flask route without causing these runtime issues? Any insights into best practices would be greatly appreciated! I'm working with Python in a Docker container on Windows 11. What are your experiences with this?