I have this code:
from flask import Flask, request, make_response, jsonify
import asyncio
from master_call import master_call_interface
#Start flask app
app = Flask(__name__)
@app.route("/api/master-call", endpoint="master_call_endpoint", methods=["POST"])
async def master_call_endpoint():
interface = master_call_interface(
all = True
)
response = await interface.get_account_data()
return make_response(jsonify(response), 200))
if __name__ == "__main__":
app.run()
And the idea is that when it's called the get_account_data()
function is run asynchronously and once it is done running the value that is returned from it is sent back as an HTTP 200 response.
The problem is that when I run this code and invoke the endpoint I get the following error:
Traceback (most recent call last):
File "C:\Users\quant\AppData\Roaming\Python\Python39\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\quant\AppData\Roaming\Python\Python39\site-packages\flask\app.py", line 1526, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Users\quant\AppData\Roaming\Python\Python39\site-packages\flask\app.py", line 1545, in finalize_request
response = self.make_response(rv)
File "C:\Users\quant\AppData\Roaming\Python\Python39\site-packages\flask\app.py", line 1734, in make_response
raise TypeError(
TypeError: The view function did not return a valid response. The return type must be a
string, dict, tuple, Response instance, or WSGI callable, but it was a coroutine.
It seems like the problem is that the interface.get_account_data() function is never awaited to complete running. And I'm not sure how to fix this.
I've tried asyncio.run()
which works fine locally. But when I use asyncio.run()
in my production code (a gunicorn
server) it says that I can't use asyncio.run()
as there already is a running event loop. So instead then I try to use asyncio.get_event_loop()
to add the function as a task. But that just results in the code telling me that there is no event loop in the current thread
Any ideas are greatly appreciated