createfakecategories.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import random
  2. import time
  3. from faker import Factory
  4. from django.core.management.base import BaseCommand
  5. from misago.acl.cache import clear as clear_acl_cache
  6. from misago.categories.models import Category, RoleCategoryACL
  7. from misago.core.management.progressbar import show_progress
  8. class Command(BaseCommand):
  9. help = "Creates fake categories for dev and testing purposes."
  10. def add_arguments(self, parser):
  11. parser.add_argument(
  12. 'categories',
  13. help="number of categories to create",
  14. nargs='?',
  15. type=int,
  16. default=5,
  17. )
  18. parser.add_argument(
  19. 'minlevel',
  20. help="min. level of created categories",
  21. nargs='?',
  22. type=int,
  23. default=0,
  24. )
  25. def handle(self, *args, **options):
  26. items_to_create = options['categories']
  27. min_level = options['minlevel']
  28. categories = Category.objects.all_categories(True)
  29. copy_acl_from = list(Category.objects.all_categories())[0]
  30. categories = categories.filter(level__gte=min_level)
  31. fake = Factory.create()
  32. message = 'Creating %s fake categories...\n'
  33. self.stdout.write(message % items_to_create)
  34. created_count = 0
  35. start_time = time.time()
  36. show_progress(self, created_count, items_to_create)
  37. while created_count < items_to_create:
  38. parent = random.choice(categories)
  39. new_category = Category()
  40. if random.randint(1, 100) > 75:
  41. new_category.set_name(fake.catch_phrase().title())
  42. else:
  43. new_category.set_name(fake.street_name())
  44. if random.randint(1, 100) > 50:
  45. if random.randint(1, 100) > 80:
  46. new_category.description = '\r\n'.join(fake.paragraphs())
  47. else:
  48. new_category.description = fake.paragraph()
  49. new_category.insert_at(
  50. parent,
  51. position='last-child',
  52. save=True,
  53. )
  54. copied_acls = []
  55. for acl in copy_acl_from.category_role_set.all():
  56. copied_acls.append(
  57. RoleCategoryACL(
  58. role_id=acl.role_id,
  59. category=new_category,
  60. category_role_id=acl.category_role_id,
  61. )
  62. )
  63. if copied_acls:
  64. RoleCategoryACL.objects.bulk_create(copied_acls)
  65. created_count += 1
  66. show_progress(self, created_count, items_to_create, start_time)
  67. clear_acl_cache()
  68. total_time = time.time() - start_time
  69. total_humanized = time.strftime('%H:%M:%S', time.gmtime(total_time))
  70. message = '\n\nSuccessfully created %s fake categories in %s'
  71. self.stdout.write(message % (created_count, total_humanized))