sprint/SprintLib/utils.py
2022-10-14 02:35:27 +00:00

91 lines
2.2 KiB
Python

import datetime
import io
from random import choice
from time import sleep
from django.core.management import BaseCommand
from minio import Minio, S3Error
from Sprint import settings
from SprintLib.queue import send_to_queue
from SprintLib.redis import lock
BUCKET_NAME = 'dev'
client = Minio(
settings.MINIO_HOST,
access_key=settings.MINIO_ACCESS_KEY,
secret_key=settings.MINIO_SECRET_KEY,
secure=False
)
@lock('write_bytes')
def write_bytes(data: bytes):
try:
obj = client.get_object(BUCKET_NAME, 'meta.txt')
num = int(obj.data.decode('utf-8')) + 1
except S3Error:
client.put_object(BUCKET_NAME, 'meta.txt', io.BytesIO(b"1"), 1)
num = 1
b_num = str(num).encode('utf-8')
client.put_object(BUCKET_NAME, str(num), io.BytesIO(data), len(data))
client.put_object(BUCKET_NAME, 'meta.txt', io.BytesIO(b_num), len(b_num))
return num
def get_bytes(num: int) -> bytes:
try:
return client.get_object(BUCKET_NAME, str(num)).data
except Exception as e:
print(e.with_traceback(None))
return b''
def delete_file(num: int):
try:
client.remove_object(BUCKET_NAME, str(num))
except:
...
def generate_token():
letters = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
return ''.join([choice(letters) for _ in range(30)])
class Timer:
start_time = None
end_time = None
def __init__(self, solution, test):
self.solution = solution
self.test = test
def __enter__(self):
assert self.start_time is None
self.start_time = datetime.datetime.now()
def __exit__(self, exc_type, exc_val, exc_tb):
self.end_time = datetime.datetime.now()
self.solution.extras[self.test]['time_spent'] = (self.end_time - self.start_time).total_seconds() * 1000
class LoopWorker(BaseCommand):
sleep_period = 5
def go(self):
raise NotImplementedError("Method go should be implemented")
def handle(self, *args, **options):
while True:
self.go()
sleep(self.sleep_period)
def send_testing(solution):
if solution.set is not None and len(solution.set.checkers.all()) != 0:
return
send_to_queue("test", {"id": solution.id})