createfakecategories.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import random
  2. import time
  3. from faker import Factory
  4. from django.core.management.base import BaseCommand
  5. from misago.acl import version as acl_version
  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. message = '\n\nSuccessfully created %s fake categories in %s'
  35. created_count = 0
  36. start_time = time.time()
  37. show_progress(self, created_count, items_to_create)
  38. while created_count < items_to_create:
  39. parent = random.choice(categories)
  40. new_category = Category()
  41. if random.randint(1, 100) > 75:
  42. new_category.set_name(fake.catch_phrase().title())
  43. else:
  44. new_category.set_name(fake.street_name())
  45. if random.randint(1, 100) > 50:
  46. if random.randint(1, 100) > 80:
  47. new_category.description = '\r\n'.join(fake.paragraphs())
  48. else:
  49. new_category.description = fake.paragraph()
  50. new_category.insert_at(
  51. parent,
  52. position='last-child',
  53. save=True,
  54. )
  55. copied_acls = []
  56. for acl in copy_acl_from.category_role_set.all():
  57. copied_acls.append(
  58. RoleCategoryACL(
  59. role_id=acl.role_id,
  60. category=new_category,
  61. category_role_id=acl.category_role_id,
  62. )
  63. )
  64. if copied_acls:
  65. RoleCategoryACL.objects.bulk_create(copied_acls)
  66. created_count += 1
  67. show_progress(self, created_count, items_to_create, start_time)
  68. acl_version.invalidate()
  69. total_time = time.time() - start_time
  70. total_humanized = time.strftime('%H:%M:%S', time.gmtime(total_time))
  71. self.stdout.write(message % (created_count, total_humanized))