I’ve revamped my last year’s app. In the beginning there were two different python applications – first one for counting statistics and the second one – web server gunicorn+flask with GET requests. (both services in centos)
Statistics makes counting and stores everything in Postgres. And web server is connected to that Postgres database and answers to GET requests.
In rewritten version I’ve made all statistics using pandas framework and now I want to merge those two apps into one.
I use asyncio to get data and count statistics. Everything works perfectly and now I’m up to add web server to respond to GET.
Part of code:
import asyncio
from contextlib import closing
import db_cl, tks_db
from formdf_cl import FormatDF
getinfofromtks = tks_db.TKS() # Class object to connect to third party database
formatdf = FormatDF() # counting class object, that stores some data
dbb = db_cl.MyDatabase('mydb.ini') # Class object to connect to my database
async def get_some_data():
# getting information from third party database every 5 seconds.
await asyncio.sleep(5)
ans_inc, ans_out = getinfofromtks.getdf()
return ans_inc, ans_out # two huge dataframes in pandas
async def process(ans_inc, ans_out):
# counting data on CPU
await asyncio.sleep(0)
formatdf.leftjoin(ans_inc, ans_out)
# storing statistics in my Database
dbb.query_database('INSERT INTO statistic (timestamp, outgoing, incoming, stats) values (%s, %s,%s, %s)',
formatdf.make_count())
dbb.commit_query()
async def main():
while True:
ans_inc, ans_out = await get_some_data() # blocking, get data from third party database
asyncio.ensure_future(process(ans_inc, ans_out)) # computing
if __name__ == "__main__":
with closing(asyncio.get_event_loop()) as event_loop:
event_loop.run_until_complete(main())
Now I wish to add http server as threaded application (with flask or aiohttp) that will answer to GET requests using parameters from class object “formatdf”.
What’s the best way to include those features?
2
Answers
I managed to add a http server as a corutine. First I tried to use aiohttp, but eventually I found Quart (same as Flask but it uses Asyncio). Sample code to run http server on Quart:
To add this code as corutine I've used
await asyncio.gather()
and used app.run_task instead of app.run. Changed the code from my question like this:The last question that remains is to make available parameters from "formatdf" class object to my http server. I've implemented that adding line
Tests.restapi_quart.app.config["formatdf"] = formatdf
to process(...) function. To call it from quart:I just had to figure this out for my app. Here is how you run an aiohttp server in side an existing asyncio app.
https://docs.aiohttp.org/en/stable/web_lowlevel.html