create_jobs.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import sys
  4. import shutil
  5. from django.core.management.base import AppCommand
  6. from django.core.management.color import color_style
  7. from django_extensions.management.utils import _make_writeable, signalcommand
  8. class Command(AppCommand):
  9. help = "Creates a Django jobs command directory structure for the given app name in the current directory."
  10. requires_system_checks = False
  11. # Can't import settings during this command, because they haven't
  12. # necessarily been created.
  13. can_import_settings = True
  14. @signalcommand
  15. def handle_app_config(self, app, **options):
  16. copy_template('jobs_template', app.path, **options)
  17. def copy_template(template_name, copy_to, **options):
  18. """Copy the specified template directory to the copy_to location"""
  19. import django_extensions
  20. style = color_style()
  21. ERROR = getattr(style, 'ERROR', lambda x: x)
  22. SUCCESS = getattr(style, 'SUCCESS', lambda x: x)
  23. template_dir = os.path.join(django_extensions.__path__[0], 'conf', template_name)
  24. verbosity = options["verbosity"]
  25. # walks the template structure and copies it
  26. for d, subdirs, files in os.walk(template_dir):
  27. relative_dir = d[len(template_dir) + 1:]
  28. if relative_dir and not os.path.exists(os.path.join(copy_to, relative_dir)):
  29. os.mkdir(os.path.join(copy_to, relative_dir))
  30. for i, subdir in enumerate(subdirs):
  31. if subdir.startswith('.'):
  32. del subdirs[i]
  33. for f in files:
  34. if f.endswith('.pyc') or f.startswith('.DS_Store'):
  35. continue
  36. path_old = os.path.join(d, f)
  37. path_new = os.path.join(copy_to, relative_dir, f).rstrip(".tmpl")
  38. if os.path.exists(path_new):
  39. if verbosity > 1:
  40. print(ERROR("%s already exists" % path_new))
  41. continue
  42. if verbosity > 1:
  43. print(SUCCESS("%s" % path_new))
  44. with open(path_old, 'r') as fp_orig:
  45. with open(path_new, 'w') as fp_new:
  46. fp_new.write(fp_orig.read())
  47. try:
  48. shutil.copymode(path_old, path_new)
  49. _make_writeable(path_new)
  50. except OSError:
  51. sys.stderr.write("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new)