createfakecategories.py 2.9 KB

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