• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.generate_random_token函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中zerver.lib.utils.generate_random_token函数的典型用法代码示例。如果您正苦于以下问题:Python generate_random_token函数的具体用法?Python generate_random_token怎么用?Python generate_random_token使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了generate_random_token函数的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: generate_secrets

def generate_secrets(development=False):
    # type: (bool) -> None
    if development:
        OUTPUT_SETTINGS_FILENAME = "zproject/dev-secrets.conf"
    else:
        OUTPUT_SETTINGS_FILENAME = "/etc/zulip/zulip-secrets.conf"

    lines = [u'[secrets]\n']

    def config_line(var, value):
        # type: (text_type, text_type) -> text_type
        return "%s = %s\n" % (var, value)

    old_conf = get_old_conf(OUTPUT_SETTINGS_FILENAME)
    for name in AUTOGENERATED_SETTINGS:
        lines.append(config_line(name, old_conf.get(name, generate_random_token(64))))

    secret_key = old_conf.get('secret_key', generate_django_secretkey())
    lines.append(config_line('secret_key', secret_key))

    camo_key = old_conf.get('camo_key', get_random_string(64))
    lines.append(config_line('camo_key', camo_key))

    if not development:
        # Write the Camo config file directly
        generate_camo_config_file(camo_key)

    out = open(OUTPUT_SETTINGS_FILENAME, 'w')
    out.write(force_str("".join(lines)))
    out.close()

    print("Generated %s with auto-generated secrets!" % (OUTPUT_SETTINGS_FILENAME,))
开发者ID:HKingz,项目名称:zulip,代码行数:32,代码来源:generate_secrets.py


示例2: generate_secrets

def generate_secrets(development=False):
    if development:
        OUTPUT_SETTINGS_FILENAME = "zproject/dev-secrets.conf"
    else:
        OUTPUT_SETTINGS_FILENAME = "/etc/zulip/zulip-secrets.conf"

    lines = ["[secrets]\n"]

    def config_line(var, value):
        return "%s = %s\n" % (var, value)

    for name in AUTOGENERATED_SETTINGS:
        lines.append(config_line(name, generate_random_token(64)))

    lines.append(config_line("secret_key", generate_django_secretkey()))
    camo_key = get_random_string(64)
    lines.append(config_line("camo_key", camo_key))
    if not development:
        # Write the Camo config file directly
        generate_camo_config_file(camo_key)

    out = open(OUTPUT_SETTINGS_FILENAME, "w")
    out.write("".join(lines))
    out.close()

    print("Generated %s with auto-generated secrets!" % (OUTPUT_SETTINGS_FILENAME,))
开发者ID:jakeprem,项目名称:zulip,代码行数:26,代码来源:generate_secrets.py


示例3: create_missed_message_address

def create_missed_message_address(user_profile: UserProfile, message: Message) -> str:
    if settings.EMAIL_GATEWAY_PATTERN == '':
        logger.warning("EMAIL_GATEWAY_PATTERN is an empty string, using "
                       "NOREPLY_EMAIL_ADDRESS in the 'from' field.")
        return FromAddress.NOREPLY

    if message.recipient.type == Recipient.PERSONAL:
        # We need to reply to the sender so look up their personal recipient_id
        recipient_id = get_personal_recipient(message.sender_id).id
    else:
        recipient_id = message.recipient_id

    data = {
        'user_profile_id': user_profile.id,
        'recipient_id': recipient_id,
        'subject': message.topic_name().encode('utf-8'),
    }

    while True:
        token = generate_random_token(32)
        key = missed_message_redis_key(token)
        if redis_client.hsetnx(key, 'uses_left', 1):
            break

    with redis_client.pipeline() as pipeline:
        pipeline.hmset(key, data)
        pipeline.expire(key, 60 * 60 * 24 * 5)
        pipeline.execute()

    address = 'mm' + token
    return settings.EMAIL_GATEWAY_PATTERN % (address,)
开发者ID:deltay,项目名称:zulip,代码行数:31,代码来源:email_mirror.py


示例4: create_missed_message_address

def create_missed_message_address(user_profile, message):
    # type: (UserProfile, Message) -> text_type
    if message.recipient.type == Recipient.PERSONAL:
        # We need to reply to the sender so look up their personal recipient_id
        recipient_id = get_recipient(Recipient.PERSONAL, message.sender_id).id
    else:
        recipient_id = message.recipient_id

    data = {
        'user_profile_id': user_profile.id,
        'recipient_id': recipient_id,
        'subject': message.subject,
    }

    while True:
        token = generate_random_token(32)
        key = missed_message_redis_key(token)
        if redis_client.hsetnx(key, 'uses_left', 1):
            break

    with redis_client.pipeline() as pipeline:
        pipeline.hmset(key, data)
        pipeline.expire(key, 60 * 60 * 24 * 5)
        pipeline.execute()

    address = u'mm' + token
    return settings.EMAIL_GATEWAY_PATTERN % (address,)
开发者ID:150vb,项目名称:zulip,代码行数:27,代码来源:email_mirror.py


示例5: create_missed_message_address

def create_missed_message_address(user_profile, message):
    # type: (UserProfile, Message) -> text_type
    if settings.EMAIL_GATEWAY_PATTERN == "":
        logging.warning("EMAIL_GATEWAY_PATTERN is an empty string, using " "NOREPLY_EMAIL_ADDRESS in the 'from' field.")
        return settings.NOREPLY_EMAIL_ADDRESS

    if message.recipient.type == Recipient.PERSONAL:
        # We need to reply to the sender so look up their personal recipient_id
        recipient_id = get_recipient(Recipient.PERSONAL, message.sender_id).id
    else:
        recipient_id = message.recipient_id

    data = {"user_profile_id": user_profile.id, "recipient_id": recipient_id, "subject": message.subject}

    while True:
        token = generate_random_token(32)
        key = missed_message_redis_key(token)
        if redis_client.hsetnx(key, "uses_left", 1):
            break

    with redis_client.pipeline() as pipeline:
        pipeline.hmset(key, data)
        pipeline.expire(key, 60 * 60 * 24 * 5)
        pipeline.execute()

    address = u"mm" + token
    return settings.EMAIL_GATEWAY_PATTERN % (address,)
开发者ID:rlugojr,项目名称:zulip,代码行数:27,代码来源:email_mirror.py


示例6: generate_secrets

def generate_secrets(development=False):
    # type: (bool) -> None
    if development:
        OUTPUT_SETTINGS_FILENAME = "zproject/dev-secrets.conf"
    else:
        OUTPUT_SETTINGS_FILENAME = "/etc/zulip/zulip-secrets.conf"
    current_conf = get_old_conf(OUTPUT_SETTINGS_FILENAME)

    lines = []  # type: List[Text]
    if len(current_conf) == 0:
        lines = [u'[secrets]\n']

    def need_secret(name):
        # type: (str) -> bool
        return name not in current_conf

    def add_secret(name, value):
        # type: (str, Text) -> None
        lines.append("%s = %s\n" % (name, value))
        current_conf[name] = value

    for name in AUTOGENERATED_SETTINGS:
        if need_secret(name):
            add_secret(name, generate_random_token(64))

    if need_secret('secret_key'):
        add_secret('secret_key', generate_django_secretkey())

    if need_secret('camo_key'):
        add_secret('camo_key', get_random_string(64))

    # zulip_org_key is generated using os.urandom().
    # zulip_org_id does not require a secure CPRNG,
    # it only needs to be unique.
    if need_secret('zulip_org_key'):
        add_secret('zulip_org_key', get_random_string(64))
    if need_secret('zulip_org_id'):
        add_secret('zulip_org_id', str(uuid.uuid4()))

    if not development:
        # Write the Camo config file directly
        generate_camo_config_file(current_conf['camo_key'])

    if len(lines) == 0:
        print("generate_secrets: No new secrets to generate.")
        return

    out = open(OUTPUT_SETTINGS_FILENAME, 'a')
    # Write a newline at the start, in case there was no newline at
    # the end of the file due to human editing.
    out.write("\n" + force_str("".join(lines)))
    out.close()

    print("Generated new secrets in %s." % (OUTPUT_SETTINGS_FILENAME,))
开发者ID:joydeep1701,项目名称:zulip,代码行数:54,代码来源:generate_secrets.py


示例7: handle

    def handle(self, *args: Any, **options: Any) -> None:
        realm = self.get_realm(options)
        assert realm is not None  # Should be ensured by parser

        output_dir = options["output_dir"]
        if output_dir is None:
            output_dir = tempfile.mkdtemp(prefix="zulip-export-")
        else:
            output_dir = os.path.realpath(os.path.expanduser(output_dir))
        if os.path.exists(output_dir):
            shutil.rmtree(output_dir)
        os.makedirs(output_dir)
        print("Exporting realm %s" % (realm.string_id,))
        num_threads = int(options['threads'])
        if num_threads < 1:
            raise CommandError('You must have at least one thread.')

        do_export_realm(realm, output_dir, threads=num_threads, public_only=options["public_only"])
        print("Finished exporting to %s; tarring" % (output_dir,))

        do_write_stats_file_for_realm_export(output_dir)

        tarball_path = output_dir.rstrip('/') + '.tar.gz'
        os.chdir(os.path.dirname(output_dir))
        subprocess.check_call(["tar", "-czf", tarball_path, os.path.basename(output_dir)])
        print("Tarball written to %s" % (tarball_path,))

        if not options["upload_to_s3"]:
            return

        def percent_callback(complete: Any, total: Any) -> None:
            sys.stdout.write('.')
            sys.stdout.flush()

        if settings.LOCAL_UPLOADS_DIR is not None:
            raise CommandError("S3 backend must be configured to upload to S3")

        print("Uploading export tarball to S3")

        from zerver.lib.upload import S3Connection, get_bucket, Key
        conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY)
        # We use the avatar bucket, because it's world-readable.
        bucket = get_bucket(conn, settings.S3_AVATAR_BUCKET)
        key = Key(bucket)
        key.key = os.path.join("exports", generate_random_token(32), os.path.basename(tarball_path))
        key.set_contents_from_filename(tarball_path, cb=percent_callback, num_cb=40)

        public_url = 'https://{bucket}.{host}/{key}'.format(
            host=conn.server_name(),
            bucket=bucket.name,
            key=key.key)
        print("Uploaded to %s" % (public_url,))
开发者ID:BakerWang,项目名称:zulip,代码行数:52,代码来源:export.py


示例8: __init__

 def __init__(self, user, tokens, alert=None, badge=None, sound=None,
         category=None, **kwargs):
     self.frame = Frame()
     self.tokens = tokens
     expiry = time.time() + 24 * 3600
     priority = 10
     payload = Payload(alert=alert, badge=badge, sound=sound,
                       category=category, custom=kwargs)
     for token in tokens:
         data = {'token': token, 'user': user}
         identifier = generate_random_token(32)
         key = get_apns_key(identifier)
         redis_client.hmset(key, data)
         redis_client.expire(key, expiry)
         self.frame.add_item(token, payload, identifier, expiry, priority)
开发者ID:150vb,项目名称:zulip,代码行数:15,代码来源:push_notifications.py


示例9: generate_email_token_for_stream

def generate_email_token_for_stream():
    return generate_random_token(32)
开发者ID:handelxh,项目名称:zulip,代码行数:2,代码来源:models.py


示例10: generate_client_id

def generate_client_id():
    # type: () -> Text
    return generate_random_token(32)
开发者ID:dawran6,项目名称:zulip,代码行数:3,代码来源:users.py


示例11: sign_string

def sign_string(string: str) -> Tuple[str, str]:
    salt = generate_random_token(64)
    signer = Signer(salt=salt)
    return signer.sign(string), salt
开发者ID:jdherg,项目名称:zulip,代码行数:4,代码来源:stripe.py


示例12: generate_key

def generate_key():
    # type: () -> text_type
    return generate_random_token(40)
开发者ID:TijeeCorp,项目名称:zulip,代码行数:3,代码来源:models.py


示例13: home_real


#.........这里部分代码省略.........
        password_min_guesses  = settings.PASSWORD_MIN_GUESSES,
        jitsi_server_url      = settings.JITSI_SERVER_URL,
        search_pills_enabled  = settings.SEARCH_PILLS_ENABLED,

        # Misc. extra data.
        have_initial_messages = user_has_messages,
        initial_servertime    = time.time(),  # Used for calculating relative presence age
        default_language_name = get_language_name(register_ret['default_language']),
        language_list_dbl_col = get_language_list_for_templates(register_ret['default_language']),
        language_list         = get_language_list(),
        needs_tutorial        = needs_tutorial,
        first_in_realm        = first_in_realm,
        prompt_for_invites    = prompt_for_invites,
        furthest_read_time    = sent_time_in_epoch_seconds(latest_read),
        has_mobile_devices    = num_push_devices_for_user(user_profile) > 0,
        bot_types             = get_bot_types(user_profile),
        two_fa_enabled        = two_fa_enabled,
        # Adding two_fa_enabled as condition saves us 3 queries when
        # 2FA is not enabled.
        two_fa_enabled_user   = two_fa_enabled and bool(default_device(user_profile)),
    )

    undesired_register_ret_fields = [
        'streams',
    ]
    for field_name in set(register_ret.keys()) - set(undesired_register_ret_fields):
        page_params[field_name] = register_ret[field_name]

    if narrow_stream is not None:
        # In narrow_stream context, initial pointer is just latest message
        recipient = get_stream_recipient(narrow_stream.id)
        try:
            initial_pointer = Message.objects.filter(recipient=recipient).order_by('id').reverse()[0].id
        except IndexError:
            initial_pointer = -1
        page_params["narrow_stream"] = narrow_stream.name
        if narrow_topic is not None:
            page_params["narrow_topic"] = narrow_topic
        page_params["narrow"] = [dict(operator=term[0], operand=term[1]) for term in narrow]
        page_params["max_message_id"] = initial_pointer
        page_params["pointer"] = initial_pointer
        page_params["have_initial_messages"] = (initial_pointer != -1)
        page_params["enable_desktop_notifications"] = False

    statsd.incr('views.home')
    show_invites = True

    # Some realms only allow admins to invite users
    if user_profile.realm.invite_by_admins_only and not user_profile.is_realm_admin:
        show_invites = False
    if user_profile.is_guest:
        show_invites = False

    show_billing = False
    show_plans = False
    if settings.CORPORATE_ENABLED:
        from corporate.models import Customer
        if user_profile.is_billing_admin or user_profile.is_realm_admin:
            customer = Customer.objects.filter(realm=user_profile.realm).first()
            if customer is not None and customer.has_billing_relationship:
                show_billing = True
        if user_profile.realm.plan_type == Realm.LIMITED:
            show_plans = True

    request._log_data['extra'] = "[%s]" % (register_ret["queue_id"],)

    page_params['translation_data'] = {}
    if request_language != 'en':
        page_params['translation_data'] = get_language_translation_data(request_language)

    csp_nonce = generate_random_token(48)
    emojiset = user_profile.emojiset
    if emojiset == UserProfile.TEXT_EMOJISET:
        # If current emojiset is `TEXT_EMOJISET`, then fallback to
        # GOOGLE_EMOJISET for picking which spritesheet's CSS to
        # include (and thus how to display emojis in the emoji picker
        # and composebox typeahead).
        emojiset = UserProfile.GOOGLE_BLOB_EMOJISET
    response = render(request, 'zerver/app/index.html',
                      context={'user_profile': user_profile,
                               'emojiset': emojiset,
                               'page_params': JSONEncoderForHTML().encode(page_params),
                               'csp_nonce': csp_nonce,
                               'avatar_url': avatar_url(user_profile),
                               'show_debug':
                               settings.DEBUG and ('show_debug' in request.GET),
                               'pipeline': settings.PIPELINE_ENABLED,
                               'search_pills_enabled': settings.SEARCH_PILLS_ENABLED,
                               'show_invites': show_invites,
                               'show_billing': show_billing,
                               'show_plans': show_plans,
                               'is_admin': user_profile.is_realm_admin,
                               'is_guest': user_profile.is_guest,
                               'show_webathena': user_profile.realm.webathena_enabled,
                               'enable_feedback': settings.ENABLE_FEEDBACK,
                               'embedded': narrow_stream is not None,
                               'invite_as': PreregistrationUser.INVITE_AS,
                               },)
    patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
    return response
开发者ID:akashnimare,项目名称:zulip,代码行数:101,代码来源:home.py


示例14: generate_client_id

def generate_client_id() -> str:
    return generate_random_token(32)
开发者ID:joydeep1701,项目名称:zulip,代码行数:2,代码来源:users.py



注:本文中的zerver.lib.utils.generate_random_token函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.get_subdomain函数代码示例发布时间:2022-05-26
下一篇:
Python utils.check_subdomain函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap