当前位置: 首页>>代码示例>>Python>>正文


Python shortcuts.rand_str函数代码示例

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


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

示例1: handle

 def handle(self, *args, **options):
     try:
         admin = User.objects.get(username="root")
         if admin.admin_type == SUPER_ADMIN:
             self.stdout.write(self.style.WARNING("Super admin user 'root' already exists, "
                                                  "would you like to reset it's password?\n"
                                                  "Input yes to confirm: "))
             if raw_input() == "yes":
                 rand_password = rand_str(length=6)
                 admin.set_password(rand_password)
                 admin.save()
                 self.stdout.write(self.style.SUCCESS("Successfully created super admin user password.\n"
                                                      "Username: root\nPassword: %s\n"
                                                      "Remember to change password and turn on two factors auth "
                                                      "after installation." % rand_password))
             else:
                 self.stdout.write(self.style.SUCCESS("Nothing happened"))
         else:
             self.stdout.write(self.style.ERROR("User 'root' is not super admin."))
     except User.DoesNotExist:
         user = User.objects.create(username="root", real_name="root", email="[email protected]", admin_type=SUPER_ADMIN)
         rand_password = rand_str(length=6)
         user.set_password(rand_password)
         user.save()
         UserProfile.objects.create(user=user)
         self.stdout.write(self.style.SUCCESS("Successfully created super admin user.\n"
                                              "Username: root\nPassword: %s\n"
                                              "Remember to change password and turn on two factors auth "
                                              "after installation." % rand_password))
开发者ID:8cbx,项目名称:OnlineJudge,代码行数:29,代码来源:initadmin.py

示例2: put

    def put(self, request):
        """
        Edit user api
        """
        data = request.data
        try:
            user = User.objects.get(id=data["id"])
        except User.DoesNotExist:
            return self.error("User does not exist")
        if User.objects.filter(username=data["username"].lower()).exclude(id=user.id).exists():
            return self.error("Username already exists")
        if User.objects.filter(email=data["email"].lower()).exclude(id=user.id).exists():
            return self.error("Email already exists")

        pre_username = user.username
        user.username = data["username"].lower()
        user.email = data["email"].lower()
        user.admin_type = data["admin_type"]
        user.is_disabled = data["is_disabled"]

        if data["admin_type"] == AdminType.ADMIN:
            user.problem_permission = data["problem_permission"]
        elif data["admin_type"] == AdminType.SUPER_ADMIN:
            user.problem_permission = ProblemPermission.ALL
        else:
            user.problem_permission = ProblemPermission.NONE

        if data["password"]:
            user.set_password(data["password"])

        if data["open_api"]:
            # Avoid reset user appkey after saving changes
            if not user.open_api:
                user.open_api_appkey = rand_str()
        else:
            user.open_api_appkey = None
        user.open_api = data["open_api"]

        if data["two_factor_auth"]:
            # Avoid reset user tfa_token after saving changes
            if not user.two_factor_auth:
                user.tfa_token = rand_str()
        else:
            user.tfa_token = None

        user.two_factor_auth = data["two_factor_auth"]

        user.save()
        if pre_username != user.username:
            Submission.objects.filter(username=pre_username).update(username=user.username)

        UserProfile.objects.filter(user=user).update(real_name=data["real_name"])
        return self.success(UserAdminSerializer(user).data)
开发者ID:joeyac,项目名称:OnlineJudge,代码行数:53,代码来源:admin.py

示例3: put

    def put(self, request):
        """
        用户编辑json api接口
        ---
        request_serializer: EditUserSerializer
        response_serializer: UserSerializer
        """
        serializer = EditUserSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            try:
                user = User.objects.get(id=data["id"])
            except User.DoesNotExist:
                return error_response(u"该用户不存在!")
            try:
                user = User.objects.get(username=data["username"])
                if user.id != data["id"]:
                    return error_response(u"昵称已经存在")
            except User.DoesNotExist:
                pass
            user.username = data["username"]
            user.real_name = data["real_name"]
            user.email = data["email"]
            user.admin_type = data["admin_type"]

            if data["password"]:
                user.set_password(data["password"])

            # 后台控制用户是否可以使用openapi
            if data["openapi"] is False:
                user.openapi_appkey = None
            elif data["openapi"] and user.openapi_appkey is None:
                user.openapi_appkey = rand_str()

            # 后台控制用户是否使用两步验证
            # 注意:用户没开启,后台开启的话,用户没有绑定过两步验证token,会造成无法登陆的!
            if data["tfa_auth"] is False:
                user.two_factor_auth = False
            elif data["tfa_auth"] and user.two_factor_auth is False:
                user.two_factor_auth = True
                user.tfa_token = rand_str()

            # 后台控制用户是否被禁用
            user.is_forbidden = data["is_forbidden"]

            user.save()
            return success_response(UserSerializer(user).data)
        else:
            return serializer_invalid_response(serializer)
开发者ID:ArchFeh,项目名称:OnlineJudge,代码行数:49,代码来源:views.py

示例4: post

    def post(self, request):
        form = UploadProblemForm(request.POST, request.FILES)
        if form.is_valid():
            file = form.cleaned_data["file"]
            with tempfile.NamedTemporaryFile("wb") as tf:
                for chunk in file.chunks(4096):
                    tf.file.write(chunk)
                problems = FPSParser(tf.name).parse()
        else:
            return self.error("Parse upload file error")

        helper = FPSHelper()
        with transaction.atomic():
            for _problem in problems:
                test_case_id = rand_str()
                test_case_dir = os.path.join(settings.TEST_CASE_DIR, test_case_id)
                os.mkdir(test_case_dir)
                helper.save_test_case(_problem, test_case_dir)
                problem_data = helper.save_image(_problem, settings.UPLOAD_DIR, settings.UPLOAD_PREFIX)
                s = FPSProblemSerializer(data=problem_data)
                if not s.is_valid():
                    return self.error(f"Parse FPS file error: {s.errors}")
                problem_data = s.data
                problem_data["test_case_id"] = test_case_id
                self._create_problem(problem_data, request.user)
        return self.success({"import_count": len(problems)})
开发者ID:pq-dong,项目名称:OnlineJudge,代码行数:26,代码来源:admin.py

示例5: post

 def post(self, request):
     if request.user.is_authenticated():
         return self.error("You have already logged in, are you kidding me? ")
     data = request.data
     captcha = Captcha(request)
     if not captcha.check(data["captcha"]):
         return self.error("Invalid captcha")
     try:
         user = User.objects.get(email__iexact=data["email"])
     except User.DoesNotExist:
         return self.error("User does not exist")
     if user.reset_password_token_expire_time and 0 < int(
             (user.reset_password_token_expire_time - now()).total_seconds()) < 20 * 60:
         return self.error("You can only reset password once per 20 minutes")
     user.reset_password_token = rand_str()
     user.reset_password_token_expire_time = now() + timedelta(minutes=20)
     user.save()
     render_data = {
         "username": user.username,
         "website_name": SysOptions.website_name,
         "link": f"{SysOptions.website_base_url}/reset-password/{user.reset_password_token}"
     }
     email_html = render_to_string("reset_password_email.html", render_data)
     send_email_async.delay(from_name=SysOptions.website_name_shortcut,
                            to_email=user.email,
                            to_name=user.username,
                            subject=f"Reset your password",
                            content=email_html)
     return self.success("Succeeded")
开发者ID:joeyac,项目名称:OnlineJudge,代码行数:29,代码来源:oj.py

示例6: post

    def post(self, request):
        """
        提交请求重置密码
        ---
        request_serializer: ApplyResetPasswordSerializer
        """
        serializer = ApplyResetPasswordSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            captcha = Captcha(request)
            if not captcha.check(data["captcha"]):
                return error_response(u"验证码错误")
            try:
                user = User.objects.get(email=data["email"])
            except User.DoesNotExist:
                return error_response(u"用户不存在")
            if user.reset_password_token_create_time and (now() - user.reset_password_token_create_time).total_seconds() < 20 * 60:
                return error_response(u"20分钟内只能找回一次密码")
            user.reset_password_token = rand_str()
            user.reset_password_token_create_time = now()
            user.save()
            email_template = codecs.open(settings.TEMPLATES[0]["DIRS"][0] + "utils/reset_password_email.html", "r", "utf-8").read()

            email_template = email_template.replace("{{ username }}", user.username).\
                replace("{{ website_name }}", settings.WEBSITE_INFO["website_name"]).\
                replace("{{ link }}", request.scheme + "://" + request.META['HTTP_HOST'] + "/reset_password/t/" + user.reset_password_token)

            send_email(settings.WEBSITE_INFO["website_name"],
                       user.email,
                       user.username,
                       settings.WEBSITE_INFO["website_name"] + u" 登录信息找回邮件",
                       email_template)
            return success_response(u"邮件发送成功,请前往您的邮箱查收")
        else:
            return serializer_invalid_response(serializer)
开发者ID:adamwen829,项目名称:OnlineJudge,代码行数:35,代码来源:views.py

示例7: post

    def post(self, request):
        """
        提交请求重置密码
        ---
        request_serializer: ApplyResetPasswordSerializer
        """
        serializer = ApplyResetPasswordSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            captcha = Captcha(request)
            if not captcha.check(data["captcha"]):
                return error_response(u"验证码错误")
            try:
                user = User.objects.get(username=data["username"], email=data["email"])
            except User.DoesNotExist:
                return error_response(u"用户不存在")
            user.reset_password_token = rand_str()
            user.save()
            email_template = codecs.open(settings.TEMPLATES[0]["DIRS"][0] + "utils/reset_password_email.html", "r", "utf-8").read()

            email_template = email_template.replace("{{ username }}", user.username).replace("{{ link }}", request.scheme + "://" + request.META['HTTP_HOST'] + "/reset_password/?token=" + user.reset_password_token)

            send_email(user.email, user.username, u"qduoj 密码找回邮件", email_template)
            return success_response(u"邮件发生成功")
        else:
            return serializer_invalid_response(serializer)
开发者ID:eduStack,项目名称:OnlineJudge,代码行数:26,代码来源:views.py

示例8: post

    def post(self, request):
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            img = form.cleaned_data["image"]
        else:
            return self.response({
                "success": False,
                "msg": "Upload failed",
                "file_path": ""})

        suffix = os.path.splitext(img.name)[-1].lower()
        if suffix not in [".gif", ".jpg", ".jpeg", ".bmp", ".png"]:
            return self.response({
                "success": False,
                "msg": "Unsupported file format",
                "file_path": ""})
        img_name = rand_str(10) + suffix
        try:
            with open(os.path.join(settings.UPLOAD_DIR, img_name), "wb") as imgFile:
                for chunk in img:
                    imgFile.write(chunk)
        except IOError as e:
            logger.error(e)
            return self.response({
                "success": True,
                "msg": "Upload Error",
                "file_path": f"{settings.UPLOAD_PREFIX}/{img_name}"})
        return self.response({
            "success": True,
            "msg": "Success",
            "file_path": f"{settings.UPLOAD_PREFIX}/{img_name}"})
开发者ID:joeyac,项目名称:OnlineJudge,代码行数:31,代码来源:views.py

示例9: get

 def get(self, request):
     callback = request.GET.get("callback", None)
     if not callback or callback != settings.SSO["callback"]:
         return error_page(request, u"参数错误")
     token = rand_str()
     request.user.auth_token = token
     request.user.save()
     return render(request, "oj/account/sso.html", {"redirect_url": callback + "?token=" + token, "callback": callback})
开发者ID:adamwen829,项目名称:OnlineJudge,代码行数:8,代码来源:views.py

示例10: auth_page

def auth_page(request):
    if not request.user.is_authenticated():
        return render(request, "oj/account/oauth.html")
    callback = request.GET.get("callback", None)
    if not callback:
        return error_page(request, u"参数错误")
    token = rand_str()
    request.user.auth_token = token
    return render(request, "oj/account/oauth.html", {"callback": callback, "token": token})
开发者ID:kdwycz,项目名称:OnlineJudge,代码行数:9,代码来源:views.py

示例11: handle

 def handle(self, *args, **options):
     user = User.objects.create(username="root", real_name="root", email="[email protected]", admin_type=SUPER_ADMIN)
     rand_password = rand_str(length=6)
     user.set_password(rand_password)
     user.save()
     UserProfile.objects.create(user=user)
     self.stdout.write(self.style.SUCCESS("Successfully created super admin user.\nUsername: root\nPassword: %s\n"
                                          "Remember to change password and turn on two factors auth "
                                          "after installation." % rand_password))
开发者ID:xiaoguizi0426,项目名称:OnlineJudge,代码行数:9,代码来源:initadmin.py

示例12: post

    def post(self, request):
        """
        Generate User
        """
        data = request.data
        number_max_length = max(len(str(data["number_from"])), len(str(data["number_to"])))
        if number_max_length + len(data["prefix"]) + len(data["suffix"]) > 32:
            return self.error("Username should not more than 32 characters")
        if data["number_from"] > data["number_to"]:
            return self.error("Start number must be lower than end number")

        file_id = rand_str(8)
        filename = f"/tmp/{file_id}.xlsx"
        workbook = xlsxwriter.Workbook(filename)
        worksheet = workbook.add_worksheet()
        worksheet.set_column("A:B", 20)
        worksheet.write("A1", "Username")
        worksheet.write("B1", "Password")
        i = 1

        user_list = []
        for number in range(data["number_from"], data["number_to"] + 1):
            raw_password = rand_str(data["password_length"])
            user = User(username=f"{data['prefix']}{number}{data['suffix']}", password=make_password(raw_password))
            user.raw_password = raw_password
            user_list.append(user)

        try:
            with transaction.atomic():

                ret = User.objects.bulk_create(user_list)
                UserProfile.objects.bulk_create([UserProfile(user=user) for user in ret])
                for item in user_list:
                    worksheet.write_string(i, 0, item.username)
                    worksheet.write_string(i, 1, item.raw_password)
                    i += 1
                workbook.close()
                return self.success({"file_id": file_id})
        except IntegrityError as e:
            # Extract detail from exception message
            #    duplicate key value violates unique constraint "user_username_key"
            #    DETAIL:  Key (username)=(root11) already exists.
            return self.error(str(e).split("\n")[1])
开发者ID:joeyac,项目名称:OnlineJudge,代码行数:43,代码来源:admin.py

示例13: process_zip

    def process_zip(self, uploaded_zip_file, spj, dir=""):
        try:
            zip_file = zipfile.ZipFile(uploaded_zip_file, "r")
        except zipfile.BadZipFile:
            raise APIError("Bad zip file")
        name_list = zip_file.namelist()
        test_case_list = self.filter_name_list(name_list, spj=spj, dir=dir)
        if not test_case_list:
            raise APIError("Empty file")

        test_case_id = rand_str()
        test_case_dir = os.path.join(settings.TEST_CASE_DIR, test_case_id)
        os.mkdir(test_case_dir)
        os.chmod(test_case_dir, 0o710)

        size_cache = {}
        md5_cache = {}

        for item in test_case_list:
            with open(os.path.join(test_case_dir, item), "wb") as f:
                content = zip_file.read(f"{dir}{item}").replace(b"\r\n", b"\n")
                size_cache[item] = len(content)
                if item.endswith(".out"):
                    md5_cache[item] = hashlib.md5(content.rstrip()).hexdigest()
                f.write(content)
        test_case_info = {"spj": spj, "test_cases": {}}

        info = []

        if spj:
            for index, item in enumerate(test_case_list):
                data = {"input_name": item, "input_size": size_cache[item]}
                info.append(data)
                test_case_info["test_cases"][str(index + 1)] = data
        else:
            # ["1.in", "1.out", "2.in", "2.out"] => [("1.in", "1.out"), ("2.in", "2.out")]
            test_case_list = zip(*[test_case_list[i::2] for i in range(2)])
            for index, item in enumerate(test_case_list):
                data = {"stripped_output_md5": md5_cache[item[1]],
                        "input_size": size_cache[item[0]],
                        "output_size": size_cache[item[1]],
                        "input_name": item[0],
                        "output_name": item[1]}
                info.append(data)
                test_case_info["test_cases"][str(index + 1)] = data

        with open(os.path.join(test_case_dir, "info"), "w", encoding="utf-8") as f:
            f.write(json.dumps(test_case_info, indent=4))

        for item in os.listdir(test_case_dir):
            os.chmod(os.path.join(test_case_dir, item), 0o640)

        return info, test_case_id
开发者ID:pq-dong,项目名称:OnlineJudge,代码行数:53,代码来源:admin.py

示例14: get

    def get(self, request):
        """
        Get QR code
        """
        user = request.user
        if user.two_factor_auth:
            return self.error("2FA is already turned on")
        token = rand_str()
        user.tfa_token = token
        user.save()

        label = f"{SysOptions.website_name_shortcut}:{user.username}"
        image = qrcode.make(OtpAuth(token).to_uri("totp", label, SysOptions.website_name.replace(" ", "")))
        return self.success(img2base64(image))
开发者ID:joeyac,项目名称:OnlineJudge,代码行数:14,代码来源:oj.py

示例15: post

    def post(self, request):
        if "file" not in request.FILES:
            return error_response(u"文件上传失败")

        f = request.FILES["file"]
        if f.size > 1024 * 1024:
            return error_response(u"图片过大")
        if os.path.splitext(f.name)[-1].lower() not in [".gif", ".jpg", ".jpeg", ".bmp", ".png"]:
            return error_response(u"需要上传图片格式")
        name = "avatar_" + rand_str(5) + os.path.splitext(f.name)[-1]
        with open(os.path.join(settings.IMAGE_UPLOAD_DIR, name), "wb") as img:
            for chunk in request.FILES["file"]:
                img.write(chunk)
        return success_response({"path": "/static/upload/" + name})
开发者ID:ArchFeh,项目名称:OnlineJudge,代码行数:14,代码来源:views.py


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