[extensions-web] Allow to quickly generate Extensions and Reviews.



commit d25587824226878366545741e4dd89ab55269673
Author: Oscar Domingo <oscardomingo gmail com>
Date:   Thu Jul 4 23:31:23 2019 +0100

    Allow to quickly generate Extensions and Reviews.
    
    If you are starting development from an empty database it
    can be cumbersome to upload extensions manually and or write
    reviews, for this exact reason I created these two cli commands,
    to allow contributors to get set-up faster.
    
    Closes: https://gitlab.gnome.org/Infrastructure/extensions-web/merge_requests/14
    Signed-off-by: Yuri Konotopov <ykonotopov gnome org>

 README.rst                                         |  15 +++
 .../management/commands/populate_extensions.py     |  89 ++++++++++++++++++
 .../management/commands/populate_ratings.py        | 101 +++++++++++++++++++++
 3 files changed, 205 insertions(+)
---
diff --git a/README.rst b/README.rst
index f24d533..d98bc79 100644
--- a/README.rst
+++ b/README.rst
@@ -120,6 +120,21 @@ And to start the webserver:
 
 Log in using superuser account. You should be able to upload and review extensions.
 
+If you want to quickly add extensions and/or reviews to them, there are two functions available, the 
extensions will use boilerplate data:
+::
+  $ python manage.py populate_extensions <number_of_extensions>
+
+This function will create as many (very simple) extensions as you tell it to.
+
+Then to add a given number of random ratings to all the extensions:
+::
+
+  $ python manage.py populate_reviews <number_of_ratings>
+
+This function will create as many ratings into each extension as you tell it to, in this case, the username 
and the rating content gets randomly picked from a "Lorem Ipsum" string.
+
+
+
 .. _virtualenv: http://www.virtualenv.org/
 .. _pip: http://www.pip-installer.org/
 
diff --git a/sweettooth/extensions/management/commands/populate_extensions.py 
b/sweettooth/extensions/management/commands/populate_extensions.py
new file mode 100644
index 0000000..a6a297a
--- /dev/null
+++ b/sweettooth/extensions/management/commands/populate_extensions.py
@@ -0,0 +1,89 @@
+import uuid
+import random
+
+from django.contrib.auth.models import User
+from django.core.management.base import BaseCommand, CommandError
+from django.core.exceptions import ObjectDoesNotExist
+from sweettooth.extensions import models
+from django.contrib.sites.models import Site
+
+
+class Command(BaseCommand):
+    help = 'Populates the database with randomly generated extensions.'
+
+    def add_arguments(self, parser):
+        parser.add_argument('number_of_extensions', nargs=1, type=int)
+        parser.add_argument(
+            '--user',
+            type=str,
+            default=None,
+            help='Specify the User that creates the extension(s).'
+        )
+
+    def _create_extension(self, user=None, verbose=False):
+        """Create an extension using boilerplate data,
+        if a user is provided, attempt to assing it as
+        the author of the extension.
+
+        Args:
+            user (str, optional): Username for the extension author.
+            verbose (bool, optional): Wheter to display extra output.
+
+        Raises:
+            CommandError: This exception is raised when the given 
+                          user does not exist.
+        """
+        current_site = Site.objects.get_current()
+        metadata = {
+            'uuid': str(uuid.uuid4()),
+            'name': 'Test Extension %d' % random.randint(1, 9999),
+            'description': 'Simple test metadata',
+            'url': '%s' % current_site.domain
+        }
+
+        if not user:
+            random_name = 'randomuser%d' % random.randint(1, 9999)
+
+            try:
+                user = models.User.objects.get(username=random_name)
+            except ObjectDoesNotExist:
+                user = User.objects.create_user(
+                    username=random_name,
+                    email='%s@%s' % (random_name, current_site.domain),
+                    password='password'
+                )
+        else:
+            try:
+                user = models.User.objects.get(username=user)
+            except ObjectDoesNotExist:
+                raise CommandError('The specified username (%s) does not exist.' % user)
+
+        extension = models.Extension.objects.create_from_metadata(metadata,
+                                                                  creator=user)
+
+        extension_version = models.ExtensionVersion.objects.create(extension=extension,
+                                                         status=models.STATUS_ACTIVE)
+        if verbose:
+            self.stdout.write('Created extension %s with user %s' % (metadata, user))
+
+    def handle(self, *args, **options):
+        verbose = False
+        if options['verbosity'] >= 2:
+            verbose = True
+
+        number_of_extensions = options['number_of_extensions'][0]
+
+        if verbose:
+            self.stdout.write('Generating %d extensions.' % number_of_extensions)
+
+        if options['number_of_extensions'][0] <= 0:
+            raise CommandError('The number of extensions (%d) provided is not valid.' % number_of_extensions)
+
+        for extension in range(1, number_of_extensions):
+            if options['user']:
+                self._create_extension(user=options['user'], verbose=verbose)
+            else:
+                self._create_extension(verbose=verbose)
+
+        if verbose:
+            self.stdout.write(self.style.SUCCESS('Done!'))
diff --git a/sweettooth/ratings/management/commands/populate_ratings.py 
b/sweettooth/ratings/management/commands/populate_ratings.py
new file mode 100644
index 0000000..41e4577
--- /dev/null
+++ b/sweettooth/ratings/management/commands/populate_ratings.py
@@ -0,0 +1,101 @@
+import random
+import datetime
+
+from django.contrib.auth.models import User
+from django.core.management.base import BaseCommand, CommandError
+from django.core.exceptions import ObjectDoesNotExist
+from django.contrib.contenttypes.models import ContentType
+from django.conf import settings
+from django.contrib.sites.models import Site
+
+from sweettooth.extensions import models
+from sweettooth.ratings.models import RatingComment
+
+
+class Command(BaseCommand):
+    help = 'Populates all the Extensions with a number of randomly generated ratings.'
+
+    def add_arguments(self, parser):
+        parser.add_argument('number_of_ratings', nargs=1, type=int)
+        parser.add_argument(
+            '--user',
+            type=str,
+            default=None,
+            help='Specify the User that creates the rating(s).'
+        )
+
+    def _write_rating(self, user=None, verbose=False):
+        """Post a randomly generated rating into all the
+        extensions. If a user is provided, attempt to post
+        the ratings with it as the author.
+
+        Args:
+            user (str, optional): Username for the ratings author.
+            verbose (bool, optional): Wheter to display extra output.
+
+        Raises:
+            CommandError: This exception is raised when the given 
+                          user does not exist.
+        """
+        lorem_text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco 
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit 
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa 
qui officia deserunt mollit anim id est laborum.'
+        lorem_text_list = (lorem_text.replace(',', '')).split()
+
+        random_name = lorem_text_list[random.randint(0, len(lorem_text_list)-1)]
+        current_site = Site.objects.get_current()
+
+        for extension in models.Extension.objects.all():
+            if not user:
+                try:
+                    user = models.User.objects.get(username=random_name)
+                except ObjectDoesNotExist:
+                    user = User.objects.create_user(
+                        username=random_name,
+                        email='%s@%s' % (random_name, current_site.domain),
+                        password='password'
+                    )
+            else:
+                try:
+                    user = models.User.objects.get(username=user)
+                except ObjectDoesNotExist:
+                    raise CommandError('The specified username (%s) does not exist.' % user)
+
+            rating_text = lorem_text[:random.randint(1, len(lorem_text))]
+
+            comment = RatingComment(
+                user=user,
+                content_type=ContentType.objects.get_for_model(extension),
+                object_pk=extension._get_pk_val(),
+                comment=rating_text,
+                rating=random.randint(-1, 5),
+                submit_date=datetime.datetime.now(),
+                site_id=settings.SITE_ID,
+                is_public=True,
+                is_removed=False,
+            )
+
+            comment.save()
+
+            if verbose:
+                self.stdout.write('\nAdding Rating in Extension:\n%s\n%s\n' % (extension, 
comment.get_as_text()))
+
+    def handle(self, *args, **options):
+        verbose = False
+        if options['verbosity'] >= 2:
+            verbose = True
+
+        number_of_ratings = options['number_of_ratings'][0]
+
+        if verbose:
+            self.stdout.write('Generating %d rating(s) for each Extension.' % number_of_ratings)
+
+        if number_of_ratings <= 0:
+            raise CommandError('The number of ratings (%d) provided is not valid.' % number_of_ratings)
+
+        for ratings in range(0, number_of_ratings):
+            if options['user']:
+                self._write_rating(user=options['user'], verbose=verbose)
+            else:
+                self._write_rating(verbose=verbose)
+
+        if verbose:
+            self.stdout.write(self.style.SUCCESS('Done!'))


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]