Python secrets.choice() Examples

The following are 30 code examples of secrets.choice(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module secrets , or try the search function .
Example #1
Source File: account.py    From marsha with MIT License 7 votes vote down vote up
def save(self, *args, **kwargs):
        """Generate the oauth consumer key and shared secret randomly upon creation.

        Parameters
        ----------
        args : list
            Passed onto parent's `save` method
        kwargs: dict
            Passed onto parent's `save` method

        """
        self.full_clean()
        if not self.oauth_consumer_key:
            self.oauth_consumer_key = "".join(
                secrets.choice(OAUTH_CONSUMER_KEY_CHARS)
                for _ in range(OAUTH_CONSUMER_KEY_SIZE)
            )
        if not self.shared_secret:
            self.shared_secret = "".join(
                secrets.choice(SHARED_SECRET_CHARS) for _ in range(SHARED_SECRET_SIZE)
            )
        super().save(*args, **kwargs) 
Example #2
Source File: duel.py    From PythonTwitchBotFramework with MIT License 6 votes vote down vote up
def accept_duel(channel: str, challenger: str, target: str) -> Tuple[Optional[str], Optional[int]]:
    """
    accepts a duel from [target] issued by [challenger]
    returns tuple of (winner, bet) if duel exists and has not expired, else (None, None)

    :param channel: the channel which the challenger / target is in
    :param challenger: the user who initialized a challenge to [target]
    :param target: the user who was challenged
    :return: (winner, bet) if duel exists and has not expired, else (None, None)
    """
    duel = get_duel(channel, challenger, target)
    remove_duel(channel, challenger, target)

    if not duel or duel_expired(duel):
        return None, None

    return choice((challenger, target)), duel.bet 
Example #3
Source File: arena.py    From PythonTwitchBotFramework with MIT License 6 votes vote down vote up
def _start_arena(self):
        if len(self.users) < self.min_users:
            await self.channel.send_message(
                f'not enough users joined the arena to start, everyone that entered was issued a refund')

            for user in self.users:
                add_balance(self.channel.name, user, self.entry_fee)

        else:
            currency = get_currency_name(self.channel.name).name
            winner = choice(tuple(self.users))
            winnings = self.entry_fee * len(self.users)

            add_balance(self.channel.name, winner, winnings)
            await self.channel.send_message(
                choice(VICTORY_MESSAGES).format(winner=winner, winnings=winnings, currency=currency))

            self.users.clear()

        if self.on_arena_ended_func:
            self.on_arena_ended_func(self)

        self.running = False 
Example #4
Source File: models.py    From Django-Poll-App with MIT License 6 votes vote down vote up
def get_result_dict(self):
        res = []
        for choice in self.choice_set.all():
            d = {}
            alert_class = ['primary', 'secondary', 'success',
                           'danger', 'dark', 'warning', 'info']

            d['alert_class'] = secrets.choice(alert_class)
            d['text'] = choice.choice_text
            d['num_votes'] = choice.get_vote_count
            if not self.get_vote_count:
                d['percentage'] = 0
            else:
                d['percentage'] = (choice.get_vote_count /
                                   self.get_vote_count)*100

            res.append(d)
        return res 
Example #5
Source File: random.py    From mimesis with MIT License 6 votes vote down vote up
def randstr(self, unique: bool = False,
                length: Optional[int] = None) -> str:
        """Generate random string value.

        This method can be especially useful when you need to generate
        only unique values in your provider. Just pass parameter unique=True.

        Basically, this method is just a simple wrapper around uuid.uuid4().

        :param unique: Generate only unique values.
        :param length: Length of string. Default range is (min=16, max=128).
        :return: Random string.

        """
        if unique:
            return str(uuid.uuid4().hex)

        if length is None:
            length = self.randint(16, 128)

        _string = string.ascii_letters + string.digits
        _string = ''.join(
            secrets.choice(_string) for _ in range(length)
        )
        return _string 
Example #6
Source File: conftest.py    From hangar-py with Apache License 2.0 6 votes vote down vote up
def server_instance(monkeypatch, managed_tmpdir, worker_id):
    from secrets import choice
    from hangar.remote import server
    monkeypatch.setattr(server, 'server_config', mock_server_config)

    possibble_addresses = [x for x in range(50000, 59999)]
    chosen_address = choice(possibble_addresses)
    address = f'localhost:{chosen_address}'
    base_tmpdir = pjoin(managed_tmpdir, f'{worker_id[-1]}')
    mkdir(base_tmpdir)
    server, hangserver, _ = server.serve(base_tmpdir, overwrite=True, channel_address=address)
    server.start()
    yield address

    hangserver.close()
    server.stop(0.1)
    server.wait_for_termination(timeout=2) 
Example #7
Source File: schema.py    From cms with GNU General Public License v3.0 6 votes vote down vote up
def mutate(self, info, email):
        user = User.objects.get(email=email)
        if user is not None:
            newPassword = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(10))
            user.set_password(newPassword)
            user.save()
            context = {
                "password": newPassword,
                "username": user.username
            }
            message = render_to_string('email/password_reset_email.html', context)
            send_mail('Reset Password | amFOSS CMS', strip_tags(message), from_email, [email], fail_silently=False,
                      html_message=message)
            return userStatusObj(status=True)
        else:
            raise APIException('Email is not registered',
                               code='WRONG_EMAIL') 
Example #8
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 6 votes vote down vote up
def handler(event, context):
    response_code = cfnresponse.SUCCESS
    response_data = {}
    print(event)
    if event['RequestType'] == 'Create':
        phys_id = ''.join(random.choice(alnum) for _ in range(16))
    else:
        phys_id = event['PhysicalResourceId']
    try:
        if event['RequestType'] in ['Create', 'Update']:
            if 'Length' in event['ResourceProperties']:
                pw_len = int(event['ResourceProperties']['Length'])
            else:
                pw_len = 16
            response_data['EMRClusterName'] = generate_password(pw_len)
        cfnresponse.send(event, context, response_code, response_data, phys_id)
    except Exception as e:
        print(str(e))
        traceback.print_exc()
        cfnresponse.send(event, context, cfnresponse.FAILED, response_data, phys_id, str(e)) 
Example #9
Source File: lambda_function.py    From aws-servicebroker with Apache License 2.0 6 votes vote down vote up
def handler(event, context):
    response_code = cfnresponse.SUCCESS
    response_data = {}
    print(event)
    if event['RequestType'] == 'Create':
        phys_id = ''.join(random.choice(alnum) for _ in range(16))
    else:
        phys_id = event['PhysicalResourceId']
    try:
        if event['RequestType'] in ['Create', 'Update']:
            if 'Length' in event['ResourceProperties']:
                pw_len = int(event['ResourceProperties']['Length'])
            else:
                pw_len = 16
            response_data['DBName'] = generate_password(pw_len)
        cfnresponse.send(event, context, response_code, response_data, phys_id)
    except Exception as e:
        print(str(e))
        traceback.print_exc()
        cfnresponse.send(event, context, cfnresponse.FAILED, response_data, phys_id, str(e)) 
Example #10
Source File: XDR_iocs.py    From content with MIT License 6 votes vote down vote up
def get_headers(params: Dict) -> Dict:
    api_key: str = str(params.get('apikey'))
    api_key_id: str = str(params.get('apikey_id'))
    nonce: str = "".join([secrets.choice(string.ascii_letters + string.digits) for _ in range(64)])
    timestamp: str = str(int(datetime.now(timezone.utc).timestamp()) * 1000)
    auth_key = "%s%s%s" % (api_key, nonce, timestamp)
    auth_key = auth_key.encode("utf-8")
    api_key_hash: str = hashlib.sha256(auth_key).hexdigest()

    headers: Dict = {
        "x-xdr-timestamp": timestamp,
        "x-xdr-nonce": nonce,
        "x-xdr-auth-id": str(api_key_id),
        "Authorization": api_key_hash,
        "x-iocs-source": "xsoar"
    }

    return headers 
Example #11
Source File: generate.py    From fbctf-2019-challenges with MIT License 6 votes vote down vote up
def write_records(players, filename):
    # given a list of players, write records
    player_names = set([player[0] for player in players])
    rows = []
    for player in players:
        for i in range(random.randint(4, 14)):
            sender = player[0]
            msg = make_a_msg(sender, secrets.choice(
                list(player_names - set((sender,)))))
            if sender == players[0][0]:  # this is the security flaw
                rows.append(make_signed_message(msg, player, 0))
            else:
                rows.append(make_signed_message(msg, player, i))
    random.shuffle(rows)  # to make it a little less obvious
    with open(filename, 'w') as outfile:
        outcsv = csv.writer(outfile)
        for row in rows:
            outcsv.writerow(row) 
Example #12
Source File: core.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def bot_move(self, last: int):
        """

        :param last:
        :type last:
        :return:
        :rtype:
        """
        choice, bad_col = None, True
        while bad_col:
            move = secrets.randbelow(3)
            if move == 0:
                mod = secrets.choice([-1, 0, 1])
                choice = max(min(6, last + mod), 0)
            else:
                choice = secrets.randbelow(6)
            if not self.column_full(choice):
                bad_col = False
        return choice 
Example #13
Source File: item_core.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def pick_item_in_rarity(self, item_category, rarity):
        """
        Picks a random item within the given rarity.
        :param item_category: The type of the item.
        :type item_category: str
        :param rarity: The rarity to choose from.
        :type rarity: int
        :return:
        :rtype: SigmaRawItem
        """
        in_rarity = []
        for item in self.all_items:
            if item.type.lower() == item_category:
                if item.rarity == rarity:
                    in_rarity.append(item)
        choice = secrets.choice(in_rarity)
        return choice 
Example #14
Source File: safe_core.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def generate_embed(post, titles, color=0xff6699, icon='https://i.imgur.com/WQbzk9y.png'):
    """

    :param post:
    :type post:
    :param titles:
    :type titles:
    :param color:
    :type color:
    :param icon:
    :type icon:
    :return:
    :rtype:
    """
    image_url = post.attrib['file_url']
    image_source = f'http://safebooru.org/index.php?page=post&s=view&id={post.attrib["id"]}'
    if image_url.startswith('//'):
        image_url = 'https:' + image_url
    response = discord.Embed(color=color)
    response.set_author(name=secrets.choice(titles), icon_url=icon, url=image_source)
    response.set_image(url=image_url)
    response.set_footer(
        text=f'Score: {post.attrib["score"]} | Size: {post.attrib["width"]}x{post.attrib["height"]}')
    return response 
Example #15
Source File: keyvis.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def keyvis(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    keys = [key for key in key_vn_list]
    choice = pld.args[0].lower() if pld.args else secrets.choice(keys)
    item = key_vn_list.get(choice)
    if item:
        image_number = secrets.randbelow(item[2]) + item[1]
        url_base = 'https://vncg.org'
        image_url = f'{url_base}/f{image_number}.jpg'
        response = discord.Embed(color=0x744EAA)
        response.set_image(url=image_url)
    else:
        response = not_found('No results.')
    await pld.msg.channel.send(embed=response) 
Example #16
Source File: table_unflipper.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def table_unflipper(ev, pld):
    """
    :param ev: The event object referenced in the event.
    :type ev: sigma.core.mechanics.event.SigmaEvent
    :param pld: The event payload data to process.
    :type pld: sigma.core.mechanics.payload.MessagePayload
    """
    if '(╯°□°)╯︵ ┻━┻'.replace(' ', '') in pld.msg.content.replace(' ', ''):
        if pld.msg.guild:
            unflip = bool(pld.settings.get('unflip'))
        else:
            unflip = True
        if unflip:
            await add_special_stats(ev.db, 'tables_fixed')
            table = ['┬─┬ ノ( ^_^ノ)',
                     '┬─┬ ノ(° -°ノ)',
                     '┬─┬ ノ(゜-゜ノ)',
                     r'┬─┬ ノ(ಠ\_ಠノ)',
                     '┻━┻~~~~  ╯(°□° ╯)',
                     '┻━┻====  ╯(°□° ╯)',
                     r' ┬──┬ ¯\_(ツ)',
                     '(ヘ・_・)ヘ┳━┳',
                     'ヘ(´° □°)ヘ┳━┳']
            table_resp = secrets.choice(table)
            await pld.msg.channel.send(table_resp) 
Example #17
Source File: randomemote.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
def randomemote(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    emotes, nsfw = pld.msg.guild.emojis, False
    if pld.args:
        if pld.args[-1].lower() == '--global':
            emotes, nsfw = await get_emote_cache(cmd), True
    if not nsfw or pld.msg.channel.is_nsfw():
        if emotes:
            emote = secrets.choice(emotes)
            response = discord.Embed().set_image(url=emote.url)
        else:
            response = error('This server has no custom emotes.')
    else:
        response = error('Emotes from other servers can be NSFW.')
        response.description = 'Mark this channel as NSFW or move to one that is.'
    await pld.msg.channel.send(embed=response) 
Example #18
Source File: dns.py    From TrustTrees with Apache License 2.0 6 votes vote down vote up
def _try_to_get_first_ip_for_hostname(hostname):
    """
    :returns: string
    e.g.
        "1.2.3.4" or ""
    """
    try:
        answer = _dns_query(
            hostname,
            query_type='A',
            target_nameserver=secrets.choice(global_state.RESOLVERS),
        )
        if answer.rrset:
            return str(answer.rrset[0])
    except (
        dns.resolver.NoNameservers,
        dns.resolver.NXDOMAIN,
        dns.resolver.Timeout,
        dns.resolver.YXDOMAIN,
    ):
        pass
    return '' 
Example #19
Source File: post_gen_project.py    From wemake-django-template with MIT License 6 votes vote down vote up
def _get_random_string(length=50):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits

    >>> secret = _get_random_string()
    >>> len(secret)
    50

    """
    punctuation = string.punctuation.replace(
        '"', '',
    ).replace(
        "'", '',
    ).replace(
        '\\', '',
    ).replace(
        '$', '',  # see issue-271
    )

    chars = string.digits + string.ascii_letters + punctuation
    return ''.join(secrets.choice(chars) for _ in range(length)) 
Example #20
Source File: routing_table.py    From trinity with MIT License 5 votes vote down vote up
def get_random_entry(self) -> NodeID:
        return secrets.choice(self.entries) 
Example #21
Source File: passwordstore.py    From python-pass with GNU General Public License v3.0 5 votes vote down vote up
def generate_password(
        self,
        path,
        digits=True,
        symbols=True,
        length=25,
        first_line_only=False
    ):
        """Returns and stores a random password

        :param path: Where to insert the password. Ex: 'passwordstore.org'
        :param digits: Should the password have digits? Defaults to True
        :param symbols: Should the password have symbols? Defaults to True
        :param length: Length of the password. Defaults to 25
        :param first_line_only: Modify only the first line of an existing entry
        :returns: Generated password.
        """
        if first_line_only:
            old_content = self.get_decrypted_password(path)
            content_wo_pass = ''.join(old_content.partition('\n')[1:])
        else:
            content_wo_pass = ''

        chars = string.ascii_letters

        if symbols:
            chars += string.punctuation

        if digits:
            chars += string.digits

        password = ''.join(choice(chars) for i in range(length))

        self.insert_password(path, password + content_wo_pass)

        return password 
Example #22
Source File: admin.py    From artifactory with MIT License 5 votes vote down vote up
def _new_function_with_secret_module(pw_len=16):
    import secrets

    return "".join(secrets.choice(string.ascii_letters) for i in range(pw_len)) 
Example #23
Source File: utils.py    From django-userena-ce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_nonce():
    """
    Cryptographically generates a 40 char long nonce.

    :return: String containing the nonce.

    """
    alphabet = ascii_letters + digits
    nonce = "".join(secrets.choice(alphabet) for _ in range(40))

    return nonce 
Example #24
Source File: util.py    From anime-downloader with The Unlicense 5 votes vote down vote up
def search(query, provider, choice=None):
    # Since this function outputs to stdout this should ideally be in
    # cli. But it is used in watch too. :(
    cls = get_anime_class(provider)
    search_results = cls.search(query)
    click.echo(format_search_results(search_results), err=True)

    if not search_results:
        logger.error('No such Anime found. Please ensure correct spelling.')
        sys.exit(1)

    if choice:
        val = choice
    else:
        val = click.prompt('Enter the anime no: ', type=int, default=1, err=True)

    try:
        url = search_results[val-1].url
        title = search_results[val-1].title
    except IndexError:
        logger.error('Only maximum of {} search results are allowed.'
                     ' Please input a number less than {}'.format(
                         len(search_results), len(search_results)+1))
        sys.exit(1)


    logger.info('Selected {}'.format(title))

    return url 
Example #25
Source File: secr_gen.py    From Learning-Path-Learn-Web-Development-with-Python with MIT License 5 votes vote down vote up
def generate_pwd(length=8):
    chars = digits + ascii_letters
    return ''.join(secrets.choice(chars) for c in range(length)) 
Example #26
Source File: models.py    From desec-stack with MIT License 5 votes vote down vote up
def captcha_default_content():
    alphabet = (string.ascii_uppercase + string.digits).translate({ord(c): None for c in 'IO0'})
    content = ''.join([secrets.choice(alphabet) for _ in range(5)])
    metrics.get('desecapi_captcha_content_created').inc()
    return content 
Example #27
Source File: dns.py    From TrustTrees with Apache License 2.0 5 votes vote down vote up
def _get_random_root_ns_set():
    return secrets.choice(ROOT_SERVERS) 
Example #28
Source File: crypto.py    From Zilliqa-Mining-Proxy with GNU General Public License v3.0 5 votes vote down vote up
def rand_string(n_str=8) -> str:
    alphabet = string.ascii_letters + string.digits
    return "".join(secrets.choice(alphabet) for _ in range(n_str)) 
Example #29
Source File: models.py    From Django-Poll-App with MIT License 5 votes vote down vote up
def __str__(self):
        return f'{self.poll.text[:15]} - {self.choice.choice_text[:15]} - {self.user.username}' 
Example #30
Source File: human.py    From lightbus with Apache License 2.0 5 votes vote down vote up
def generate_human_friendly_name():
    return "{}-{}-{}".format(
        secrets.choice(_adjectives), secrets.choice(_nouns), secrets.randbelow(999) + 1
    )