本文整理汇总了Python中django.utils.crypto.get_random_string方法的典型用法代码示例。如果您正苦于以下问题:Python crypto.get_random_string方法的具体用法?Python crypto.get_random_string怎么用?Python crypto.get_random_string使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.crypto
的用法示例。
在下文中一共展示了crypto.get_random_string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def handle(self, **options):
project_name, target = options.pop('name'), options.pop('directory')
self.validate_name(project_name, "project")
# Check that the project_name cannot be imported.
try:
import_module(project_name)
except ImportError:
pass
else:
raise CommandError("%r conflicts with the name of an existing "
"Python module and cannot be used as a "
"project name. Please try another name." %
project_name)
# Create a random SECRET_KEY to put it in the main settings.
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
options['secret_key'] = get_random_string(50, chars)
super(Command, self).handle('project', project_name, target, **options)
示例2: setUp
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def setUp(self):
self.c = Client()
author = RedditUser.objects.create(
user=User.objects.create_user(username="username",
password="password"))
for i in range(50):
Submission.objects.create(score=50 - i,
title=get_random_string(length=20),
author=author).save()
for i in range(1, 50, 10):
# [1, 11, 21] [31, 41] have upvotes (lists demonstrate pages)
Vote.create(user=author,
vote_object=Submission.objects.get(id=i),
vote_value=1).save()
for i in range(2, 50, 15):
# [2, 17] [32, 47] have downvotes (lists demonstrate pages)
Vote.create(user=author,
vote_object=Submission.objects.get(id=i),
vote_value=-1).save()
示例3: grant_sudo_privileges
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def grant_sudo_privileges(request, max_age=COOKIE_AGE):
"""
Assigns a random token to the user's session
that allows them to have elevated permissions
"""
user = getattr(request, "user", None)
# If there's not a user on the request, just noop
if user is None:
return
if not user.is_authenticated():
raise ValueError("User needs to be logged in to be elevated to sudo")
# Token doesn't need to be unique,
# just needs to be unpredictable and match the cookie and the session
token = get_random_string()
request.session[COOKIE_NAME] = token
request._sudo = True
request._sudo_token = token
request._sudo_max_age = max_age
return token
示例4: form_valid
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def form_valid(self, form):
user = User.objects.filter(email=self.request.POST.get('email'))
if user:
user = user[0]
subject = "Password Reset"
password = get_random_string(6)
message = '<p>Your Password for the forum account is <strong>'+password + \
'</strong></p><br/><p>Use this credentials to login into <a href="' + \
settings.HOST_URL + '/forum/">forum</a></p>'
to = user.email
from_email = settings.DEFAULT_FROM_EMAIL
Memail([to], from_email, subject, message, email_template_name=None, context=None)
user.set_password(password)
user.save()
data = {
"error": False, "response": "An Email is sent to the entered email id"}
return JsonResponse(data)
else:
data = {
"error": True, "message": "User With this email id doesn't exists!!!"}
return JsonResponse(data)
示例5: form_valid
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def form_valid(self, form):
user = form.user_cache
activation = user.activation_set.first()
activation.delete()
code = get_random_string(20)
act = Activation()
act.code = code
act.user = user
act.save()
send_activation_email(self.request, user.email, code)
messages.success(self.request, _('A new activation code has been sent to your email address.'))
return redirect('accounts:resend_activation_code')
示例6: get_available_name
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def get_available_name(self, bucket, key, max_length=32, force_name_change=False):
file_root, file_ext = os.path.splitext(key)
while (
force_name_change
or self.key_exists(bucket, key)
or (max_length and len(key) > max_length)
):
force_name_change = False
# file_ext includes the dot.
key = "%s_%s%s" % (file_root, get_random_string(7), file_ext)
if max_length is None:
continue
# Truncate file_root if max_length exceeded.
truncation = len(key) - max_length
if truncation > 0:
file_root = file_root[:-truncation]
# Entire file_root was truncated in attempt to find an available filename.
if not file_root:
raise SuspiciousFileOperation(
'Storage can not find an available filename for "%s". '
"Please make sure that the corresponding file field "
'allows sufficient "max_length".' % key
)
key = "%s_%s%s" % (file_root, get_random_string(7), file_ext)
return key
示例7: get_or_create_user
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def get_or_create_user(self, row, users_list, password_length):
generated_password = None
username, password, email, first_name, last_name = row
if not username and email:
username = email.split('@')[0]
username = find_available_username(username, users_list)
user = User(username=username,
email=email,
first_name=first_name,
last_name=last_name)
cleartext_delimiter = 'cleartext$'
if not password:
password = get_random_string(length=password_length)
user.set_password(password)
generated_password = ([username, password, email])
elif password and password.startswith(cleartext_delimiter):
password = password[len(cleartext_delimiter):]
user.set_password(password)
else:
user.password = password
user.full_clean()
return user, generated_password
示例8: storage
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def storage(request):
# create a random test bucket name
bucket_name = "test_bucket_" + get_random_string(6, string.ascii_lowercase)
storage = DjangoGCloudStorage(
project=request.config.getoption("--gcs-project-name"),
bucket=bucket_name,
credentials_file_path=request.config.getoption("--gcs-credentials-file")
)
# Make sure the bucket exists
bucket = Bucket(storage.client, bucket_name)
bucket.create(
location=request.config.getoption("--gcs-bucket-location")
)
yield storage
storage.bucket.delete_blobs(storage.bucket.list_blobs())
storage.bucket.delete(force=True)
示例9: readable_random_token
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def readable_random_token(alphanumeric=False, add_spaces=False, short_token=False, long_token=False):
"""
Generate a random token that is also reasonably readable.
Generates 4 segments of 4 characters, seperated by dashes. Can either use digits only (default),
or non-confusing letters and digits (alphanumeric=True). If add_spaces is set, spaces are added
around the groups. This is intended to prevent mobile phones that see e.g. "-3" as an emoticon.
If short_token is set, the token is two segments of four characters.
"""
segments = 4
if short_token:
segments = 2
if long_token:
segments = 8
if alphanumeric:
allowed_chars = "BCDFGHJLKMNPQRSTVWXYZ23456789"
else:
allowed_chars = "1234567890"
elements = [get_random_string(length=4, allowed_chars=allowed_chars) for i in range(segments)]
join_str = "-"
if add_spaces:
join_str = " - "
return join_str.join(elements)
示例10: do_node_post
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def do_node_post(self, data):
probe_source_id = int(data["request_id"].split("_")[-1])
probe_source = ProbeSource.objects.get(pk=probe_source_id)
session_id = get_random_string(64)
CarveSession.objects.create(probe_source=probe_source,
machine_serial_number=self.machine_serial_number,
session_id=session_id,
carve_guid=data["carve_id"],
carve_size=int(data["carve_size"]),
block_size=int(data["block_size"]),
block_count=int(data["block_count"]))
post_file_carve_events(self.machine_serial_number, self.user_agent, self.ip,
[{"probe": {"id": probe_source.pk,
"name": probe_source.name},
"action": "start",
"session_id": session_id}])
return {"session_id": session_id}
示例11: get_sync_server_config
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def get_sync_server_config(self):
config = {k: getattr(self, k)
for k in self.SYNC_SERVER_CONFIGURATION_ATTRIBUTES}
# translate client mode
if self.client_mode == self.MONITOR_MODE:
config["client_mode"] = self.PREFLIGHT_MONITOR_MODE
elif self.client_mode == self.LOCKDOWN_MODE:
config["client_mode"] = self.PREFLIGHT_LOCKDOWN_MODE
else:
raise NotImplementedError("Unknown santa client mode: {}".format(self.client_mode))
# provide non matching regexp if the regexp are empty
for attr in ("blacklist_regex",
"whitelist_regex"):
if not config.get(attr):
config[attr] = "NON_MATCHING_PLACEHOLDER_{}".format(get_random_string(8))
return config
示例12: setUpTestData
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def setUpTestData(cls):
push_certificate = PushCertificate.objects.create(
name=get_random_string(64),
topic=get_random_string(256),
not_before=datetime(2000, 1, 1),
not_after=datetime(2050, 1, 1),
certificate=get_random_string(64).encode("utf-8"),
private_key=get_random_string(64).encode("utf-8")
)
cls.meta_business_unit = MetaBusinessUnit.objects.create(name=get_random_string(32))
cls.meta_business_unit.create_enrollment_business_unit()
MetaBusinessUnitPushCertificate.objects.create(
push_certificate=push_certificate,
meta_business_unit=cls.meta_business_unit
)
cls.enrolled_device = EnrolledDevice.objects.create(
push_certificate=push_certificate,
serial_number=get_random_string(64),
udid=get_random_string(36),
token=get_random_string(32).encode("utf-8"),
push_magic=get_random_string(73),
unlock_token=get_random_string(32).encode("utf-8")
)
cls.serial_number = cls.enrolled_device.serial_number
示例13: test_enroll_view
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def test_enroll_view(self):
self.log_user_in()
_, enrollment = self.create_enrollment()
self.log_user_out()
response = self.post_as_json("enroll", {})
self.assertEqual(response.status_code, 400)
machine_serial_number = get_random_string(32)
response = self.post_as_json("enroll", {"secret": "yolo",
"uuid": str(uuid.uuid4()),
"serial_number": machine_serial_number})
self.assertEqual(response.status_code, 400)
response = self.post_as_json("enroll", {"secret": enrollment.secret.secret,
"uuid": str(uuid.uuid4()),
"serial_number": machine_serial_number})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], "application/json")
json_response = response.json()
self.assertCountEqual(["token"], json_response.keys())
token = json_response["token"]
enrolled_machine = EnrolledMachine.objects.get(enrollment=enrollment,
serial_number=machine_serial_number)
self.assertEqual(token, enrolled_machine.token)
示例14: get_valid_name
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def get_valid_name(self, name):
file_root, file_ext = os.path.splitext(name)
return "%s%s" % (get_random_string(RANDOM_FILENAME_LENGTH).lower(), file_ext)
示例15: get_available_name
# 需要导入模块: from django.utils import crypto [as 别名]
# 或者: from django.utils.crypto import get_random_string [as 别名]
def get_available_name(self, name):
dir_name, file_name = os.path.split(name)
file_root, file_ext = os.path.splitext(file_name)
while self.exists(name):
name = os.path.join(dir_name, "%s%s" % (get_random_string(RANDOM_FILENAME_LENGTH).lower(), file_ext))
return name