createfakecategories.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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(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(RoleCategoryACL(
  57. role_id=acl.role_id,
  58. category=new_category,
  59. category_role_id=acl.category_role_id,
  60. ))
  61. if copied_acls:
  62. RoleCategoryACL.objects.bulk_create(copied_acls)
  63. created_count += 1
  64. show_progress(
  65. self, created_count, items_to_create, start_time)
  66. acl_version.invalidate()
  67. total_time = time.time() - start_time
  68. total_humanized = time.strftime('%H:%M:%S', time.gmtime(total_time))
  69. self.stdout.write(message % (created_count, total_humanized))