本文整理汇总了Python中secrets.choice方法的典型用法代码示例。如果您正苦于以下问题:Python secrets.choice方法的具体用法?Python secrets.choice怎么用?Python secrets.choice使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类secrets
的用法示例。
在下文中一共展示了secrets.choice方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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)
示例2: get_result_dict
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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
示例3: accept_duel
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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
示例4: _start_arena
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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
示例5: randstr
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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
示例6: mutate
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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')
示例7: handler
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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))
示例8: handler
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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))
示例9: get_headers
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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
示例10: write_records
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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)
示例11: server_instance
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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)
示例12: bot_move
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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
示例13: pick_item_in_rarity
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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
示例14: generate_embed
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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
示例15: keyvis
# 需要导入模块: import secrets [as 别名]
# 或者: from secrets import choice [as 别名]
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)