Пример #1
0
 def post(self, request):
     """
     加入某个小组的api
     ---
     request_serializer: CreateJoinGroupRequestSerializer
     """
     serializer = CreateJoinGroupRequestSerializer(data=request.data)
     if serializer.is_valid():
         data = serializer.data
         try:
             group = Group.objects.get(id=data["group_id"])
         except Group.DoesNotExist:
             return error_response(u"小组不存在")
         if group.join_group_setting == 0:
             if join_group(request.user, group):
                 return success_response(u"你已经成功的加入该小组")
             else:
                 return error_response(u"你已经是小组成员了")
         elif group.join_group_setting == 1:
             if not data["message"]:
                 return error_response(u"message : 该字段是必填项。")
             try:
                 JoinGroupRequest.objects.get(user=request.user, group=group, status=False)
                 return error_response(u"你已经提交过申请了,请等待审核")
             except JoinGroupRequest.DoesNotExist:
                 JoinGroupRequest.objects.create(user=request.user, group=group, message=data["message"])
             return success_response(u"申请提交成功,请等待审核")
         elif group.join_group_setting == 2:
             return error_response(u"该小组不允许任何人加入")
     else:
         return serializer_invalid_response(serializer)
Пример #2
0
    def post(self, request):
        """
        用户登录json api接口
        ---
        request_serializer: UserLoginSerializer
        """
        serializer = UserLoginSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            user = auth.authenticate(username=data["username"], password=data["password"])
            # 用户名或密码错误的话 返回None
            if user:
                if not user.two_factor_auth:
                    auth.login(request, user)
                    return success_response(u"登录成功")

                # 没有输入两步验证的验证码
                if user.two_factor_auth and "tfa_code" not in data:
                    return success_response("tfa_required")

                if OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]):
                    auth.login(request, user)
                    return success_response(u"登录成功")
                else:
                    return error_response(u"验证码错误")
            else:
                return error_response(u"用户名或密码错误")
        else:
            return serializer_invalid_response(serializer)
Пример #3
0
    def put(self, request):
        """
        同意或者拒绝加入小组请求
        ---
        request_serializer: PutJoinGroupRequestSerializer
        """
        serializer = PutJoinGroupRequestSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            try:
                join_request = JoinGroupRequest.objects.get(id=data["request_id"], group__admin=request.user,
                                                            status=False)
            except JoinGroupRequest.DoesNotExist:
                return error_response(u"请求不存在")

            join_request.status = True
            join_request.save()
            if data["status"]:
                if join_group(join_request.user, join_request.group):
                    join_request.accepted = True
                    join_request.save()
                    return success_response(u"加入成功")
                else:
                    return error_response(u"加入失败,已经在本小组内")
            else:
                return success_response(u"已拒绝")

        else:
            return serializer_invalid_response(serializer)
Пример #4
0
 def get(self, request):
     """
     判断用户登录是否需要验证码
     ---
     """
     username = request.GET.get("username", None)
     if username:
         try:
             User.objects.get(username=username, admin_type__gt=0)
         except User.DoesNotExist:
             return success_response({"applied_captcha": False})
         return success_response({"applied_captcha": True})
     return success_response({"applied_captcha": False})
Пример #5
0
 def post(self, request):
     """
     检测邮箱是否存在,存在返回True,不存在返回False
     ---
     request_serializer: EmailCheckSerializer
     """
     serializer = EmailCheckSerializer(data=request.data)
     if serializer.is_valid():
         try:
             User.objects.get(email=serializer.data["email"])
             return success_response(True)
         except User.DoesNotExist:
             return success_response(False)
     else:
         return serializer_invalid_response(serializer)
Пример #6
0
 def post(self, request):
     problem_id = request.data.get("problem_id", -1)
     try:
         problem = ContestProblem.objects.get(id=problem_id, is_public=False)
         problem.is_public = True
         problem.save()
     except ContestProblem.DoesNotExist:
         return error_response(u"比赛不存在")
     if problem.contest.status != CONTEST_ENDED:
         return error_response(u"比赛还没有结束,不能公开题目")
     Problem.objects.create(
         title=problem.title,
         description=problem.description,
         input_description=problem.input_description,
         output_description=problem.output_description,
         samples=problem.samples,
         test_case_id=problem.test_case_id,
         hint=problem.hint,
         created_by=problem.created_by,
         time_limit=problem.time_limit,
         memory_limit=problem.memory_limit,
         visible=False,
         difficulty=-1,
         source=problem.contest.title,
     )
     problem.is_public = True
     problem.save()
     return success_response(u"创建成功")
Пример #7
0
    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)
Пример #8
0
    def put(self, request):
        """
        修改判题服务器信息 json api接口
        ---
        request_serializer: EditJudgesSerializer
        response_serializer: JudgesSerializer
        """
        serializer = EditJudgesSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            try:
                judge_server = JudgeServer.objects.get(pk=data["id"])
            except JudgeServer.DoesNotExist:
                return error_response(u"此判题服务器不存在!")

            judge_server.name = data["name"]
            judge_server.ip = data["ip"]
            judge_server.port = data["port"]
            judge_server.max_instance_number = data["max_instance_number"]
            # 强制reset为0, 因为celery可能部分情况下进程挂掉, 导致这个值增加后无法减少, 在编辑的时候重置为0算是一种临时解决方案。
            judge_server.used_instance_number = 0
            judge_server.token = data["token"]
            judge_server.status = data["status"]
            judge_server.save()
            return success_response(JudgesSerializer(judge_server).data)
        else:
            return serializer_invalid_response(serializer)
Пример #9
0
 def post(self, request):
     """
     用户注册json api接口
     ---
     request_serializer: UserRegisterSerializer
     """
     serializer = UserRegisterSerializer(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.objects.get(username=data["username"])
             return error_response(u"用户名已存在")
         except User.DoesNotExist:
             pass
         try:
             User.objects.get(email=data["email"])
             return error_response(u"该邮箱已被注册,请换其他邮箱进行注册")
         except User.DoesNotExist:
             user = User.objects.create(username=data["username"], real_name=data["real_name"],
                                        email=data["email"])
             user.set_password(data["password"])
             user.save()
             return success_response(u"注册成功!")
     else:
         return serializer_invalid_response(serializer)
Пример #10
0
 def post(self, request):
     """
     创建比赛的提交
     ---
     request_serializer: CreateContestSubmissionSerializer
     """
     serializer = CreateContestSubmissionSerializer(data=request.data)
     if serializer.is_valid():
         data = serializer.data
         contest = Contest.objects.get(id=data["contest_id"])
         try:
             problem = ContestProblem.objects.get(contest=contest, id=data["problem_id"])
         except ContestProblem.DoesNotExist:
             return error_response(u"题目不存在")
         submission = Submission.objects.create(user_id=request.user.id,
                                                language=int(data["language"]),
                                                contest_id=contest.id,
                                                code=data["code"],
                                                problem_id=problem.id)
         try:
             _judge.delay(submission.id, problem.time_limit, problem.memory_limit, problem.test_case_id,
                          problem.spj, problem.spj_language, problem.spj_code, problem.spj_version)
         except Exception as e:
             logger.error(e)
             return error_response(u"提交判题任务失败")
         return success_response({"submission_id": submission.id})
     else:
         return serializer_invalid_response(serializer)
Пример #11
0
 def post(self, request):
     """
     题目发布json api接口
     ---
     request_serializer: CreateProblemSerializer
     response_serializer: ProblemSerializer
     """
     serializer = CreateProblemSerializer(data=request.data)
     if serializer.is_valid():
         data = serializer.data
         problem = Problem.objects.create(title=data["title"],
                                          description=data["description"],
                                          input_description=data["input_description"],
                                          output_description=data["output_description"],
                                          test_case_id=data["test_case_id"],
                                          source=data["source"],
                                          samples=json.dumps(data["samples"]),
                                          time_limit=data["time_limit"],
                                          memory_limit=data["memory_limit"],
                                          difficulty=data["difficulty"],
                                          created_by=request.user,
                                          hint=data["hint"],
                                          visible=data["visible"])
         for tag in data["tags"]:
             try:
                 tag = ProblemTag.objects.get(name=tag)
             except ProblemTag.DoesNotExist:
                 tag = ProblemTag.objects.create(name=tag)
             problem.tags.add(tag)
         return success_response(ProblemSerializer(problem).data)
     else:
         return serializer_invalid_response(serializer)
Пример #12
0
    def get(self, request):
        """
        比赛分页json api接口
        ---
        response_serializer: ContestSerializer
        """
        contest_id = request.GET.get("contest_id", None)
        if contest_id:
            try:
                # 普通管理员只能获取自己创建的题目
                # 超级管理员可以获取全部的题目
                contest = Contest.objects.get(id=contest_id)
                if request.user.admin_type != SUPER_ADMIN:
                    contest_set = Contest.objects.filter(groups__in=request.user.managed_groups.all())
                    if contest not in contest_set:
                        return error_response(u"比赛不存在")
                return success_response(ContestSerializer(contest).data)
            except Contest.DoesNotExist:
                return error_response(u"比赛不存在")

        if request.user.admin_type == SUPER_ADMIN:
            contest = Contest.objects.all().order_by("-create_time")
        else:
            contest = Contest.objects.filter(groups__in=request.user.managed_groups.all()).distinct().order_by("-create_time")
        visible = request.GET.get("visible", None)
        if visible:
            contest = contest.filter(visible=(visible == "true"))
        keyword = request.GET.get("keyword", None)
        if keyword:
            contest = contest.filter(Q(title__contains=keyword) |
                                     Q(description__contains=keyword))
        return paginate(request, contest, ContestSerializer)
Пример #13
0
def _submit_code(user, problem_id, language, code):
    controller = BucketController(user_id=user.id,
                                  redis_conn=redis.Redis(host=settings.REDIS_CACHE["host"],
                                                         port=settings.REDIS_CACHE["port"],
                                                         db=settings.REDIS_CACHE["db"]),
                                  default_capacity=settings.TOKEN_BUCKET_DEFAULT_CAPACITY)
    bucket = TokenBucket(fill_rate=settings.TOKEN_BUCKET_FILL_RATE,
                         capacity=settings.TOKEN_BUCKET_DEFAULT_CAPACITY,
                         last_capacity=controller.last_capacity,
                         last_timestamp=controller.last_timestamp)
    if bucket.consume():
        controller.last_capacity -= 1
    else:
        return error_response(u"您提交的频率过快, 请等待%d秒" % int(bucket.expected_time() + 1))

    try:
        problem = Problem.objects.get(id=problem_id)
    except Problem.DoesNotExist:
        return error_response(u"题目不存在")
    submission = Submission.objects.create(user_id=user.id,
                                           language=language,
                                           code=code,
                                           problem_id=problem.id)

    try:
        _judge.delay(submission.id, problem.time_limit, problem.memory_limit, problem.test_case_id,
                     problem.spj, problem.spj_language, problem.spj_code, problem.spj_version)
    except Exception as e:
        logger.error(e)
        return error_response(u"提交判题任务失败")
    return success_response({"submission_id": submission.id})
Пример #14
0
    def get(self, request):
        """
        比赛题目分页json api接口
        ---
        response_serializer: ContestProblemSerializer
        """
        contest_problem_id = request.GET.get("contest_problem_id", None)
        if contest_problem_id:
            try:
                contest_problem = ContestProblem.objects.get(id=contest_problem_id)
                if request.user.admin_type != SUPER_ADMIN and contest_problem.created_by != request.user:
                    return error_response(u"比赛题目不存在")
                return success_response(ContestProblemSerializer(contest_problem).data)
            except ContestProblem.DoesNotExist:
                return error_response(u"比赛题目不存在")

        contest_problems = ContestProblem.objects.all().order_by("sort_index")
        if request.user.admin_type != SUPER_ADMIN:
            contest_problems = contest_problems.filter(created_by=request.user).order_by("sort_index")
        visible = request.GET.get("visible", None)
        if visible:
            contest_problems = contest_problems.filter(visible=(visible == "true"))
        keyword = request.GET.get("keyword", None)
        if keyword:
            contest_problems = contest_problems.filter(Q(title__contains=keyword) |
                                                       Q(description__contains=keyword))
        contest_id = request.GET.get("contest_id", None)
        if contest_id:
            contest_problems = contest_problems.filter(contest__id=contest_id).order_by("sort_index")

        return paginate(request, contest_problems, ContestProblemSerializer)
Пример #15
0
    def put(self, request):
        """
        修改小组信息的api
        ---
        request_serializer: EditGroupSerializer
        response_serializer: GroupSerializer
        """
        serializer = EditGroupSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            try:
                group = self.get_group(request, data["group_id"])
            except Group.DoesNotExist:
                return error_response(u"小组不存在")
            try:
                group.name = data["name"]
                group.description = data["description"]
                group.join_group_setting = data["join_group_setting"]
                group.visible = data["visible"]
                group.save()
            except IntegrityError:
                return error_response(u"小组名已经存在")

            return success_response(GroupSerializer(group).data)
        else:
            return serializer_invalid_response(serializer)
Пример #16
0
 def post(self, request):
     """
     比赛题目发布json api接口
     ---
     request_serializer: CreateContestProblemSerializer
     response_serializer: ContestProblemSerializer
     """
     serializer = CreateContestProblemSerializer(data=request.data)
     if serializer.is_valid():
         data = serializer.data
         try:
             contest = Contest.objects.get(id=data["contest_id"])
             if request.user.admin_type != SUPER_ADMIN:
                 contest_set = Contest.objects.filter(groups__in=request.user.managed_groups.all())
                 if contest not in contest_set:
                     return error_response(u"比赛不存在")
         except Contest.DoesNotExist:
             return error_response(u"比赛不存在")
         contest_problem = ContestProblem.objects.create(title=data["title"],
                                                         description=data["description"],
                                                         input_description=data["input_description"],
                                                         output_description=data["output_description"],
                                                         test_case_id=data["test_case_id"],
                                                         samples=json.dumps(data["samples"]),
                                                         time_limit=data["time_limit"],
                                                         memory_limit=data["memory_limit"],
                                                         created_by=request.user,
                                                         hint=data["hint"],
                                                         contest=contest,
                                                         sort_index=data["sort_index"])
         return success_response(ContestProblemSerializer(contest_problem).data)
     else:
         return serializer_invalid_response(serializer)
Пример #17
0
 def get(self, request):
     """
     查询小组列表或者单个小组的信息,查询单个小组需要传递group_id参数,否则返回全部
     ---
     response_serializer: GroupSerializer
     """
     group_id = request.GET.get("group_id", None)
     # 根据 id 查询小组信息
     if group_id:
         try:
             group = self.get_group(request, group_id)
             return success_response(GroupSerializer(group).data)
         except Group.DoesNotExist:
             return error_response(u"小组不存在")
     else:
         groups = self.get_groups(request)
         # 搜索小组
         if request.GET.get("keyword", None):
             groups = groups.filter(name__contains=request.GET["keyword"])
         # 只返回我创建的小组 适用于超级管理员
         if request.GET.get("my_group", None):
             groups = groups.filter(admin=request.user)
         # 只返回指定用户的小组 适用于管理员
         elif request.GET.get("admin_id", None):
             groups = groups.filter(admin__id=request.GET["admin_id"])
         return paginate(request, groups, GroupSerializer)
Пример #18
0
    def get(self, request):
        """
        题目分页json api接口
        ---
        response_serializer: ProblemSerializer
        """
        problem_id = request.GET.get("problem_id", None)
        if problem_id:
            try:
                # 普通管理员只能获取自己创建的题目
                # 超级管理员可以获取全部的题目
                problem = Problem.objects.get(id=problem_id)
                if request.user.admin_type != SUPER_ADMIN and problem.created_by != request.user:
                    return error_response(u"题目不存在")
                return success_response(ProblemSerializer(problem).data)
            except Problem.DoesNotExist:
                return error_response(u"题目不存在")

        # 获取问题列表
        problems = Problem.objects.all().order_by("-create_time")

        if request.user.admin_type != SUPER_ADMIN:
            problems = problems.filter(created_by=request.user)

        visible = request.GET.get("visible", None)
        if visible:
            problems = problems.filter(visible=(visible == "true"))
        keyword = request.GET.get("keyword", None)
        if keyword:
            problems = problems.filter(Q(title__contains=keyword) |
                                       Q(description__contains=keyword))

        return paginate(request, problems, ProblemSerializer)
Пример #19
0
    def post(self, request):
        """
        公告发布json api接口
        ---
        request_serializer: CreateAnnouncementSerializer
        """
        serializer = CreateAnnouncementSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            groups = []
            # 如果不是全局公告,就去查询一下小组的id 列表中的内容,注意用户身份
            if not data["is_global"]:
                if request.user.admin_type == SUPER_ADMIN:
                    groups = Group.objects.filter(id__in=data["groups"])
                else:
                    groups = Group.objects.filter(id__in=data["groups"], admin=request.user)
                if not groups.count():
                    return error_response(u"至少选择一个小组")
            else:
                if request.user.admin_type != SUPER_ADMIN:
                    return error_response(u"只有超级管理员可以创建全局公告")

            announcement = Announcement.objects.create(title=data["title"],
                                                       content=data["content"],
                                                       created_by=request.user,
                                                       is_global=data["is_global"])

            announcement.groups.add(*groups)
            return success_response(u"公告发布成功!")
        else:
            return serializer_invalid_response(serializer)
Пример #20
0
    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)
Пример #21
0
 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"])
         user.save()
         return success_response(UserSerializer(user).data)
     else:
         return serializer_invalid_response(serializer)
Пример #22
0
    def post(self, request):
        serializer = SubmissionRejudgeSerializer(data=request.data)
        if serializer.is_valid():
            submission_id = serializer.data["submission_id"]
            try:
                submission = Submission.objects.get(id=submission_id)
            except Submission.DoesNotExist:
                return error_response(u"提交不存在")
            # 目前只考虑前台公开题目的重新判题
            try:
                problem = Problem.objects.get(id=submission.problem_id)
            except Problem.DoesNotExist:
                return error_response(u"题目不存在")
            try:
                judge.delay(submission_id, problem.time_limit, problem.memory_limit, problem.test_case_id)
            except Exception as e:
                logger.error(e)
                return error_response(u"提交判题任务失败")

            # 增加redis 中判题队列长度的计数器
            r = redis.Redis(host=redis_config["host"], port=redis_config["port"], db=redis_config["db"])
            r.incr("judge_queue_length")
            return success_response(u"任务提交成功")
        else:
            return serializer_invalid_response(serializer)
Пример #23
0
 def get(self, request):
     """
     返回这个用户的个人信息
     ---
     response_serializer: UserSerializer
     """
     return success_response(UserSerializer(request.user).data)
Пример #24
0
 def post(self, request):
     """
     创建比赛的提交
     ---
     request_serializer: CreateContestSubmissionSerializer
     """
     serializer = CreateContestSubmissionSerializer(data=request.data)
     if serializer.is_valid():
         data = serializer.data
         contest = Contest.objects.get(id=data["contest_id"])
         try:
             problem = ContestProblem.objects.get(contest=contest, id=data["problem_id"])
             # 更新题目提交计数器
             problem.total_submit_number += 1
             problem.save()
         except ContestProblem.DoesNotExist:
             return error_response(u"题目不存在")
         submission = Submission.objects.create(user_id=request.user.id, language=int(data["language"]),
                                                contest_id=contest.id, code=data["code"], problem_id=problem.id)
         try:
             judge.delay(submission.id, problem.time_limit, problem.memory_limit, problem.test_case_id)
         except Exception:
             return error_response(u"提交判题任务失败")
         # 增加redis 中判题队列长度的计数器
         r = redis.Redis(host=redis_config["host"], port=redis_config["port"], db=redis_config["db"])
         r.incr("judge_queue_length")
         return success_response({"submission_id": submission.id})
     else:
         return serializer_invalid_response(serializer)
Пример #25
0
    def post(self, request):
        """
        用户登录json api接口
        ---
        request_serializer: UserLoginSerializer
        """
        serializer = UserLoginSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data

            if "captcha" not in data:
                return error_response(u"请填写验证码!")
            captcha = Captcha(request)
            if not captcha.check(data["captcha"]):
                return error_response(u"验证码错误")

            user = auth.authenticate(username=data["username"], password=data["password"])
            # 用户名或密码错误的话 返回None
            if user:
                auth.login(request, user)
                return success_response(u"登录成功")
            else:
                return error_response(u"用户名或密码错误")
        else:
            return serializer_invalid_response(serializer)
Пример #26
0
    def put(self, request):
        """
        比赛题目编辑json api接口
        ---
        request_serializer: EditContestProblemSerializer
        response_serializer: ContestProblemSerializer
        """
        serializer = EditContestProblemSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data

            try:
                contest_problem = ContestProblem.objects.get(id=data["id"])
            except ContestProblem.DoesNotExist:
                return error_response(u"该比赛题目不存在!")
            contest = Contest.objects.get(id=contest_problem.contest_id)
            if request.user.admin_type != SUPER_ADMIN and contest.created_by != request.user:
                return error_response(u"比赛不存在")
            contest_problem.title = data["title"]
            contest_problem.description = data["description"]
            contest_problem.input_description = data["input_description"]
            contest_problem.output_description = data["output_description"]
            contest_problem.test_case_id = data["test_case_id"]
            contest_problem.time_limit = data["time_limit"]
            contest_problem.memory_limit = data["memory_limit"]
            contest_problem.samples = json.dumps(data["samples"])
            contest_problem.hint = data["hint"]
            contest_problem.visible = data["visible"]
            contest_problem.sort_index = data["sort_index"]
            contest_problem.last_update_time = now()
            contest_problem.save()
            return success_response(ContestProblemSerializer(contest_problem).data)
        else:
            return serializer_invalid_response(serializer)
Пример #27
0
    def post(self, request):
        """
        提交代码
        ---
        request_serializer: CreateSubmissionSerializer
        """
        serializer = CreateSubmissionSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            try:
                problem = Problem.objects.get(id=data["problem_id"])
            except Problem.DoesNotExist:
                return error_response(u"题目不存在")
            submission = Submission.objects.create(user_id=request.user.id, language=int(data["language"]),
                                                   code=data["code"], problem_id=problem.id)

            try:
                judge.delay(submission.id, problem.time_limit, problem.memory_limit, problem.test_case_id)
            except Exception as e:
                logger.error(e)
                return error_response(u"提交判题任务失败")
            r = redis.Redis(host=redis_config["host"], port=redis_config["port"], db=redis_config["db"])
            r.incr("judge_queue_length")

            return success_response({"submission_id": submission.id})
        else:
            return serializer_invalid_response(serializer)
Пример #28
0
 def get(self, request):
     r = redis.Redis(host=redis_config["host"], port=redis_config["port"], db=redis_config["db"])
     waiting_number = r.get("judge_queue_length")
     if waiting_number is None:
         waiting_number = 0
     now = datetime.datetime.now()
     return success_response({"time": ":".join([str(now.hour), str(now.minute), str(now.second)]),
                              "count": waiting_number})
Пример #29
0
    def put(self, request):
        """
        比赛编辑json api接口
        ---
        request_serializer: EditContestSerializer
        response_serializer: ContestSerializer
        """
        serializer = EditContestSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            groups = []
            try:
                # 超级管理员可以编辑所有的
                contest = Contest.objects.get(id=data["id"])
                if request.user.admin_type != SUPER_ADMIN:
                    contest = contest.get(created_by=request.user)
            except Contest.DoesNotExist:
                return error_response(u"该比赛不存在!")
            try:
                contest = Contest.objects.get(title=data["title"])
                if contest.id != data["id"]:
                    return error_response(u"该比赛名称已经存在")
            except Contest.DoesNotExist:
                pass
            if data["contest_type"] in [PUBLIC_CONTEST, PASSWORD_PROTECTED_CONTEST]:
                if request.user.admin_type != SUPER_ADMIN:
                    return error_response(u"只有超级管理员才可创建公开赛")
            if data["contest_type"] == PASSWORD_PROTECTED_CONTEST:
                if not data["password"]:
                    return error_response(u"此比赛为有密码的公开赛,密码不可为空")
            elif data["contest_type"] == GROUP_CONTEST:
                if request.user.admin_type == SUPER_ADMIN:
                    groups = Group.objects.filter(id__in=data["groups"])
                else:
                    groups = Group.objects.filter(id__in=data["groups"], admin=request.user)
                if not groups.count():
                    return error_response(u"请至少选择一个小组")
            if data["start_time"] >= data["end_time"]:
                return error_response(u"比赛的开始时间必须早于比赛结束的时间")

            contest.title = data["title"]
            contest.description = data["description"]
            contest.mode = data["mode"]
            contest.contest_type = data["contest_type"]
            contest.real_time_rank = data["real_time_rank"]
            contest.show_user_submission = data["show_user_submission"]
            contest.start_time = dateparse.parse_datetime(data["start_time"])
            contest.end_time = dateparse.parse_datetime(data["end_time"])
            contest.visible = data["visible"]
            contest.password = data["password"]
            contest.save()

            contest.groups.clear()
            contest.groups.add(*groups)
            return success_response(ContestSerializer(contest).data)
        else:
            return serializer_invalid_response(serializer)
Пример #30
0
 def get(self, request):
     contest_id = request.GET.get("contest_id", -1)
     try:
         contest = Contest.objects.get(id=contest_id)
     except Contest.DoesNotExist:
         return error_response(u"比赛不存在")
     return success_response({"start": int((contest.start_time - now()).total_seconds() * 1000),
                              "end": int((contest.end_time - now()).total_seconds() * 1000),
                              "status": contest.status})
Пример #31
0
 def put(self, request):
     serializer = TopicSerializer(data=request.data)
     if serializer.is_valid():
         data = serializer.data
         if str(request.data["dell"]) == '1':
             topic=Topic.objects.get(id=int(request.data['id']))
             topic.delete()
             return success_response(u"删除成功")
         else :#修改
             try:
                 topic = Topic.objects.get(id=int(request.data['id']))
             except Topic.DoesNotExist:
                 return error_response(u"厉害了,没有这个id,sorry!")
         topic.title = data["title"]
         topic.hidden = data["hidden"]
         topic.closed = data["closed"]
         topic.content_raw = data["content_raw"]
         topic.save()
         return success_response(TopicSerializer(topic).data)
     else :
         return serializer_invalid_response(serializer)
Пример #32
0
 def get(self, request):
     test_case_id = request.GET.get("test_case_id", None)
     if not test_case_id:
         return error_response(u"参数错误")
     test_case_config = settings.TEST_CASE_DIR + test_case_id + "/info"
     try:
         f = open(test_case_config)
         config = json.loads(f.read())
         f.close()
     except Exception as e:
         return error_response(u"读取测试用例出错")
     return success_response({"file_list": config["test_cases"]})
Пример #33
0
 def post(self, request):
     bookName = request.POST.get("bookName")
     author = request.POST.get("author")
     type = request.POST.get("type")
     describe = request.POST.get("describe")
     book = BookInfo(bookName=bookName,
                     author=author,
                     type=type,
                     describe=describe)
     book.save()
     message = "书籍创建成功"
     return shortcuts.success_response(message)
Пример #34
0
 def get(self, request):
     test_case_id = request.GET.get("test_case_id", None)
     if not test_case_id:
         return error_response(u"参数错误")
     test_case_config = os.path.join(settings.TEST_CASE_DIR, test_case_id, "info")
     try:
         f = open(test_case_config)
         config = json.loads(f.read())
         f.close()
     except Exception as e:
         return error_response(u"读取测试用例出错")
     return success_response({"file_list": config["test_cases"], "spj": config.get("spj", False)})
Пример #35
0
 def get(self, request):
     submission_id = request.GET.get("submission_id", None)
     if not submission_id:
         return error_response(u"参数错误")
     try:
         submission = Submission.objects.get(id=submission_id, user_id=request.user.id)
     except Submission.DoesNotExist:
         return error_response(u"提交不存在")
     response_data = {"result": submission.result}
     if submission.result == 0:
         response_data["accepted_answer_time"] = submission.accepted_answer_time
         response_data["accepted_answer_info"] = submission.accepted_answer_info
     return success_response(response_data)
Пример #36
0
 def post(self, request):
     """
     公告发布json api接口
     ---
     request_serializer: CreateAnnouncementSerializer
     """
     serializer = CreateAnnouncementSerializer(data=request.data)
     if serializer.is_valid():
         data = serializer.data
         Announcement.objects.create(title=data["title"], content=data["content"], created_by=request.user)
         return success_response(u"公告发布成功!")
     else:
         return serializer_invalid_response(serializer)
Пример #37
0
 def put(self, request):
     serializer = AppendixSerializer(data=request.data)
     if serializer.is_valid():
         data = serializer.data
         if str(request.data["dell"]) == '1':
             try:
                 appendix=Appendix.objects.get(id=int(request.data['id']))
                 appendix.delete()
             except Appendix.DoesNotExist:
                 return error_response(u"厉害了,没有这个id,sorry!")
             return success_response(u"删除成功")
         else :#修改
             try:
                 appendix = Appendix.objects.get(id=int(request.data['id']))
             except Appendix.DoesNotExist:
                 return error_response(u"厉害了,没有这个id,sorry!")
                 pass
         appendix.content_raw = data["content_raw"]
         appendix.save()
         return success_response(PostSerializer(appendix).data)
     else :
         return serializer_invalid_response(serializer)
Пример #38
0
 def post(self, request):
     """
     用户留言功能
     """
     serializer = UserLeaveMessageSerializer(data=request.data)
     if serializer.is_valid():
         data = serializer.data
         leave_to = User.objects.get(username=data["leave_to"])
         Message.objects.create(content=data["content"], who_leave=request.user,
                                leave_to=leave_to)
         return success_response(u"留言成功")
     else:
         return serializer_invalid_response(serializer)
Пример #39
0
    def post(self, request):
        """
        比赛发布json api接口
        ---
        request_serializer: CreateContestSerializer
        response_serializer: ContestSerializer
        """
        serializer = CreateContestSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            groups = []
            # 首先判断比赛的类型: 0 即为是小组赛(GROUP_CONTEST),1 即为是无密码的公开赛(PUBLIC_CONTEST),
            # 2 即为是有密码的公开赛(PASSWORD_PUBLIC_CONTEST)
            # 此时为有密码的公开赛,并且此时只能超级管理员才有权限此创建比赛
            if data["contest_type"] in [
                    PUBLIC_CONTEST, PASSWORD_PROTECTED_CONTEST
            ]:
                if request.user.admin_type != SUPER_ADMIN:
                    return error_response(u"只有超级管理员才可创建公开赛")

            if data["contest_type"] == PASSWORD_PROTECTED_CONTEST:
                if not data["password"]:
                    return error_response(u"此比赛为有密码的公开赛,密码不可为空")
            # 没有密码的公开赛 没有密码的小组赛
            elif data["contest_type"] == GROUP_CONTEST:
                if request.user.admin_type == SUPER_ADMIN:
                    groups = Group.objects.filter(id__in=data["groups"])
                else:
                    groups = Group.objects.filter(id__in=data["groups"],
                                                  admin=request.user)
                if not groups.count():
                    return error_response(u"请至少选择一个小组")
            if data["start_time"] >= data["end_time"]:
                return error_response(u"比赛的开始时间必须早于比赛结束的时间")
            try:
                contest = Contest.objects.create(
                    title=data["title"],
                    description=data["description"],
                    contest_type=data["contest_type"],
                    real_time_rank=data["real_time_rank"],
                    password=data["password"],
                    start_time=dateparse.parse_datetime(data["start_time"]),
                    end_time=dateparse.parse_datetime(data["end_time"]),
                    created_by=request.user,
                    visible=data["visible"])
            except IntegrityError:
                return error_response(u"比赛名已经存在")
            contest.groups.add(*groups)
            return success_response(ContestSerializer(contest).data)
        else:
            return serializer_invalid_response(serializer)
Пример #40
0
 def post(self, request):
     """
     post讨论内容
     """
     msg = request.POST.get("message")
     problem_id = request.POST.get("problem_id")
     try:
         problem = Problem.objects.get(id=problem_id, visible=True)
     except Problem.DoesNotExist:
         return error_response(u"题目不存在")
     ProblemDiscussion.objects.create(message=msg,
                                      user=request.user,
                                      problem=problem)
     return success_response(u"留言成功!")
Пример #41
0
 def get(self, request):
     # serializer = RewardSerializers(request.data)
     userId = request.user.id
     userName = request.user.userName
     bookId = request.GET.get("bookId")
     productionNumber = request.GET.get("productionNumber")
     rewardType = request.GET.get("rewardType")
     book = BookInfo.objects.filter(id=bookId).get()
     rewardMoney =rewardtype.rewardType[rewardType].money * int(productionNumber)
     reward = Reward(userId=userId, bookId=bookId, userName=userName, bookName=book.bookName,
                     rewardMoney=rewardMoney, productionNumber=productionNumber, rewardType=rewardType)
     reward.save()
     message = "打赏成功"
     return shortcuts.success_response(message)
Пример #42
0
 def get(self, request):
     contest_id = request.GET.get("contest_id", -1)
     try:
         contest = Contest.objects.get(id=contest_id)
     except Contest.DoesNotExist:
         return error_response(u"比赛不存在")
     return success_response({
         "start":
         int((contest.start_time - now()).total_seconds() * 1000),
         "end":
         int((contest.end_time - now()).total_seconds() * 1000),
         "status":
         contest.status
     })
Пример #43
0
    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})
    def get(self, request):
        """
        获取全部判题服务器
        """
        judge_server_id = request.GET.get("judge_server_id", None)
        if judge_server_id:
            try:
                judge_server = JudgeServer.objects.get(id=judge_server_id)
            except JudgeServer.DoesNotExist:
                return error_response(u"判题服务器不存在")
            return success_response(JudgesSerializer(judge_server).data)
        judge_server = JudgeServer.objects.all()

        return paginate(request, judge_server, JudgesSerializer)
Пример #45
0
    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)
Пример #46
0
 def post(self, request):
     userId = request.POST.get("userId")
     userName = request.POST.get("userName")
     userPhone = request.POST.get("userPhone")
     userPassword = request.POST.get("userPassword")
     userType = request.POST.get("userType")
     user = User.objects.get(id=userId)
     print userPassword
     if userPassword is not None:
         user.set_password(userPassword)
     user.userName = userName
     user.phone = userPhone
     user.save()
     message = "用户信息修改成功"
     return shortcuts.success_response(message)
Пример #47
0
 def post(self, request):
     problem_id = request.data.get("problem_id", -1)
     try:
         problem = ContestProblem.objects.get(id=problem_id)
     except ContestProblem.DoesNotExist:
         return error_response(u"比赛不存在")
     Problem.objects.create(title=problem.title, description=problem.description,
                            input_description=problem.input_description,
                            output_description=problem.output_description,
                            samples=problem.samples,
                            test_case_id=problem.test_case_id,
                            hint=problem.hint, created_by=problem.created_by,
                            time_limit=problem.time_limit, memory_limit=problem.memory_limit,
                            visible=False, difficulty=-1, source=problem.contest.title)
     return success_response(u"创建成功")
Пример #48
0
    def get(self, request):

        commentId = request.GET["commentId"]
        isShow = request.GET["isShow"]
        commentStick = request.GET["commentStick"]
        commentEssence = request.GET["commentEssence"]
        comment = Comment.objects.get(id=commentId)

        print commentStick
        print commentEssence

        type = 0

        if ('true' == commentStick) and ('true' == commentEssence):
            type = 3
            commentStick = True
            commentEssence = True

        if ('false' == commentStick) and ('true' == commentEssence):
            type = 2
            commentStick = False
            commentEssence = True

        if ('true' == commentStick) and ('false' == commentEssence):
            type = 1
            commentStick = True
            commentEssence = False

        if ('false' == commentStick) and ('false' == commentEssence):
            type = 0
            commentStick = False
            commentEssence = False

        if ('true' == isShow):
            isShow = True
        else:
            isShow = False

        comment.commentType = type
        print type
        comment.save()

        comment.commentStick = commentStick
        comment.commentEssence = commentEssence
        comment.isShow = isShow
        comment.save()
        message = "评论状态修改成功"
        return shortcuts.success_response(message)
Пример #49
0
 def post(self, request):
     serializer = EditBookInfoSerializers(request.data)
     data = serializer.data
     book = BookInfo.objects.get(id=data['id'])
     book.name = data['bookName']
     book.author = data['author']
     book.state = data['state']
     book.type = data['type']
     book.describe = data['describe']
     if "" == data['testimonials']:
         book.testimonials = data['testimonials']
     else:
         book.testimonials = data['testimonials'] + " : "
     book.save()
     message = "书籍修改成功"
     return shortcuts.success_response(message)
Пример #50
0
 def post(self, request):
     """
     开启两步验证
     """
     serializer = TwoFactorAuthCodeSerializer(data=request.data)
     if serializer.is_valid():
         code = serializer.data["code"]
         user = request.user
         if OtpAuth(user.tfa_token).valid_totp(code):
             user.two_factor_auth = True
             user.save()
             return success_response(u"开启两步验证成功")
         else:
             return error_response(u"验证码错误")
     else:
         return serializer_invalid_response(serializer)
Пример #51
0
 def post(self, request):
     serializer = SSOSerializer(data=request.data)
     if serializer.is_valid():
         try:
             user = User.objects.get(auth_token=serializer.data["token"])
             user.auth_token = None
             user.save()
             return success_response({
                 "username": user.username,
                 "admin_type": user.admin_type,
                 "avatar": user.userprofile.avatar
             })
         except User.DoesNotExist:
             return error_response(u"用户不存在")
     else:
         return serializer_invalid_response(serializer)
Пример #52
0
 def post(self, request):
     serializer = SubmissionhareSerializer(data=request.data)
     if serializer.is_valid():
         submission_id = serializer.data["submission_id"]
         try:
             result = _get_submission(submission_id, request.user)
         except Submission.DoesNotExist:
             return error_response(u"提交不存在")
         if not result["can_share"]:
             return error_page(request, u"提交不存在")
         submission = result["submission"]
         submission.shared = not submission.shared
         submission.save()
         return success_response(submission.shared)
     else:
         return serializer_invalid_response(serializer)
Пример #53
0
    def post(self, request):
        serializer = UserRegisterSerializer(data=request.data)
        data = request.data
        phone = request.session.get('phone')

        if serializer.is_valid():
            user = User.objects.create(userName=phone)
            user.set_password(data["password"])
            user.phone = phone
            user.save()
            userProfile = UserProfile(User=user)
            userProfile.save()
            message = "注册成功"
            return shortcuts.success_response(message)
        else:
            message = "请输入正确格式"
            return shortcuts.error_response(message)
Пример #54
0
 def get(sell, request):
     """
     openapi 获取题目内容
     """
     problem_id = request.GET.get("problem_id", None)
     appkey = request.GET.get("appkey", None)
     if not (problem_id and appkey):
         return error_response(u"参数错误")
     try:
         User.objects.get(openapi_appkey=appkey)
     except User.DoesNotExist:
         return error_response(u"appkey无效")
     try:
         problem = Problem.objects.get(id=problem_id, visible=True)
     except Problem.DoesNotExist:
         return error_page(request, u"题目不存在")
     return success_response(OpenAPIProblemSerializer(problem).data)
Пример #55
0
 def get(self, request):
     """
     openapi 获取提交详情
     """
     submission_id = request.GET.get("submission_id", None)
     appkey = request.GET.get("appkey", None)
     if not (submission_id and appkey):
         return error_response(u"参数错误")
     try:
         user = User.objects.get(openapi_appkey=appkey)
     except User.DoesNotExist:
         return error_response(u"appkey无效")
     try:
         submission = Submission.objects.get(id=submission_id, user_id=user.id)
         return success_response(OpenAPISubmissionSerializer(submission).data)
     except Submission.DoesNotExist:
         return error_response(u"提交不存在")
Пример #56
0
 def post(self, request):
     serializer = CreateChapterSerializers(request.data)
     data = serializer.data
     book = BookInfo.objects.get(id=data['bookId'])
     chaptersId = book.chaptersNumber + 1
     book.add_chapters_number()
     bookContent = BooksContent(BookInfo=book,
                                chaptersId=chaptersId,
                                chaptersName=data['chaptersName'],
                                chaptersType=data['chaptersType'],
                                chaptersContent=data['chaptersContent'],
                                chaptersState=data['chaptersState'])
     bookContent.wordNumber = len(data['chaptersContent'])
     bookContent.save()
     print u"章节内容" + data['chaptersContent']
     message = "章节创建成功"
     return shortcuts.success_response(message)
Пример #57
0
    def put(self, request):
        """
        题目编辑json api接口
        ---
        request_serializer: EditProblemSerializer
        response_serializer: ProblemSerializer
        """
        serializer = EditProblemSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            problem = Problem.objects.get(id=data["id"])

            problem.title = data["title"]
            problem.description = data["description"]
            problem.input_description = data["input_description"]
            problem.output_description = data["output_description"]
            problem.test_case_id = data["test_case_id"]
            problem.source = data["source"]
            problem.time_limit = data["time_limit"]
            problem.memory_limit = data["memory_limit"]
            problem.spj = data["spj"]
            problem.spj_language = data["spj_language"]
            problem.spj_code = data["spj_code"]
            problem.spj_version = self._spj_version(data["spj_code"])
            problem.difficulty = data["difficulty"]
            problem.samples = json.dumps(data["samples"])
            problem.hint = data["hint"]
            problem.visible = data["visible"]
            problem.last_update_time = now()

            # 删除原有的标签的对应关系
            problem.tags.remove(*problem.tags.all())
            # 重新添加所有的标签
            for tag in data["tags"]:
                try:
                    tag = ProblemTag.objects.get(name=tag)
                except ProblemTag.DoesNotExist:
                    tag = ProblemTag.objects.create(name=tag)
                problem.tags.add(tag)

            problem.save()

            return success_response(ProblemSerializer(problem).data)
        else:
            return serializer_invalid_response(serializer)
Пример #58
0
 def put(self, request):
     serializer = EditUserProfileSerializer(data=request.data)
     if serializer.is_valid():
         data = serializer.data
         user_profile = request.user.userprofile
         if data["avatar"]:
             user_profile.avatar = data["avatar"]
         user_profile.mood = data["mood"]
         user_profile.hduoj_username = data["hduoj_username"]
         user_profile.bestcoder_username = data["bestcoder_username"]
         user_profile.codeforces_username = data["codeforces_username"]
         user_profile.blog = data["blog"]
         user_profile.school = data["school"]
         user_profile.phone_number = data["phone_number"]
         user_profile.save()
         return success_response(u"修改成功")
     else:
         return serializer_invalid_response(serializer)
Пример #59
0
 def put(self, request):
     """
     删除小组成员的api接口
     ---
     request_serializer: EditGroupMemberSerializer
     """
     serializer = EditGroupMemberSerializer(data=request.data)
     if serializer.is_valid():
         try:
             group = self.get_group(request, serializer.data["group_id"])
         except Group.DoesNotExist:
             return error_response(u"小组不存在")
         user_id_list = serializer.data["members"]
         UserGroupRelation.objects.filter(
             group=group, user__id__in=user_id_list).delete()
         return success_response(u"删除成功")
     else:
         return serializer_invalid_response(serializer)
Пример #60
0
    def post(self, request):
        """
        提交代码
        ---
        request_serializer: CreateSubmissionSerializer
        """
        controller = BucketController(
            user_id=request.user.id,
            redis_conn=redis.Redis(host=settings.REDIS_CACHE["host"],
                                   port=settings.REDIS_CACHE["port"],
                                   db=settings.REDIS_CACHE["db"]),
            default_capacity=settings.TOKEN_BUCKET_DEFAULT_CAPACITY)
        bucket = TokenBucket(fill_rate=settings.TOKEN_BUCKET_FILL_RATE,
                             capacity=settings.TOKEN_BUCKET_DEFAULT_CAPACITY,
                             last_capacity=controller.last_capacity,
                             last_timestamp=controller.last_timestamp)
        if bucket.consume():
            controller.last_capacity -= 1
        else:
            return error_response(u"您提交的频率过快, 请等待%d秒" %
                                  int(bucket.expected_time() + 1))

        serializer = CreateSubmissionSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            try:
                problem = Problem.objects.get(id=data["problem_id"])
            except Problem.DoesNotExist:
                return error_response(u"题目不存在")
            submission = Submission.objects.create(user_id=request.user.id,
                                                   language=int(
                                                       data["language"]),
                                                   code=data["code"],
                                                   problem_id=problem.id)

            try:
                _judge.delay(submission, problem.time_limit,
                             problem.memory_limit, problem.test_case_id)
            except Exception as e:
                logger.error(e)
                return error_response(u"提交判题任务失败")
            return success_response({"submission_id": submission.id})
        else:
            return serializer_invalid_response(serializer)