Created
March 22, 2019 07:26
-
-
Save t1f7/5c6764ed5481460d2b9a28f6224cf5bd to your computer and use it in GitHub Desktop.
Django service application with persistent connection
This file contains hidden or 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
| # init django | |
| import os | |
| import sys | |
| sys.path.append(os.path.join(os.path.dirname(__file__), 'apps')) | |
| is_production = os.path.isfile('.production') | |
| if is_production: | |
| os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.settings.production") | |
| else: | |
| os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.settings.dev") | |
| from django.core.wsgi import get_wsgi_application | |
| application = get_wsgi_application() | |
| from django.conf import settings | |
| from django.utils import timezone | |
| # import your models here | |
| from task.models import Task | |
| from client.models import Client | |
| # database connection lost fix | |
| from django.db import connection, reset_queries | |
| from django.db.utils import OperationalError | |
| while True: | |
| db_conn = None | |
| while not db_conn: | |
| try: | |
| connection.ensure_connection() | |
| db_conn = True | |
| reset_queries() | |
| except OperationalError: | |
| print('Database unavailable, waiting 1 second...') | |
| time.sleep(1) | |
| tasks = Task.objects.filter(last_check_at__lte=timezone.localtime() - timezone.timedelta(hours=1)) | |
| if tasks: | |
| # boolean operation executes lazy queries | |
| pass | |
| time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment