Yes, I do see several problems. Some of them:

- All middleware are run for every request
- What you're doing can slow down your request response time to minutes, 
depending on home many migrations you have
- Depending on your database, migrations might not be atomic thus causing 
conflicts
- You have no way to intervene when something goes south
- ...

I can elaborate in more detail when you want. But please, don't run migrations 
as part of the request-response cycle.

/Markus

On Sun, Jul 28, 2019, at 3:48 PM, David Grant wrote:
> 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 [email protected].
>  To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/bdfd6393-6d68-4285-b5a6-eb1be98ef467%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/django-users/bdfd6393-6d68-4285-b5a6-eb1be98ef467%40googlegroups.com?utm_medium=email&utm_source=footer>.

-- 
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 [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3d2c95c8-3fe6-4890-8c06-2206ad72c7b0%40www.fastmail.com.

Reply via email to