This repository has been archived by the owner on Feb 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Tally provider occurrences in results
- Loading branch information
1 parent
d0e2e5e
commit 0965bd0
Showing
3 changed files
with
61 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
from collections import defaultdict | ||
from datetime import datetime | ||
|
||
from django_redis import get_redis_connection | ||
from django_redis.client.default import Redis | ||
|
||
|
||
def _get_weekly_timestamp() -> str: | ||
"""Get a timestamp for the Monday of any given week.""" | ||
now = datetime.now() | ||
return datetime( | ||
now.year, | ||
now.month, | ||
# Set the day to Monday of the current week | ||
now.day - now.weekday(), | ||
).strftime("%Y-%m-%d") | ||
|
||
|
||
def count_provider_occurrences(results: list[dict]) -> None: | ||
# Use ``get_redis_connection`` rather than Django's caches | ||
# so that we can open a pipeline rather than sending off ``n`` | ||
# writes and because the RedisPy client's ``incr`` method | ||
# is safe by default rather than Django's handspun method which: | ||
# 1. Takes two requests to execute; and | ||
# 2. Raises a ``ValueError`` if the key doesn't exist rather than | ||
# just initialising the key to the value like Redis's behaviour. | ||
tallies: Redis = get_redis_connection("tallies") | ||
|
||
provider_occurrences = defaultdict(int) | ||
for result in results: | ||
provider_occurrences[result["provider"]] += 1 | ||
|
||
week = _get_weekly_timestamp() | ||
with tallies.pipeline() as pipe: | ||
for provider, occurrences in provider_occurrences.items(): | ||
pipe.incr(f"provider_occurrences:{week}:{provider}", occurrences) | ||
pipe.incr(f"provider_appeared_in_searches:{week}:{provider}", 1) | ||
|
||
pipe.execute() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters