createfakecategories.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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', help="number of categories to create", nargs='?', type=int, default=5
  13. )
  14. parser.add_argument(
  15. 'minlevel', help="min. level of created categories", nargs='?', type=int, default=0
  16. )
  17. def handle(self, *args, **options):
  18. items_to_create = options['categories']
  19. min_level = options['minlevel']
  20. categories = Category.objects.all_categories(True)
  21. copy_acl_from = list(Category.objects.all_categories())[0]
  22. categories = categories.filter(level__gte=min_level)
  23. fake = Factory.create()
  24. message = 'Creating %s fake categories...\n'
  25. self.stdout.write(message % items_to_create)
  26. message = '\n\nSuccessfully created %s fake categories in %s'
  27. created_count = 0
  28. start_time = time.time()
  29. show_progress(self, created_count, items_to_create)
  30. while created_count < items_to_create:
  31. parent = random.choice(categories)
  32. new_category = Category()
  33. if random.randint(1, 100) > 75:
  34. new_category.set_name(fake.catch_phrase().title())
  35. else:
  36. new_category.set_name(fake.street_name())
  37. if random.randint(1, 100) > 50:
  38. if random.randint(1, 100) > 80:
  39. new_category.description = '\r\n'.join(fake.paragraphs())
  40. else:
  41. new_category.description = fake.paragraph()
  42. new_category.insert_at(
  43. parent,
  44. position='last-child',
  45. save=True,
  46. )
  47. copied_acls = []
  48. for acl in copy_acl_from.category_role_set.all():
  49. copied_acls.append(
  50. RoleCategoryACL(
  51. role_id=acl.role_id,
  52. category=new_category,
  53. category_role_id=acl.category_role_id,
  54. )
  55. )
  56. if copied_acls:
  57. RoleCategoryACL.objects.bulk_create(copied_acls)
  58. created_count += 1
  59. show_progress(self, created_count, items_to_create, start_time)
  60. acl_version.invalidate()
  61. total_time = time.time() - start_time
  62. total_humanized = time.strftime('%H:%M:%S', time.gmtime(total_time))
  63. self.stdout.write(message % (created_count, total_humanized))