Sunday, July 28, 2019

Running pending migrations in Middleware

Anyone see any problems with running migrations in Middleware?

import logging
import os
import time

from django.core.management import call_command
from django.http import HttpResponse

from products.models.models import AppVersion

LOG = logging.getLogger(__name__)


# Used for testing locally when the GAE_VERSION environment is not set
FAKE_VERSION_TESTING = 8


class MigrateMiddleware:

def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
start_time = time.time()
try:
LOG.info("Running migrate middleware")
# Figure out what version of our app is now deployed
            app_version, created = AppVersion.objects.get_or_create(version=os.getenv('GAE_VERSION', FAKE_VERSION_TESTING))
if not app_version.migrations_succeeded or created:
                # Previous attempt at this deployed version failed, or this was a new deployment.
try:
call_command('migrate')
except:
return HttpResponse("Running a Django migration failed! Investigate.", status=500)
app_version.migrations_succeeded = True
app_version.save()
finally:
LOG.info("Took: %ss", time.time() - start_time)
return self.get_response(request)


It seems to work just fine in a quick test.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bdfd6393-6d68-4285-b5a6-eb1be98ef467%40googlegroups.com.

No comments:

Post a Comment