oncall-engine/engine/common/database.py
Joey Orlando 16196822de
Add utility function to get readonly db key if defined (#1264)
# What this PR does

This is a minor refactor before implementing
https://github.com/grafana/oncall-private/issues/1558.

Additionally, it cleans up a few spots where we do this:
```
# Re-take in case we are in the readonly db context.
```
We currently don't read anything from a read-only database, so this
should be not necessary.

## Checklist

- [x] Tests updated
- [ ] Documentation added (N/A)
- [ ] `CHANGELOG.md` updated (N/A)
2023-02-01 12:07:32 +01:00

17 lines
674 B
Python

import random
from django.conf import settings
def get_random_readonly_database_key_if_present_otherwise_default() -> str:
"""
This function returns a string, representing a key in the DATABASES django settings.
If settings.READONLY_DATABASES is set, and non-empty, it randomly chooses one of the read-only databases,
otherwise it falls back to "default".
This is primarily intended to be used for django's QuerySet.using() function
"""
using_db = "default"
if hasattr(settings, "READONLY_DATABASES") and len(settings.READONLY_DATABASES) > 0:
using_db = random.choice(list(settings.READONLY_DATABASES.keys()))
return using_db