0129_fix_script_paths.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from django.conf import settings
  2. from django.core.files.storage import storages
  3. from django.db import migrations
  4. from urllib.parse import urlparse
  5. from extras.storage import ScriptFileSystemStorage
  6. def normalize(url):
  7. parsed_url = urlparse(url)
  8. if not parsed_url.path.endswith('/'):
  9. return url + '/'
  10. return url
  11. def fix_script_paths(apps, schema_editor):
  12. """
  13. Fix script paths for scripts that had incorrect path from NB 4.3.
  14. """
  15. storage = storages.create_storage(storages.backends["scripts"])
  16. if not isinstance(storage, ScriptFileSystemStorage):
  17. return
  18. ScriptModule = apps.get_model('extras', 'ScriptModule')
  19. script_root_path = normalize(settings.SCRIPTS_ROOT)
  20. for script in ScriptModule.objects.filter(file_path__startswith=script_root_path):
  21. script.file_path = script.file_path[len(script_root_path):]
  22. script.save()
  23. class Migration(migrations.Migration):
  24. dependencies = [
  25. ('extras', '0128_tableconfig'),
  26. ]
  27. operations = [
  28. migrations.RunPython(code=fix_script_paths, reverse_code=migrations.RunPython.noop),
  29. ]
  30. def oc_fix_script_paths(objectchange, reverting):
  31. script_root_path = normalize(settings.SCRIPTS_ROOT)
  32. for data in (objectchange.prechange_data, objectchange.postchange_data):
  33. if data is None:
  34. continue
  35. if file_path := data.get('file_path'):
  36. if file_path.startswith(script_root_path):
  37. data['file_path'] = file_path[len(script_root_path):]
  38. objectchange_migrators = {
  39. 'extras.scriptmodule': oc_fix_script_paths,
  40. }