コード例 #1
0
    def test_get_paragraph(self):
        """Test :func:`lorem.get_paragraph`."""
        with self.mock_pool:
            with self.mock_randint:
                paragraph = lorem.get_paragraph(count=1)
        self.assertEqual(paragraph, 'Lorem ipsum lorem ipsum. Lorem ipsum lorem ipsum. '
                                    'Lorem ipsum lorem ipsum. Lorem ipsum lorem ipsum. '
                                    'Lorem ipsum lorem ipsum.')

        with self.mock_pool:
            with self.mock_randint:
                paragraph = lorem.get_paragraph(count=(1, 3))
        self.assertEqual(paragraph, 'Lorem ipsum lorem ipsum. Lorem ipsum lorem ipsum. '
                                    'Lorem ipsum lorem ipsum. Lorem ipsum lorem ipsum. '
                                    'Lorem ipsum lorem ipsum.')
コード例 #2
0
def generate_post() -> dict:
    """
    Generate random post
    @return: dict with title, short_description, image,
             full_description, user, posted
    """
    dict_post = {
        'title': '',
        'short_description': '',
        'image': '',
        'full_description': '',
        'user': 1,
        'posted': False
    }
    fake = Faker(['en_US'])
    dict_post['title'] = get_word(count=1)
    dict_post['short_description'] = get_sentence(count=1,
                                                  word_range=(4, 8),
                                                  sep=' ')
    dict_post['image'] = fake.image_url()
    dict_post['full_description'] = get_paragraph(count=3,
                                                  comma=(0, 2),
                                                  word_range=(4, 8),
                                                  sentence_range=(5, 10),
                                                  sep=os.linesep)
    dict_post['user'] = random.randint(1, 2)
    dict_post['posted'] = random.choice([True, False])
    return dict_post
コード例 #3
0
def populate_comments(title_id, review_id, count=5):
    count = random.randint(0, count * 2)
    for i in range(count):
        username = random.choice(_get_users())["username"]
        requests.post(
            URL_RDB + f"/titles/{title_id}/reviews/{review_id}/comments/",
            data={"text": lorem.get_paragraph()},
            auth=(username, os.getenv("USER_PASSWORD")),
        )
コード例 #4
0
def make_tags():
    '''
    Creates a limited # of tags. Roughly 50
    '''
    logger.info('Making tags')
    new_tags = []
    paragraph = lorem.get_paragraph()
    punctuation = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''  # punctuation to check against
    no_punctuation_paragraph = ""
    for char in paragraph:  # loop over every character and if not in punctuation string\
        if char not in punctuation:  # then add it to no punctuation string, includes whitespace!
            no_punctuation_paragraph = \
                no_punctuation_paragraph + char
    words = no_punctuation_paragraph.split(' ')  # split into list of words
    words = set(words)  # make unique
    words = list(words)  # convert back to list
    for i in words:
        new_tags.append(Tag(name=i))
    Tag.objects.bulk_create(new_tags)  # profit
    logger.info('Making tags complete')
コード例 #5
0
def getFakeReview():
    return {
        fnames[0]:
        random.choice(companies),
        fnames[1]:
        str(uuid.uuid4())[:8],
        fnames[2]:
        str(uuid.uuid4())[:8],
        fnames[3]:
        random.choices(seniorities, weights=seniorities_weights, k=1)[0] +
        ' ' + random.choice(job_titles),
        fnames[4]:
        lorem.get_paragraph(count=random.randint(1, 3)),
        fnames[5]:
        max(int(random.gauss(1, 7)), 0),
        fnames[6]:
        max(int(random.gauss(1, 3)), 0),
        fnames[7]:
        max(int(random.gauss(1, 2)), 0),
        fnames[8]:
        max(int(random.gauss(1, 1)), 0),
        fnames[9]:
        random.choices(countryCodes)[0],
    }
コード例 #6
0
def make_posts(post_qty):
    '''
    post_qty: int
    returns: Created model instances
    https://docs.djangoproject.com/en/3.1/ref/models/querysets/#bulk-create
    Using bulk_create. Had to include slug, created and modified to make work.
    bulk_create doesn't call models save method or call pre and post save signals. Duh!
    '''
    logger.info('Making posts')
    new_posts = []  # container for new posts
    for i in range(post_qty):
        title = lorem.get_sentence(1)
        slug = slugify(title)
        num = str(uuid.uuid4().hex)
        unique_slug = f'{slug}-{num}'
        overview = lorem.get_sentence(3)
        created = timezone.now()
        modified = timezone.now()
        content = lorem.get_paragraph(10)
        author = lorem.get_word()
        featured = random.getrandbits(1)
        new_post = Post(title=title,
                        slug=unique_slug,
                        overview=overview,
                        date=created,
                        modified=modified,
                        content=content,
                        author=author,
                        featured=featured)
        new_posts.append(new_post)  # add new posts to container
    Post.objects.bulk_create(new_posts)  # profit
    search_vectors = SearchVector('title', weight='A') + \
                    SearchVector('overview', weight='B') + \
                    SearchVector('content', weight='C')
    Post.objects.update(search_vector=search_vectors)
    logger.info('Making posts complete')
コード例 #7
0
 def handle(self, *args, **options):
     # users
     users = []
     for _ in range(50):
         first_name, last_name = names.get_first_name(
         ), names.get_last_name()
         username = first_name.lower() + "_" + last_name.lower()
         users.append(
             User.objects.create_user(first_name=first_name,
                                      last_name=last_name,
                                      username=username))
     # test user
     try:
         user = User.objects.get(username="******")
         user.first_name = "John"
         user.last_name = "Doe"
         user.save()
     except User.DoesNotExist:
         User.objects.create(username="******",
                             first_name="John",
                             last_name="Doe")
     users.append(User.objects.get(username="******"))
     # follows
     for follower in users:
         for followee in random.sample(users, random.randint(0, 50)):
             Follow.objects.create(follower=follower, followee=followee)
     # groups
     groups = [
         Group.objects.get_or_create(title="Cats",
                                     slug="cats",
                                     description="We like cats.")[0],
         Group.objects.get_or_create(title="Dogs",
                                     slug="dogs",
                                     description="We like dogs.")[0],
         Group.objects.get_or_create(title="Birds",
                                     slug="birds",
                                     description="We like birds.")[0],
         None,
     ]
     # posts
     start_date, end_date = (
         dt.datetime(year=2020, month=10, day=2).timestamp(),
         dt.datetime(year=2020, month=10, day=10).timestamp(),
     )
     for user in users:
         for post in range(random.randint(0, 7)):
             post = Post.objects.create(
                 text=lorem.get_paragraph(
                     count=random.randint(1, 3)).replace(
                         os.linesep, os.linesep + os.linesep),
                 author=user,
                 group=random.choice(groups),
             )
             post.date = dt.datetime.fromtimestamp(
                 random.uniform(start_date, end_date),
                 tz=dt.timezone(dt.timedelta(hours=0)),
             )
             post.save()
     # comments
     for post in Post.objects.all():
         start_date, end_date = (
             post.date.timestamp(),
             dt.datetime(year=2020, month=10, day=10).timestamp(),
         )
         for _ in range(random.randint(0, 10)):
             comment = Comment.objects.create(
                 post=post,
                 author=random.choice(users),
                 text=lorem.get_sentence(count=random.randint(1, 5)),
             )
             comment.date = dt.datetime.fromtimestamp(
                 random.uniform(start_date, end_date),
                 tz=dt.timezone(dt.timedelta(hours=0)),
             )
             comment.save()
コード例 #8
0
    def prepare(
        self,
        file_path: Path = Path(''),
        content_variant: str = '',
        font_family: str = '',
        font_size: str = '',
        font_style: str = '',
        font_weight: str = '',
        text_decoration_line: str = '',
        font_color: str = '',
        background_color: str = '',
        layout: Layout = Layout.center,
        content_source: str = '',
    ):

        style: str = ''
        if len(font_family) > 0: style += 'font-family: ' + font_family + '; '
        if len(font_size) > 0: style += 'font-size: ' + font_size + '; '
        if len(font_style) > 0: style += 'font-style: ' + font_style + '; '
        if len(font_weight) > 0: style += 'font-weight: ' + font_weight + '; '
        if len(text_decoration_line) > 0:
            style += 'text-decoration-line: ' + text_decoration_line + '; '
        if len(font_color) > 0: style += 'color: ' + font_color + '; '
        if len(background_color) > 0:
            style += 'background: ' + background_color + '; '

        if font_color[1:] == background_color[1:]:
            return

        # Generate content
        words: [str] = ['']
        sentences: [str] = ['']
        paragraphs: [str] = ['']
        usernames: [str] = ['']
        background_images: [str] = []

        # Get words, sentences, paragraphs and usernames
        if content_variant != 'images_only':
            if content_source == 'lorem':
                for _ in range(10):
                    words.append(lorem.get_word())
                    sentences.append(lorem.get_sentence())
                    paragraphs.append(lorem.get_paragraph())
                    usernames.append(self.gen_username())

            elif content_source == 'bible':
                for _ in range(10):
                    words.append(random.choice(self.word_list))
                    sentences.append(random.choice(self.bible_list))
                    temp_paragraph = ''
                    for _ in range(random.randint(2, 5)):
                        temp_paragraph += random.choice(self.bible_list) + ' '
                    paragraphs.append(temp_paragraph)
                    usernames.append(self.gen_username())

            elif content_source == 'random':
                for _ in range(10):
                    words.append(self.gen_random_word())
                    sentences.append(self.gen_random_sentence())
                    paragraphs.append(self.gen_random_paragraph())
                    usernames.append(self.gen_username())

            # Remove firsts
            words.pop(0)
            sentences.pop(0)
            paragraphs.pop(0)
            usernames.pop(0)

        else:
            words = ['', '', '', '', '', '', '', '', '', '']
            sentences = ['', '', '', '', '', '', '', '', '', '']
            paragraphs = ['', '', '', '', '', '', '', '', '', '']
            usernames = ['', '', '', '', '', '', '', '', '', '']

        # Get images
        if content_variant == 'with_images' or content_variant == 'images_only':
            background_images = self.get_images()

        # Generate and save document
        self.generate_file(path=file_path,
                           words=words,
                           sentences=sentences,
                           paragraphs=paragraphs,
                           usernames=usernames,
                           background_images=background_images,
                           style=style,
                           layout=layout)
コード例 #9
0
    def fill_title(self, title, url, date):
        self.append(NoEscape(r'\chapter{%s}' % title))
        with self.create(FlushRight()):
            self.append(date)
        with self.create(FlushRight()):
            self.append(url)

    def fill_document(self, data, escape=False):
        if escape:
            self.append(data)
        else:
            self.append(NoEscape(data))
        self.append(NewPage())


doc = MyDocument()
doc.fill_title('sy', 'https://github.com', 'December 2019')
doc.fill_document(l)
doc.fill_title('gk', 'https://github.com/2', 'November 2019')
x = lorem.get_paragraph(count=(10),
                        comma=(0, 2),
                        word_range=(4, 8),
                        sentence_range=(5, 10),
                        sep=os.linesep)
x = x.replace('\n', '\n\n')
doc.fill_document(x)

doc.generate_pdf('test', clean_tex=False)
tex = doc.dumps()  # The document as string in LaTeX syntax