diff --git a/playlist/tasks.py b/playlist/tasks.py index 92456a0..204ce76 100644 --- a/playlist/tasks.py +++ b/playlist/tasks.py @@ -12,6 +12,8 @@ from random import choice dotenv.load_dotenv() +UPDATE_FREQ = 10 # How often to save to database + @shared_task def get_banter(id): track = Track.objects.get(pk=id) @@ -25,13 +27,13 @@ def get_banter(id): ) r.raise_for_status() + token = 0 + for line in r.iter_lines(): body = json.loads(line) response_part = body.get('response', '') - # the response streams one token at a time, print that as we receive it - print(response_part, end='', flush=True) + token += 1 track.banter += response_part - track.save() if 'error' in body: raise Exception(body['error']) @@ -40,3 +42,5 @@ def get_banter(id): track.banter_done = True track.save() return body['context'] + elif token % UPDATE_FREQ == 0: + track.save()