本文整理汇总了Python中hashids.Hashids方法的典型用法代码示例。如果您正苦于以下问题:Python hashids.Hashids方法的具体用法?Python hashids.Hashids怎么用?Python hashids.Hashids使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hashids
的用法示例。
在下文中一共展示了hashids.Hashids方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_hashids
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def generate_hashids(apps, schema_editor):
AccessRequest = apps.get_model("secrets", "AccessRequest")
Secret = apps.get_model("secrets", "Secret")
SecretRevision = apps.get_model("secrets", "SecretRevision")
for model_class, hashid_namespace in (
(AccessRequest, "AccessRequest"),
(Secret, "Secret"),
(SecretRevision, "SecretRevision"),
):
for obj in model_class.objects.all():
if not obj.hashid:
# We cannot use the same salt for every model because
# 1. sequentially create lots of secrets
# 2. note the hashid of each secrets
# 3. you can now enumerate access requests by using the same
# hashids
# it's not a huge deal, but let's avoid it anyway
hasher = Hashids(
min_length=settings.HASHID_MIN_LENGTH,
salt=hashid_namespace + settings.HASHID_SALT,
)
obj.hashid = hasher.encode(obj.pk)
obj.save()
示例2: save
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def save(self, *args, **kwargs):
if not self.pk:
# need to save once to get a primary key, then once again to
# save the hashid
super(HashIDModel, self).save(*args, **kwargs)
if not self.hashid:
# We cannot use the same salt for every model because
# 1. sequentially create lots of secrets
# 2. note the hashid of each secrets
# 3. you can now enumerate access requests by using the same
# hashids
# it's not a huge deal, but let's avoid it anyway
hasher = Hashids(
min_length=settings.HASHID_MIN_LENGTH,
salt=self.HASHID_NAMESPACE + settings.HASHID_SALT,
)
self.hashid = hasher.encode(self.pk)
# we cannot force insert anymore because we might already have
# created the object
kwargs['force_insert'] = False
return super(HashIDModel, self).save(*args, **kwargs)
示例3: with_cache
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def with_cache():
from hashid_field.hashid import Hashid
from hashids import Hashids
hashids = Hashids(salt="asdf", min_length=7)
instances = [Hashid(i, hashids=hashids) for i in range(1, 10_000)]
return instances
示例4: no_cache
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def no_cache():
setup = dedent('''
from hashid_field.hashid import Hashid
''')
stmt = dedent('''
Hashid(123, salt="asdf", min_length=7)
''')
timer = Timer(stmt, setup)
time = timer.timeit(10_000)
print("No pre-generated Hashids instance: {}".format(time))
示例5: with_cache
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def with_cache():
setup = dedent('''
from hashid_field.hashid import Hashid
from hashids import Hashids
hashids=Hashids(salt="asdf", min_length=7)
''')
stmt = dedent('''
Hashid(123, hashids=hashids)
''')
timer = Timer(stmt, setup)
time = timer.timeit(10_000)
print("With pre-generated Hashids instance: {}".format(time))
示例6: generate_hash
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def generate_hash(redis_connection, redis_namespace=':short', hash_salt=''):
"""
Generates an URL hash.
This will increase the hash counter for the current day no mater if the hash
will be used or not.
"""
days_since_epoch = int(time.time() / 86400)
day_index = redis_connection.incr(redis_namespace + 'HI:' + str(days_since_epoch))
hashids = Hashids(salt=hash_salt)
return hashids.encode(days_since_epoch, day_index)
示例7: handler
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def handler(raw_event, context):
print(raw_event)
event = EVENT_PARSER(raw_event)
if event.s3:
for s3 in event.records:
# s3의 tar.gz 파일에서 수목,좌표 csv 객체 압축 해제
tree_csv, point_csv = get_tar(s3)
points = get_point_data(point_csv)
# 람다의 tmp폴더 혼용에 의한 오류방지를 위해 해시id 생성
dt = datetime.utcnow()
hashid = Hashids(s3.object_key).encode(dt.year, dt.month, dt.day)
shp = make_shp(tree_csv, points, hashid)
f = NamedTemporaryFile(delete=False)
tmp_file = f"{hashid}.tar.gz"
file_name = f"shp/{tmp_file}"
root, dirs, files = list(os.walk(os.path.dirname(shp)))[0]
shp_exts = ['prj', 'shp', 'shx', 'dbf', 'cpg']
# 해시파일중 shp 관련 파일로 필터링
files = [f for f in files if f.split('.')[0] == hashid and f.split('.')[-1] in shp_exts]
with tarfile.open(f.name, mode='w:gz') as gz:
for name in files:
file_path = os.path.join(root, name)
gz.add(file_path, arcname=name)
metadata = s3.object.get()["Metadata"]
metadata = {f"origin_{key}": value for key, value in zip(metadata.keys(), metadata.values())}
metadata['upload_by'] = 'csv2shp'
metadata['origin_data_bucket'] = s3.bucket_arn
metadata['origin_data_key'] = s3.object_key
s3_resource = boto3.resource('s3')
with open(f.name, 'rb') as result:
s3_resource.Object(s3.bucket_name, file_name).put(Body=result.read(), ContentEncoding="gzip",
Metadata=metadata)
示例8: gen_hash
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def gen_hash(registered_user):
"""Generates a time dependent hash.
Accepts an instance of user account and returns
a reversible 'time-unique' hash for it.
Args:
registered_user: A user instance.
Returns:
A hash composed of a time-stamp hash and a
pk-hash delimited by x.
"""
# get a timestamp (to make each generated hash unique):
timestamp = int(time() * 1000)
# encode the timestamp with secret_key:
hashids = Hashids(
salt=UserHasher.secret_key,
min_length=UserHasher.timehash_min_length,
alphabet=UserHasher.alphabet
)
timestamp_hash = hashids.encode(timestamp)
# encode the user's pk with timestamp:
hashids = Hashids(
salt=str(timestamp),
min_length=UserHasher.pkhash_min_length,
alphabet=UserHasher.alphabet
)
pk_hash = hashids.encode(registered_user.pk)
# return the combination delimited by UserHasher.delim:
return "%s%s%s" % (timestamp_hash, UserHasher.delim, pk_hash)
示例9: createHash
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def createHash(identificator):
hashids = Hashids(salt="esh2YTBZesh2YTBZ", min_length=5)
return hashids.encrypt(identificator)
示例10: token_retrieve
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def token_retrieve(request):
token = None
if 'X_TOKEN' in request.META:
token = request.META['X_TOKEN']
elif 'HTTP_X_TOKEN' in request.META:
token = request.META['HTTP_X_TOKEN']
if token is not None:
if len(token) == 20:
token = UUID(hexlify(b85decode(token.encode())).decode())
if len(token) == 25:
hasher = Hasher(salt=settings.SECRET_KEY)
token = UUID(hasher.decode(token))
try:
token = Token.objects.get(id=token, is_active=True, is_anonymous=False)
request.user = token.owner
if token.due is not None and token.due < timezone.now():
token.is_active = False
token.save()
token = None
except Exception:
token = None
return token
示例11: __retrieve__
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def __retrieve__(self, request):
token, user = None, None
if 'HTTP_X_MODIFIED_BY' in request.META:
user = request.META['HTTP_X_MODIFIED_BY']
if 'HTTP_X_TOKEN' in request.META:
token = request.META['HTTP_X_TOKEN']
else:
return token
if len(token) == 25:
hasher = Hasher(salt=settings.SECRET_KEY)
token = UUID(hasher.decode(token))
token = Token.objects.filter(id=token, is_active=True, is_anonymous=False)
if token:
token = token[0]
request.user = token.owner
user = User.objects.filter(id=user)
if token.has_perm('core.propagate_token') and user:
request.user = user[0]
if token.due and token.due < timezone.now():
token.is_active = False
token.save()
token = None
else:
token = None
return token
示例12: get_hashid
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def get_hashid(self):
hashids = Hashids(min_length=5)
return hashids.encode(self.id)
示例13: int_to_hashid
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def int_to_hashid(i, min_length=30, salt=settings.DJANGOCMS_FORMS_HASHIDS_SALT):
hashids = Hashids(salt, min_length=min_length)
return hashids.encode(i)
示例14: hashid_to_int
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def hashid_to_int(hashid, min_length=30, salt=settings.DJANGOCMS_FORMS_HASHIDS_SALT):
hashids = Hashids(salt, min_length=min_length)
try:
return hashids.decode(hashid)[0]
except IndexError:
pass
示例15: get_hashids
# 需要导入模块: import hashids [as 别名]
# 或者: from hashids import Hashids [as 别名]
def get_hashids():
return Hashids(
salt=settings.SECRET_KEY, min_length=4, alphabet="abcdefghijklmnopqrstuvwxyz"
)