inital commit 1
This commit is contained in:
commit
db645123c7
196 files changed
+11102
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,2 @@
|
||||
from ._serializers import * # NOQA
|
||||
from .api import * # NOQA
|
||||
@@ -0,0 +1,14 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
|
||||
class UsernameSerializer(serializers.Serializer):
|
||||
id = serializers.IntegerField()
|
||||
username = serializers.CharField()
|
||||
real_name = serializers.SerializerMethodField()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.need_real_name = kwargs.pop("need_real_name", False)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def get_real_name(self, obj):
|
||||
return obj.userprofile.real_name if self.need_real_name else None
|
||||
@@ -0,0 +1,187 @@
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
|
||||
from django.http import HttpResponse, QueryDict
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.generic import View
|
||||
|
||||
logger = logging.getLogger("")
|
||||
|
||||
|
||||
class APIError(Exception):
|
||||
def __init__(self, msg, err=None):
|
||||
self.err = err
|
||||
self.msg = msg
|
||||
super().__init__(err, msg)
|
||||
|
||||
|
||||
class ContentType(object):
|
||||
json_request = "application/json"
|
||||
json_response = "application/json;charset=UTF-8"
|
||||
url_encoded_request = "application/x-www-form-urlencoded"
|
||||
binary_response = "application/octet-stream"
|
||||
|
||||
|
||||
class JSONParser(object):
|
||||
content_type = ContentType.json_request
|
||||
|
||||
@staticmethod
|
||||
def parse(body):
|
||||
return json.loads(body.decode("utf-8"))
|
||||
|
||||
|
||||
class URLEncodedParser(object):
|
||||
content_type = ContentType.url_encoded_request
|
||||
|
||||
@staticmethod
|
||||
def parse(body):
|
||||
return QueryDict(body)
|
||||
|
||||
|
||||
class JSONResponse(object):
|
||||
content_type = ContentType.json_response
|
||||
|
||||
@classmethod
|
||||
def response(cls, data):
|
||||
resp = HttpResponse(json.dumps(data, indent=4), content_type=cls.content_type)
|
||||
resp.data = data
|
||||
return resp
|
||||
|
||||
|
||||
class APIView(View):
|
||||
"""
|
||||
Django view的父类, 和django-rest-framework的用法基本一致
|
||||
- request.data获取解析之后的json或者urlencoded数据, dict类型
|
||||
- self.success, self.error和self.invalid_serializer可以根据业需求修改,
|
||||
写到父类中是为了不同的人开发写法统一,不再使用自己的success/error格式
|
||||
- self.response 返回一个django HttpResponse, 具体在self.response_class中实现
|
||||
- parse请求的类需要定义在request_parser中, 目前只支持json和urlencoded的类型, 用来解析请求的数据
|
||||
"""
|
||||
request_parsers = (JSONParser, URLEncodedParser)
|
||||
response_class = JSONResponse
|
||||
|
||||
def _get_request_data(self, request):
|
||||
if request.method not in ["GET", "DELETE"]:
|
||||
body = request.body
|
||||
content_type = request.META.get("CONTENT_TYPE")
|
||||
if not content_type:
|
||||
raise ValueError("content_type is required")
|
||||
for parser in self.request_parsers:
|
||||
if content_type.startswith(parser.content_type):
|
||||
break
|
||||
# else means the for loop is not interrupted by break
|
||||
else:
|
||||
raise ValueError("unknown content_type '%s'" % content_type)
|
||||
if body:
|
||||
return parser.parse(body)
|
||||
return {}
|
||||
return request.GET
|
||||
|
||||
def response(self, data):
|
||||
return self.response_class.response(data)
|
||||
|
||||
def success(self, data=None):
|
||||
return self.response({"error": None, "data": data})
|
||||
|
||||
def error(self, msg="error", err="error"):
|
||||
return self.response({"error": err, "data": msg})
|
||||
|
||||
def extract_errors(self, errors, key="field"):
|
||||
if isinstance(errors, dict):
|
||||
if not errors:
|
||||
return key, "Invalid field"
|
||||
key = list(errors.keys())[0]
|
||||
return self.extract_errors(errors.pop(key), key)
|
||||
elif isinstance(errors, list):
|
||||
return self.extract_errors(errors[0], key)
|
||||
|
||||
return key, errors
|
||||
|
||||
def invalid_serializer(self, serializer):
|
||||
key, error = self.extract_errors(serializer.errors)
|
||||
if key == "non_field_errors":
|
||||
msg = error
|
||||
else:
|
||||
msg = f"{key}: {error}"
|
||||
return self.error(err=f"invalid-{key}", msg=msg)
|
||||
|
||||
def server_error(self):
|
||||
return self.error(err="server-error", msg="server error")
|
||||
|
||||
def paginate_data(self, request, query_set, object_serializer=None):
|
||||
"""
|
||||
:param request: django的request
|
||||
:param query_set: django model的query set或者其他list like objects
|
||||
:param object_serializer: 用来序列化query set, 如果为None, 则直接对query set切片
|
||||
:return:
|
||||
"""
|
||||
try:
|
||||
limit = int(request.GET.get("limit", "10"))
|
||||
except ValueError:
|
||||
limit = 10
|
||||
if limit < 0 or limit > 250:
|
||||
limit = 10
|
||||
try:
|
||||
offset = int(request.GET.get("offset", "0"))
|
||||
except ValueError:
|
||||
offset = 0
|
||||
if offset < 0:
|
||||
offset = 0
|
||||
results = query_set[offset:offset + limit]
|
||||
if object_serializer:
|
||||
count = query_set.count()
|
||||
results = object_serializer(results, many=True).data
|
||||
else:
|
||||
count = query_set.count()
|
||||
data = {"results": results,
|
||||
"total": count}
|
||||
return data
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if self.request_parsers:
|
||||
try:
|
||||
request.data = self._get_request_data(self.request)
|
||||
except ValueError as e:
|
||||
return self.error(err="invalid-request", msg=str(e))
|
||||
try:
|
||||
return super(APIView, self).dispatch(request, *args, **kwargs)
|
||||
except APIError as e:
|
||||
ret = {"msg": e.msg}
|
||||
if e.err:
|
||||
ret["err"] = e.err
|
||||
return self.error(**ret)
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
return self.server_error()
|
||||
|
||||
|
||||
class CSRFExemptAPIView(APIView):
|
||||
@method_decorator(csrf_exempt)
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
return super(CSRFExemptAPIView, self).dispatch(request, *args, **kwargs)
|
||||
|
||||
|
||||
def validate_serializer(serializer):
|
||||
"""
|
||||
@validate_serializer(TestSerializer)
|
||||
def post(self, request):
|
||||
return self.success(request.data)
|
||||
"""
|
||||
def validate(view_method):
|
||||
@functools.wraps(view_method)
|
||||
def handle(*args, **kwargs):
|
||||
self = args[0]
|
||||
request = args[1]
|
||||
s = serializer(data=request.data)
|
||||
if s.is_valid():
|
||||
request.data = s.data
|
||||
request.serializer = s
|
||||
return view_method(*args, **kwargs)
|
||||
else:
|
||||
return self.invalid_serializer(s)
|
||||
|
||||
return handle
|
||||
|
||||
return validate
|
||||
@@ -0,0 +1,40 @@
|
||||
from django.urls import reverse
|
||||
from django.test.testcases import TestCase
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from account.models import AdminType, ProblemPermission, User, UserProfile
|
||||
|
||||
|
||||
class APITestCase(TestCase):
|
||||
client_class = APIClient
|
||||
|
||||
def create_user(self, username, password, admin_type=AdminType.REGULAR_USER, login=True,
|
||||
problem_permission=ProblemPermission.NONE):
|
||||
user = User.objects.create(username=username, admin_type=admin_type, problem_permission=problem_permission)
|
||||
user.set_password(password)
|
||||
UserProfile.objects.create(user=user)
|
||||
user.save()
|
||||
if login:
|
||||
self.client.login(username=username, password=password)
|
||||
return user
|
||||
|
||||
def create_admin(self, username="admin", password="admin", login=True):
|
||||
return self.create_user(username=username, password=password, admin_type=AdminType.ADMIN,
|
||||
problem_permission=ProblemPermission.OWN,
|
||||
login=login)
|
||||
|
||||
def create_super_admin(self, username="root", password="root", login=True):
|
||||
return self.create_user(username=username, password=password, admin_type=AdminType.SUPER_ADMIN,
|
||||
problem_permission=ProblemPermission.ALL, login=login)
|
||||
|
||||
def reverse(self, url_name, *args, **kwargs):
|
||||
return reverse(url_name, *args, **kwargs)
|
||||
|
||||
def assertSuccess(self, response):
|
||||
if not response.data["error"] is None:
|
||||
raise AssertionError("response with errors, response: " + str(response.data))
|
||||
|
||||
def assertFailed(self, response, msg=None):
|
||||
self.assertTrue(response.data["error"] is not None)
|
||||
if msg:
|
||||
self.assertEqual(response.data["data"], msg)
|
||||
@@ -0,0 +1,27 @@
|
||||
from django.core.cache import cache, caches # noqa
|
||||
from django.conf import settings # noqa
|
||||
|
||||
from django_redis.cache import RedisCache
|
||||
from django_redis.client.default import DefaultClient
|
||||
|
||||
|
||||
class MyRedisClient(DefaultClient):
|
||||
def __getattr__(self, item):
|
||||
client = self.get_client(write=True)
|
||||
return getattr(client, item)
|
||||
|
||||
def redis_incr(self, key, count=1):
|
||||
"""
|
||||
django 默认的 incr 在 key 不存在时候会抛异常
|
||||
"""
|
||||
client = self.get_client(write=True)
|
||||
return client.incr(key, count)
|
||||
|
||||
|
||||
class MyRedisCache(RedisCache):
|
||||
def __init__(self, server, params):
|
||||
super().__init__(server, params)
|
||||
self._client_cls = MyRedisClient
|
||||
|
||||
def __getattr__(self, item):
|
||||
return getattr(self.client, item)
|
||||
Binary file not shown.
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
Copyright 2013 TY<[email protected]>
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import random
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
class Captcha(object):
|
||||
def __init__(self, request):
|
||||
"""
|
||||
初始化,设置各种属性
|
||||
"""
|
||||
self.django_request = request
|
||||
self.session_key = "_django_captcha_key"
|
||||
self.captcha_expires_time = "_django_captcha_expires_time"
|
||||
|
||||
# 验证码图片尺寸
|
||||
self.img_width = 90
|
||||
self.img_height = 30
|
||||
|
||||
def _get_font_size(self, code):
|
||||
"""
|
||||
将图片高度的80%作为字体大小
|
||||
"""
|
||||
s1 = int(self.img_height * 0.8)
|
||||
s2 = int(self.img_width / len(code))
|
||||
return int(min((s1, s2)) + max((s1, s2)) * 0.05)
|
||||
|
||||
def _set_answer(self, answer):
|
||||
"""
|
||||
设置答案和过期时间
|
||||
"""
|
||||
self.django_request.session[self.session_key] = str(answer)
|
||||
self.django_request.session[self.captcha_expires_time] = time.time() + 60
|
||||
|
||||
def _make_code(self):
|
||||
"""
|
||||
生成随机数或随机字符串
|
||||
"""
|
||||
string = random.sample("abcdefghkmnpqrstuvwxyzABCDEFGHGKMNOPQRSTUVWXYZ23456789", 4)
|
||||
self._set_answer("".join(string))
|
||||
return string
|
||||
|
||||
def get(self):
|
||||
"""
|
||||
生成验证码图片,返回值为图片的bytes
|
||||
"""
|
||||
background = (random.randrange(200, 255), random.randrange(200, 255), random.randrange(200, 255))
|
||||
code_color = (random.randrange(0, 50), random.randrange(0, 50), random.randrange(0, 50), 255)
|
||||
|
||||
font_path = os.path.join(os.path.normpath(os.path.dirname(__file__)), "timesbi.ttf")
|
||||
|
||||
image = Image.new("RGB", (self.img_width, self.img_height), background)
|
||||
code = self._make_code()
|
||||
font_size = self._get_font_size(code)
|
||||
draw = ImageDraw.Draw(image)
|
||||
|
||||
# x是第一个字母的x坐标
|
||||
x = random.randrange(int(font_size * 0.3), int(font_size * 0.5))
|
||||
|
||||
for i in code:
|
||||
# 字符y坐标
|
||||
y = random.randrange(1, 7)
|
||||
# 随机字符大小
|
||||
font = ImageFont.truetype(font_path.replace("\\", "/"), font_size + random.randrange(-3, 7))
|
||||
draw.text((x, y), i, font=font, fill=code_color)
|
||||
# 随机化字符之间的距离 字符粘连可以降低识别率
|
||||
x += font_size * random.randrange(6, 8) / 10
|
||||
|
||||
self.django_request.session[self.session_key] = "".join(code)
|
||||
return image
|
||||
|
||||
def check(self, code):
|
||||
"""
|
||||
检查用户输入的验证码是否正确
|
||||
"""
|
||||
_code = self.django_request.session.get(self.session_key) or ""
|
||||
if not _code:
|
||||
return False
|
||||
expires_time = self.django_request.session.get(self.captcha_expires_time) or 0
|
||||
# 注意 如果验证之后不清除之前的验证码的话 可能会造成重复验证的现象
|
||||
del self.django_request.session[self.session_key]
|
||||
del self.django_request.session[self.captcha_expires_time]
|
||||
if _code.lower() == str(code).lower() and time.time() < expires_time:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
Binary file not shown.
@@ -0,0 +1,8 @@
|
||||
from . import Captcha
|
||||
from ..api import APIView
|
||||
from ..shortcuts import img2base64
|
||||
|
||||
|
||||
class CaptchaAPIView(APIView):
|
||||
def get(self, request):
|
||||
return self.success(img2base64(Captcha(request).get()))
|
||||
@@ -0,0 +1,36 @@
|
||||
class Choices:
|
||||
@classmethod
|
||||
def choices(cls):
|
||||
d = cls.__dict__
|
||||
return [d[item] for item in d.keys() if not item.startswith("__")]
|
||||
|
||||
|
||||
class ContestType:
|
||||
PUBLIC_CONTEST = "Public"
|
||||
PASSWORD_PROTECTED_CONTEST = "Password Protected"
|
||||
|
||||
|
||||
class ContestStatus:
|
||||
CONTEST_NOT_START = "1"
|
||||
CONTEST_ENDED = "-1"
|
||||
CONTEST_UNDERWAY = "0"
|
||||
|
||||
|
||||
class ContestRuleType(Choices):
|
||||
ACM = "ACM"
|
||||
OI = "OI"
|
||||
|
||||
|
||||
class CacheKey:
|
||||
waiting_queue = "waiting_queue"
|
||||
contest_rank_cache = "contest_rank_cache"
|
||||
website_config = "website_config"
|
||||
|
||||
|
||||
class Difficulty(Choices):
|
||||
LOW = "Low"
|
||||
MID = "Mid"
|
||||
HIGH = "High"
|
||||
|
||||
|
||||
CONTEST_PASSWORD_SESSION_KEY = "contest_password"
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,44 @@
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
from account.models import AdminType, ProblemPermission, User, UserProfile
|
||||
from utils.shortcuts import rand_str # NOQA
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("--username", type=str)
|
||||
parser.add_argument("--password", type=str)
|
||||
parser.add_argument("--action", type=str)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
username = options["username"]
|
||||
password = options["password"]
|
||||
action = options["action"]
|
||||
|
||||
if not(username and password and action):
|
||||
self.stdout.write(self.style.ERROR("Invalid args"))
|
||||
exit(1)
|
||||
|
||||
if action == "create_super_admin":
|
||||
if User.objects.filter(id=1).exists():
|
||||
self.stdout.write(self.style.SUCCESS(f"User {username} exists, operation ignored"))
|
||||
exit()
|
||||
|
||||
user = User.objects.create(username=username, admin_type=AdminType.SUPER_ADMIN,
|
||||
problem_permission=ProblemPermission.ALL)
|
||||
user.set_password(password)
|
||||
user.save()
|
||||
UserProfile.objects.create(user=user)
|
||||
|
||||
self.stdout.write(self.style.SUCCESS("User created"))
|
||||
elif action == "reset":
|
||||
try:
|
||||
user = User.objects.get(username=username)
|
||||
user.set_password(password)
|
||||
user.save()
|
||||
self.stdout.write(self.style.SUCCESS("Password is rested"))
|
||||
except User.DoesNotExist:
|
||||
self.stdout.write(self.style.ERROR(f"User {username} doesnot exist, operation ignored"))
|
||||
exit(1)
|
||||
else:
|
||||
raise ValueError("Invalid action")
|
||||
@@ -0,0 +1,212 @@
|
||||
# flake8: noqa
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import json
|
||||
import django
|
||||
import hashlib
|
||||
from json.decoder import JSONDecodeError
|
||||
|
||||
sys.path.append("../")
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oj.settings")
|
||||
django.setup()
|
||||
from django.conf import settings
|
||||
from account.models import User, UserProfile, AdminType, ProblemPermission
|
||||
from problem.models import Problem, ProblemTag, ProblemDifficulty, ProblemRuleType
|
||||
|
||||
admin_type_map = {
|
||||
0: AdminType.REGULAR_USER,
|
||||
1: AdminType.ADMIN,
|
||||
2: AdminType.SUPER_ADMIN
|
||||
}
|
||||
languages_map = {
|
||||
1: "C",
|
||||
2: "C++",
|
||||
3: "Java"
|
||||
}
|
||||
email_regex = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
|
||||
|
||||
# pk -> name
|
||||
tags = {}
|
||||
# pk -> user obj
|
||||
users = {}
|
||||
|
||||
problems = []
|
||||
|
||||
|
||||
def get_input_result():
|
||||
while True:
|
||||
resp = input()
|
||||
if resp not in ["yes", "no"]:
|
||||
print("Please input yes or no")
|
||||
continue
|
||||
return resp == "yes"
|
||||
|
||||
|
||||
def set_problem_display_id_prefix():
|
||||
while True:
|
||||
print("Please input a prefix which will be used in all the imported problem's displayID")
|
||||
print(
|
||||
"For example, if your input is 'old'(no quote), the problems' display id will be old1, old2, old3..\ninput:",
|
||||
end="")
|
||||
resp = input()
|
||||
if resp.strip():
|
||||
return resp.strip()
|
||||
else:
|
||||
print("Empty prefix detected, sure to do that? (yes/no)")
|
||||
if get_input_result():
|
||||
return ""
|
||||
|
||||
|
||||
def get_stripped_output_md5(test_case_id, output_name):
|
||||
output_path = os.path.join(settings.TEST_CASE_DIR, test_case_id, output_name)
|
||||
with open(output_path, 'r') as f:
|
||||
return hashlib.md5(f.read().rstrip().encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def get_test_case_score(test_case_id):
|
||||
info_path = os.path.join(settings.TEST_CASE_DIR, test_case_id, "info")
|
||||
if not os.path.exists(info_path):
|
||||
return []
|
||||
with open(info_path, "r") as info_file:
|
||||
info = json.load(info_file)
|
||||
test_case_score = []
|
||||
need_rewrite = True
|
||||
for test_case in info["test_cases"].values():
|
||||
if test_case.__contains__("stripped_output_md5"):
|
||||
need_rewrite = False
|
||||
elif test_case.__contains__("striped_output_md5"):
|
||||
test_case["stripped_output_md5"] = test_case.pop("striped_output_md5")
|
||||
else:
|
||||
test_case["stripped_output_md5"] = get_stripped_output_md5(test_case_id, test_case["output_name"])
|
||||
test_case_score.append({"input_name": test_case["input_name"],
|
||||
"output_name": test_case.get("output_name", "-"),
|
||||
"score": 0})
|
||||
if need_rewrite:
|
||||
with open(info_path, "w") as f:
|
||||
f.write(json.dumps(info))
|
||||
return test_case_score
|
||||
|
||||
|
||||
def import_users():
|
||||
i = 0
|
||||
print("Find %d users in old data." % len(users.keys()))
|
||||
print("import users now? (yes/no)")
|
||||
if get_input_result():
|
||||
for data in users.values():
|
||||
if not email_regex.match(data["email"]):
|
||||
print("%s will not be created due to invalid email: %s" % (data["username"], data["email"]))
|
||||
continue
|
||||
data["username"] = data["username"].lower()
|
||||
user, created = User.objects.get_or_create(username=data["username"])
|
||||
if not created:
|
||||
print("%s already exists, omitted" % user.username)
|
||||
continue
|
||||
user.password = data["password"]
|
||||
user.email = data["email"]
|
||||
admin_type = admin_type_map[data["admin_type"]]
|
||||
user.admin_type = admin_type
|
||||
if admin_type == AdminType.ADMIN:
|
||||
user.problem_permission = ProblemPermission.OWN
|
||||
elif admin_type == AdminType.SUPER_ADMIN:
|
||||
user.problem_permission = ProblemPermission.ALL
|
||||
user.save()
|
||||
UserProfile.objects.create(user=user, real_name=data["real_name"])
|
||||
i += 1
|
||||
print("%s imported successfully" % user.username)
|
||||
print("%d users have successfully imported\n" % i)
|
||||
|
||||
|
||||
def import_tags():
|
||||
i = 0
|
||||
print("\nFind these tags in old data:")
|
||||
print(", ".join(tags.values()), '\n')
|
||||
print("import tags now? (yes/no)")
|
||||
if get_input_result():
|
||||
for tagname in tags.values():
|
||||
tag, created = ProblemTag.objects.get_or_create(name=tagname)
|
||||
if not created:
|
||||
print("%s already exists, omitted" % tagname)
|
||||
else:
|
||||
print("%s tag created successfully" % tagname)
|
||||
i += 1
|
||||
print("%d tags have successfully imported\n" % i)
|
||||
else:
|
||||
print("Problem depends on problem_tags and users, exit..")
|
||||
exit(1)
|
||||
|
||||
|
||||
def import_problems():
|
||||
i = 0
|
||||
print("\nFind %d problems in old data" % len(problems))
|
||||
prefix = set_problem_display_id_prefix()
|
||||
print("import problems using prefix: %s? (yes/no)" % prefix)
|
||||
if get_input_result():
|
||||
default_creator = User.objects.first()
|
||||
for data in problems:
|
||||
data["_id"] = prefix + str(data.pop("id"))
|
||||
if Problem.objects.filter(_id=data["_id"]).exists():
|
||||
print("%s has the same display_id with the db problem" % data["title"])
|
||||
continue
|
||||
try:
|
||||
creator_id = \
|
||||
User.objects.filter(username=users[data["created_by"]]["username"]).values_list("id", flat=True)[0]
|
||||
except (User.DoesNotExist, IndexError):
|
||||
print("The origin creator does not exist, set it to default_creator")
|
||||
creator_id = default_creator.id
|
||||
data["created_by_id"] = creator_id
|
||||
data.pop("created_by")
|
||||
data["difficulty"] = ProblemDifficulty.Mid
|
||||
if data["spj_language"]:
|
||||
data["spj_language"] = languages_map[data["spj_language"]]
|
||||
data["samples"] = json.loads(data["samples"])
|
||||
data["languages"] = ["C", "C++"]
|
||||
test_case_score = get_test_case_score(data["test_case_id"])
|
||||
if not test_case_score:
|
||||
print("%s test_case files don't exist, omitted" % data["title"])
|
||||
continue
|
||||
data["test_case_score"] = test_case_score
|
||||
data["rule_type"] = ProblemRuleType.ACM
|
||||
data["template"] = {}
|
||||
data.pop("total_submit_number")
|
||||
data.pop("total_accepted_number")
|
||||
tag_ids = data.pop("tags")
|
||||
problem = Problem.objects.create(**data)
|
||||
problem.create_time = data["create_time"]
|
||||
problem.save()
|
||||
for tag_id in tag_ids:
|
||||
tag, _ = ProblemTag.objects.get_or_create(name=tags[tag_id])
|
||||
problem.tags.add(tag)
|
||||
i += 1
|
||||
print("%s imported successfully" % data["title"])
|
||||
print("%d problems have successfully imported" % i)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) == 1:
|
||||
print("Usage: python3 %s [old_data_path]" % sys.argv[0])
|
||||
exit(0)
|
||||
data_path = sys.argv[1]
|
||||
if not os.path.isfile(data_path):
|
||||
print("Data file does not exist")
|
||||
exit(1)
|
||||
|
||||
try:
|
||||
with open(data_path, "r") as data_file:
|
||||
old_data = json.load(data_file)
|
||||
except JSONDecodeError:
|
||||
print("Data file format error, ensure it's a valid json file!")
|
||||
exit(1)
|
||||
print("Read old data successfully.\n")
|
||||
|
||||
for obj in old_data:
|
||||
if obj["model"] == "problem.problemtag":
|
||||
tags[obj["pk"]] = obj["fields"]["name"]
|
||||
elif obj["model"] == "account.user":
|
||||
users[obj["pk"]] = obj["fields"]
|
||||
elif obj["model"] == "problem.problem":
|
||||
obj["fields"]["id"] = obj["pk"]
|
||||
problems.append(obj["fields"])
|
||||
import_users()
|
||||
import_tags()
|
||||
import_problems()
|
||||
@@ -0,0 +1,10 @@
|
||||
from django.db.models import JSONField # NOQA
|
||||
from django.db import models
|
||||
|
||||
from utils.xss_filter import XSSHtml
|
||||
|
||||
|
||||
class RichTextField(models.TextField):
|
||||
def get_prep_value(self, value):
|
||||
with XSSHtml() as parser:
|
||||
return parser.clean(value or "")
|
||||
@@ -0,0 +1,42 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from options.options import SysOptions
|
||||
|
||||
|
||||
class InvalidLanguage(serializers.ValidationError):
|
||||
def __init__(self, name):
|
||||
super().__init__(detail=f"{name} is not a valid language")
|
||||
|
||||
|
||||
class LanguageNameChoiceField(serializers.CharField):
|
||||
def to_internal_value(self, data):
|
||||
data = super().to_internal_value(data)
|
||||
if data and data not in SysOptions.language_names:
|
||||
raise InvalidLanguage(data)
|
||||
return data
|
||||
|
||||
|
||||
class SPJLanguageNameChoiceField(serializers.CharField):
|
||||
def to_internal_value(self, data):
|
||||
data = super().to_internal_value(data)
|
||||
if data and data not in SysOptions.spj_language_names:
|
||||
raise InvalidLanguage(data)
|
||||
return data
|
||||
|
||||
|
||||
class LanguageNameMultiChoiceField(serializers.ListField):
|
||||
def to_internal_value(self, data):
|
||||
data = super().to_internal_value(data)
|
||||
for item in data:
|
||||
if item not in SysOptions.language_names:
|
||||
raise InvalidLanguage(item)
|
||||
return data
|
||||
|
||||
|
||||
class SPJLanguageNameMultiChoiceField(serializers.ListField):
|
||||
def to_internal_value(self, data):
|
||||
data = super().to_internal_value(data)
|
||||
for item in data:
|
||||
if item not in SysOptions.spj_language_names:
|
||||
raise InvalidLanguage(item)
|
||||
return data
|
||||
@@ -0,0 +1,94 @@
|
||||
import os
|
||||
import re
|
||||
import datetime
|
||||
import random
|
||||
from base64 import b64encode
|
||||
from io import BytesIO
|
||||
|
||||
from django.utils.crypto import get_random_string
|
||||
from envelopes import Envelope
|
||||
|
||||
|
||||
def rand_str(length=32, type="lower_hex"):
|
||||
"""
|
||||
生成指定长度的随机字符串或者数字, 可以用于密钥等安全场景
|
||||
:param length: 字符串或者数字的长度
|
||||
:param type: str 代表随机字符串,num 代表随机数字
|
||||
:return: 字符串
|
||||
"""
|
||||
if type == "str":
|
||||
return get_random_string(length, allowed_chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
|
||||
elif type == "lower_str":
|
||||
return get_random_string(length, allowed_chars="abcdefghijklmnopqrstuvwxyz0123456789")
|
||||
elif type == "lower_hex":
|
||||
return random.choice("123456789abcdef") + get_random_string(length - 1, allowed_chars="0123456789abcdef")
|
||||
else:
|
||||
return random.choice("123456789") + get_random_string(length - 1, allowed_chars="0123456789")
|
||||
|
||||
|
||||
def build_query_string(kv_data, ignore_none=True):
|
||||
# {"a": 1, "b": "test"} -> "?a=1&b=test"
|
||||
query_string = ""
|
||||
for k, v in kv_data.items():
|
||||
if ignore_none is True and kv_data[k] is None:
|
||||
continue
|
||||
if query_string != "":
|
||||
query_string += "&"
|
||||
else:
|
||||
query_string = "?"
|
||||
query_string += (k + "=" + str(v))
|
||||
return query_string
|
||||
|
||||
|
||||
def img2base64(img):
|
||||
with BytesIO() as buf:
|
||||
img.save(buf, "gif")
|
||||
buf_str = buf.getvalue()
|
||||
img_prefix = "data:image/png;base64,"
|
||||
b64_str = img_prefix + b64encode(buf_str).decode("utf-8")
|
||||
return b64_str
|
||||
|
||||
|
||||
def datetime2str(value, format="iso-8601"):
|
||||
if format.lower() == "iso-8601":
|
||||
value = value.isoformat()
|
||||
if value.endswith("+00:00"):
|
||||
value = value[:-6] + "Z"
|
||||
return value
|
||||
return value.strftime(format)
|
||||
|
||||
|
||||
def timestamp2utcstr(value):
|
||||
return datetime.datetime.utcfromtimestamp(value).isoformat()
|
||||
|
||||
|
||||
def natural_sort_key(s, _nsre=re.compile(r"(\d+)")):
|
||||
return [int(text) if text.isdigit() else text.lower()
|
||||
for text in re.split(_nsre, s)]
|
||||
|
||||
|
||||
def send_email(smtp_config, from_name, to_email, to_name, subject, content):
|
||||
envelope = Envelope(from_addr=(smtp_config["email"], from_name),
|
||||
to_addr=(to_email, to_name),
|
||||
subject=subject,
|
||||
html_body=content)
|
||||
return envelope.send(smtp_config["server"],
|
||||
login=smtp_config["email"],
|
||||
password=smtp_config["password"],
|
||||
port=smtp_config["port"],
|
||||
tls=smtp_config["tls"])
|
||||
|
||||
|
||||
def get_env(name, default=""):
|
||||
return os.environ.get(name, default)
|
||||
|
||||
|
||||
def DRAMATIQ_WORKER_ARGS(time_limit=3600_000, max_retries=0, max_age=7200_000):
|
||||
return {"max_retries": max_retries, "time_limit": time_limit, "max_age": max_age}
|
||||
|
||||
|
||||
def check_is_id(value):
|
||||
try:
|
||||
return int(value) > 0
|
||||
except Exception:
|
||||
return False
|
||||
@@ -0,0 +1,13 @@
|
||||
import os
|
||||
import dramatiq
|
||||
|
||||
from utils.shortcuts import DRAMATIQ_WORKER_ARGS
|
||||
|
||||
|
||||
@dramatiq.actor(**DRAMATIQ_WORKER_ARGS())
|
||||
def delete_files(*args):
|
||||
for item in args:
|
||||
try:
|
||||
os.remove(item)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,72 @@
|
||||
import time
|
||||
|
||||
|
||||
class TokenBucket:
|
||||
"""
|
||||
注意:对于单个key的操作不是线程安全的
|
||||
"""
|
||||
def __init__(self, key, capacity, fill_rate, default_capacity, redis_conn):
|
||||
"""
|
||||
:param capacity: 最大容量
|
||||
:param fill_rate: 填充速度/每秒
|
||||
:param default_capacity: 初始容量
|
||||
:param redis_conn: redis connection
|
||||
"""
|
||||
self._key = key
|
||||
self._capacity = capacity
|
||||
self._fill_rate = fill_rate
|
||||
self._default_capacity = default_capacity
|
||||
self._redis_conn = redis_conn
|
||||
|
||||
self._last_capacity_key = "last_capacity"
|
||||
self._last_timestamp_key = "last_timestamp"
|
||||
|
||||
def _init_key(self):
|
||||
self._last_capacity = self._default_capacity
|
||||
now = time.time()
|
||||
self._last_timestamp = now
|
||||
return self._default_capacity, now
|
||||
|
||||
@property
|
||||
def _last_capacity(self):
|
||||
last_capacity = self._redis_conn.hget(self._key, self._last_capacity_key)
|
||||
if last_capacity is None:
|
||||
return self._init_key()[0]
|
||||
else:
|
||||
return float(last_capacity)
|
||||
|
||||
@_last_capacity.setter
|
||||
def _last_capacity(self, value):
|
||||
self._redis_conn.hset(self._key, self._last_capacity_key, value)
|
||||
|
||||
@property
|
||||
def _last_timestamp(self):
|
||||
return float(self._redis_conn.hget(self._key, self._last_timestamp_key))
|
||||
|
||||
@_last_timestamp.setter
|
||||
def _last_timestamp(self, value):
|
||||
self._redis_conn.hset(self._key, self._last_timestamp_key, value)
|
||||
|
||||
def _try_to_fill(self, now):
|
||||
delta = self._fill_rate * (now - self._last_timestamp)
|
||||
return min(self._last_capacity + delta, self._capacity)
|
||||
|
||||
def consume(self, num=1):
|
||||
"""
|
||||
消耗 num 个 token,返回是否成功
|
||||
:param num:
|
||||
:return: result: bool, wait_time: float
|
||||
"""
|
||||
# print("capacity ", self.fill(time.time()))
|
||||
if self._last_capacity >= num:
|
||||
self._last_capacity -= num
|
||||
return True, 0
|
||||
else:
|
||||
now = time.time()
|
||||
cur_num = self._try_to_fill(now)
|
||||
if cur_num >= num:
|
||||
self._last_capacity = cur_num - num
|
||||
self._last_timestamp = now
|
||||
return True, 0
|
||||
else:
|
||||
return False, (num - cur_num) / self._fill_rate
|
||||
@@ -0,0 +1,8 @@
|
||||
from django.conf.urls import url
|
||||
|
||||
from .views import SimditorImageUploadAPIView, SimditorFileUploadAPIView
|
||||
|
||||
urlpatterns = [
|
||||
url(r"^upload_image/?$", SimditorImageUploadAPIView.as_view(), name="upload_image"),
|
||||
url(r"^upload_file/?$", SimditorFileUploadAPIView.as_view(), name="upload_file")
|
||||
]
|
||||
@@ -0,0 +1,75 @@
|
||||
import os
|
||||
from django.conf import settings
|
||||
from account.serializers import ImageUploadForm, FileUploadForm
|
||||
from utils.shortcuts import rand_str
|
||||
from utils.api import CSRFExemptAPIView
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SimditorImageUploadAPIView(CSRFExemptAPIView):
|
||||
request_parsers = ()
|
||||
|
||||
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": False,
|
||||
"msg": "Upload Error",
|
||||
"file_path": ""})
|
||||
return self.response({
|
||||
"success": True,
|
||||
"msg": "Success",
|
||||
"file_path": f"{settings.UPLOAD_PREFIX}/{img_name}"})
|
||||
|
||||
|
||||
class SimditorFileUploadAPIView(CSRFExemptAPIView):
|
||||
request_parsers = ()
|
||||
|
||||
def post(self, request):
|
||||
form = FileUploadForm(request.POST, request.FILES)
|
||||
if form.is_valid():
|
||||
file = form.cleaned_data["file"]
|
||||
else:
|
||||
return self.response({
|
||||
"success": False,
|
||||
"msg": "Upload failed"
|
||||
})
|
||||
|
||||
suffix = os.path.splitext(file.name)[-1].lower()
|
||||
file_name = rand_str(10) + suffix
|
||||
try:
|
||||
with open(os.path.join(settings.UPLOAD_DIR, file_name), "wb") as f:
|
||||
for chunk in file:
|
||||
f.write(chunk)
|
||||
except IOError as e:
|
||||
logger.error(e)
|
||||
return self.response({
|
||||
"success": False,
|
||||
"msg": "Upload Error"})
|
||||
return self.response({
|
||||
"success": True,
|
||||
"msg": "Success",
|
||||
"file_path": f"{settings.UPLOAD_PREFIX}/{file_name}",
|
||||
"file_name": file.name})
|
||||
@@ -0,0 +1,208 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Python 富文本XSS过滤类
|
||||
@package XssHtml
|
||||
@version 0.1
|
||||
@link http://phith0n.github.io/python-xss-filter
|
||||
@since 20150407
|
||||
@copyright (c) Phithon All Rights Reserved
|
||||
|
||||
Based on native Python module HTMLParser purifier of HTML, To Clear all javascript in html
|
||||
You can use it in all python web framework
|
||||
Written by Phithon <[email protected]> in 2015 and placed in the public domain.
|
||||
phithon <[email protected]> 编写于20150407
|
||||
From: XDSEC <www.xdsec.org> & 离别歌 <www.leavesongs.com>
|
||||
GitHub Pages: https://github.com/phith0n/python-xss-filter
|
||||
Usage:
|
||||
parser = XssHtml()
|
||||
parser.feed('<html code>')
|
||||
parser.close()
|
||||
html = parser.getHtml()
|
||||
print html
|
||||
|
||||
Requirements
|
||||
Python 2.6+ or 3.2+
|
||||
Cannot defense xss in browser which is belowed IE7
|
||||
浏览器版本:IE7+ 或其他浏览器,无法防御IE6及以下版本浏览器中的XSS
|
||||
"""
|
||||
import re
|
||||
import copy
|
||||
from html.parser import HTMLParser
|
||||
|
||||
|
||||
class XSSHtml(HTMLParser):
|
||||
allow_tags = ['a', 'img', 'br', 'strong', 'b', 'code', 'pre',
|
||||
'p', 'div', 'em', 'span', 'h1', 'h2', 'h3', 'h4',
|
||||
'h5', 'h6', 'blockquote', 'ul', 'ol', 'tr', 'th', 'td',
|
||||
'hr', 'li', 'u', 'embed', 's', 'table', 'thead', 'tbody',
|
||||
'caption', 'small', 'q', 'sup', 'sub', 'font']
|
||||
common_attrs = ["style", "class", "name"]
|
||||
nonend_tags = ["img", "hr", "br", "embed"]
|
||||
tags_own_attrs = {
|
||||
"img": ["src", "width", "height", "alt", "align"],
|
||||
"a": ["href", "target", "rel", "title"],
|
||||
"embed": ["src", "width", "height", "type", "allowfullscreen", "loop", "play", "wmode", "menu"],
|
||||
"table": ["border", "cellpadding", "cellspacing"],
|
||||
"font": ["color"]
|
||||
}
|
||||
|
||||
def __init__(self, allows=[]):
|
||||
HTMLParser.__init__(self)
|
||||
self.allow_tags = allows if allows else self.allow_tags
|
||||
self.result = []
|
||||
self.start = []
|
||||
self.data = []
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
super().close()
|
||||
|
||||
def clean(self, content):
|
||||
self.feed(content)
|
||||
return self.get_html()
|
||||
|
||||
def get_html(self):
|
||||
"""
|
||||
Get the safe html code
|
||||
"""
|
||||
for i in range(0, len(self.result)):
|
||||
if self.result[i].strip('\n'):
|
||||
self.data.append(self.result[i])
|
||||
return ''.join(self.data)
|
||||
|
||||
def handle_startendtag(self, tag, attrs):
|
||||
self.handle_starttag(tag, attrs)
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag not in self.allow_tags:
|
||||
return
|
||||
end_diagonal = ' /' if tag in self.nonend_tags else ''
|
||||
if not end_diagonal:
|
||||
self.start.append(tag)
|
||||
attdict = {}
|
||||
for attr in attrs:
|
||||
attdict[attr[0]] = attr[1]
|
||||
|
||||
attdict = self._wash_attr(attdict, tag)
|
||||
if hasattr(self, "node_%s" % tag):
|
||||
attdict = getattr(self, "node_%s" % tag)(attdict)
|
||||
else:
|
||||
attdict = self.node_default(attdict)
|
||||
|
||||
attrs = []
|
||||
for (key, value) in attdict.items():
|
||||
attrs.append('%s="%s"' % (key, self._htmlspecialchars(value)))
|
||||
attrs = (' ' + ' '.join(attrs)) if attrs else ''
|
||||
self.result.append('<' + tag + attrs + end_diagonal + '>')
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if self.start and tag == self.start[len(self.start) - 1]:
|
||||
self.result.append('</' + tag + '>')
|
||||
self.start.pop()
|
||||
|
||||
def handle_data(self, data):
|
||||
self.result.append(self._htmlspecialchars(data))
|
||||
|
||||
def handle_entityref(self, name):
|
||||
if name.isalpha():
|
||||
self.result.append("&%s;" % name)
|
||||
|
||||
def handle_charref(self, name):
|
||||
if name.isdigit():
|
||||
self.result.append("&#%s;" % name)
|
||||
|
||||
def node_default(self, attrs):
|
||||
attrs = self._common_attr(attrs)
|
||||
return attrs
|
||||
|
||||
def node_a(self, attrs):
|
||||
attrs = self._common_attr(attrs)
|
||||
attrs = self._get_link(attrs, "href")
|
||||
attrs = self._set_attr_default(attrs, "target", "_blank")
|
||||
attrs = self._limit_attr(attrs, {
|
||||
"target": ["_blank", "_self"]
|
||||
})
|
||||
return attrs
|
||||
|
||||
def node_embed(self, attrs):
|
||||
attrs = self._common_attr(attrs)
|
||||
attrs = self._get_link(attrs, "src")
|
||||
attrs = self._limit_attr(attrs, {
|
||||
"type": ["application/x-shockwave-flash"],
|
||||
"wmode": ["transparent", "window", "opaque"],
|
||||
"play": ["true", "false"],
|
||||
"loop": ["true", "false"],
|
||||
"menu": ["true", "false"],
|
||||
"allowfullscreen": ["true", "false"]
|
||||
})
|
||||
attrs["allowscriptaccess"] = "never"
|
||||
attrs["allownetworking"] = "none"
|
||||
return attrs
|
||||
|
||||
def _true_url(self, url):
|
||||
prog = re.compile(r"(^(http|https|ftp)://.+)|(^/)", re.I | re.S)
|
||||
if prog.match(url):
|
||||
return url
|
||||
else:
|
||||
return "http://%s" % url
|
||||
|
||||
def _true_style(self, style):
|
||||
if style:
|
||||
style = re.sub(r"(\\|&#|/\*|\*/)", "_", style)
|
||||
style = re.sub(r"e.*x.*p.*r.*e.*s.*s.*i.*o.*n", "_", style)
|
||||
return style
|
||||
|
||||
def _get_style(self, attrs):
|
||||
if "style" in attrs:
|
||||
attrs["style"] = self._true_style(attrs.get("style"))
|
||||
return attrs
|
||||
|
||||
def _get_link(self, attrs, name):
|
||||
if name in attrs:
|
||||
attrs[name] = self._true_url(attrs[name])
|
||||
return attrs
|
||||
|
||||
def _wash_attr(self, attrs, tag):
|
||||
if tag in self.tags_own_attrs:
|
||||
other = self.tags_own_attrs.get(tag)
|
||||
else:
|
||||
other = []
|
||||
if attrs:
|
||||
for key, value in copy.deepcopy(attrs).items():
|
||||
if key not in self.common_attrs + other:
|
||||
del attrs[key]
|
||||
return attrs
|
||||
|
||||
def _common_attr(self, attrs):
|
||||
attrs = self._get_style(attrs)
|
||||
return attrs
|
||||
|
||||
def _set_attr_default(self, attrs, name, default=''):
|
||||
if name not in attrs:
|
||||
attrs[name] = default
|
||||
return attrs
|
||||
|
||||
def _limit_attr(self, attrs, limit={}):
|
||||
for (key, value) in limit.items():
|
||||
if key in attrs and attrs[key] not in value:
|
||||
del attrs[key]
|
||||
return attrs
|
||||
|
||||
def _htmlspecialchars(self, html):
|
||||
return html.replace("<", "<") \
|
||||
.replace(">", ">") \
|
||||
.replace('"', """) \
|
||||
.replace("'", "'")
|
||||
|
||||
|
||||
if "__main__" == __name__:
|
||||
with XSSHtml() as parser:
|
||||
ret = parser.clean("""<p><img src=1 onerror=alert(/xss/)></p><div class="left">
|
||||
<a href='javascript:prompt(1)'><br />hehe</a></div>
|
||||
<p id="test" onmouseover="alert(1)">>M<svg>
|
||||
<a href="https://www.baidu.com" target="self">MM</a></p>
|
||||
<embed src='javascript:alert(/hehe/)' allowscriptaccess=always />
|
||||
<img onerror=alert(1) src=#>""")
|
||||
print(ret)
|
||||
Reference in new issue
Block a user