Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.http import HttpResponseRedirect
- from .models import Essay, Check_Result, Text, Profile, RUBILNIK, Bad_user, Counter, Block_send_textfield, \
- Rating_checker, Rating_writer, Essays_list, Test_question, Answer, Questions_list
- from .forms import get_essay, get_check, get_rate, get_answer
- from django.shortcuts import render, redirect
- from django.utils import timezone
- from django.views.generic import View
- from django.contrib.auth.models import User
- import random
- # Требование авторизации
- from django.contrib.auth.decorators import login_required
- from django.utils.decorators import method_decorator
- from datetime import datetime, timedelta
- from social_django.models import UserSocialAuth
- import requests
- import json
- import logging
- from Main import my_config
- from Site.settings import BASE_DIR
- import os
- # from weasyprint import HTML
- # Для картинок:
- from PIL import Image
- from urllib.request import urlopen
- logger = logging.getLogger(__name__)
- ADMINS_LIST = my_config.ADMINS_LIST
- def get_current_time():
- _time_now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=3))) # получение московского времени
- time_now = _time_now.strftime("%d.%m.%Y %H:%M:%S") # пример формата времени: '01.06.2020 03:26:31'
- return time_now
- # получение id вк по короткой ссылке
- # https://vk.com/dev/utils.resolveScreenName
- def _get_vk_user_id(VK_SHORT_ID):
- ACCESS_TOKEN = my_config.VK_AUTH_SERVICE_ACCESS_KEY
- API_VERSION = '5.21'
- vk_profile_response = requests.get(
- f'https://api.vk.com/method/utils.resolveScreenName?screen_name={VK_SHORT_ID}&access_token={ACCESS_TOKEN}&v={API_VERSION}').text
- dict_vk_profile_response = json.loads(vk_profile_response)
- try:
- vk_profile_id = dict_vk_profile_response['response']['object_id']
- except:
- return 'ERROR@'
- return vk_profile_id
- # получение авы вк
- # https://vk.com/dev/users.get
- def _get_vk_user_profile_photo(VK_ID, ACCESS_TOKEN, photo_size):
- API_VERSION = '5.122'
- vk_profile_response = requests.get(
- f'https://api.vk.com/method/users.get?user_ids={VK_ID}&fields={photo_size}&access_token={ACCESS_TOKEN}&v={API_VERSION}').text
- dict_vk_profile_response = json.loads(vk_profile_response)
- try:
- vk_profile_photo = dict_vk_profile_response['response'][0][photo_size]
- except:
- return 'ERROR@'
- return vk_profile_photo
- def get_url_full_vk_user_profile_photo(VK_SHORT_ID, photo_size):
- try:
- _is_error = False
- user_id_vk = _get_vk_user_id(VK_SHORT_ID)
- if user_id_vk != 'ERROR@':
- extra_data = UserSocialAuth.objects.get(uid=user_id_vk).extra_data
- else:
- logger.error(
- f': {VK_SHORT_ID} ошибка получения id vk из короткого имени пользователя! в get_url_full_vk_user_profile_photo()')
- return 'ERROR@'
- except:
- if VK_SHORT_ID in ADMINS_LIST:
- print(f'{VK_SHORT_ID}, добро пожаловать. Вы — админ!')
- return 'ADMIN@'
- else:
- logger.error(
- f': {VK_SHORT_ID} ошибка получения авы из ВК профиля пользователя! в get_url_full_vk_user_profile_photo()')
- return 'ERROR@'
- if extra_data['id'] == user_id_vk: # не знаю зачем это, но пусть будет
- access_token_vk = extra_data['access_token']
- else:
- logger.error(f': {VK_SHORT_ID} dict_extra_data[\'id\'] != user_id_vk! в get_url_full_vk_user_profile_photo()')
- return 'ERROR@'
- url_vk_profile_photo = _get_vk_user_profile_photo(user_id_vk, access_token_vk, photo_size)
- if url_vk_profile_photo == 'ERROR@':
- logger.error(
- f': {VK_SHORT_ID} ошибка получения авы из ВК профиля пользователя! в get_url_full_vk_user_profile_photo()')
- return 'ERROR@'
- return url_vk_profile_photo
- # не работает :(
- def func_is_send_textarea_blocked():
- return Block_send_textfield.objects.all().order_by('-id').get()
- # Вывод текста недели со всей информацией об авторе
- def get_text_and_author_info(request):
- get_text = Text.objects.all()
- text = get_text.order_by("-id")[0:1].get()
- text_parts = text.Body.split('\n')
- text_parts = [x for x in text_parts if x not in [None, '\n', '\r', '']]
- text_week_n_author_without_star = ''
- if '*' in text.Author:
- text_week_n_author_without_star = text.Author.replace('*', '')
- new_Author_description = ''
- if text.Author_description_bold != '':
- if text.Author_description_bold in text.Author_description:
- new_Author_description = text.Author_description.replace(text.Author_description_bold, '')
- else:
- logger.error(
- f': {request.user} text.Author_description не содержит в себе text.Author_description_bold')
- else:
- logger.warning(f': {request.user} text.Author_description_bold пуст в /send')
- return text, text_parts, text_week_n_author_without_star, new_Author_description
- def rating_functions(current_essay, last_check, profile_of_essay, profile):
- new_essay_rating = Rating_writer()
- new_essay_rating.user = current_essay.user
- new_essay_rating.rating_of_rater = profile.rating
- new_essay_rating.essay_rating = round(last_check.score, 2)
- new_essay_rating.save()
- essay_rating = Rating_writer.objects.filter(user=current_essay.user)
- e_sum = 0
- num_of_checks = 0
- sum_score = 0
- true_num_of_check = 0
- for e_rate in essay_rating:
- # Тут формула 228, которая увеличивает значимость проверки в зависимости от рейтинга проверяющего!
- e_sum += e_rate.essay_rating * ((e_rate.rating_of_rater ** 2) / 50 + 1)
- sum_score += e_rate.essay_rating
- num_of_checks += ((e_rate.rating_of_rater ** 2) / 50 + 1)
- true_num_of_check += 1
- average_essay_rating = e_sum / num_of_checks
- average_score = sum_score / true_num_of_check
- profile_of_essay.essay_rating = round(average_essay_rating * 0.2, 2)
- profile_of_essay.average_score = round(average_score, 2)
- profile_of_essay.save()
- final_score = (1.2 * profile_of_essay.checker_rating + 0.8 * profile_of_essay.essay_rating) / 2
- if final_score > profile_of_essay.rating / 2:
- profile_of_essay.rating += round(0.1 * (final_score - profile_of_essay.rating / 2), 2)
- else:
- profile_of_essay.rating -= round(0.1 * (profile_of_essay.rating / 2 - final_score), 2)
- if profile_of_essay.rating > 10:
- profile_of_essay.rating = 10
- if profile_of_essay.rating < 0:
- profile_of_essay.rating = 0
- profile_of_essay.save()
- def get_user_profile_avatars(profile, request) -> None:
- vk_profile_photo_200 = profile.avatar_200
- vk_profile_photo_50 = profile.avatar_50
- if (vk_profile_photo_200 is None or vk_profile_photo_200 == '') and (vk_profile_photo_50 is None or vk_profile_photo_50 == ''):
- logger.info(f': {request.user} впервые зашёл на сайт')
- profile.avatar_200 = get_url_full_vk_user_profile_photo(request.user.username, 'photo_200')
- profile.avatar_50 = get_url_full_vk_user_profile_photo(request.user.username, 'photo_50')
- profile.save()
- class Send(View):
- # Требуется авторизация, чтобы фукнция внутри класса запустилась
- @method_decorator(login_required)
- def get(self, request):
- logger.info(f': {request.user} открыта страница /send')
- what_time = RUBILNIK.objects.all().order_by('-id').get()
- profile = Profile.objects.get(user=request.user)
- get_user_profile_avatars(profile, request)
- if what_time.sent_check == 1 and profile.ban == 0 and profile.rating >= 1.5:
- # Определение этапа для отображения в шапке (пишем сочинения или проверяем?)
- which_step = 'Этап сдачи сочинений'
- which_step_title = 'этап 1/3'
- form = get_essay()
- data = {
- 'form': form,
- 'profile': profile,
- 'which_step': which_step,
- 'which_step_title': which_step_title,
- 'func_is_send_textarea_blocked': func_is_send_textarea_blocked(),
- }
- # получение всей информации о тексте недели и его авторе
- text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
- request)
- data['text'] = text
- data['text_parts'] = text_parts
- data['text_week_n_author_without_star'] = text_week_n_author_without_star
- data['new_Author_description'] = new_Author_description
- if_soch_already_send = False
- if Essay.objects.filter(user=request.user, text=text).exists():
- if_soch_already_send = True
- essay = Essay.objects.get(user=request.user, text=text)
- _sent_time = essay.time
- sent_time = _sent_time.strftime("%d.%m.%Y %H:%M:%S")
- new_sent_time = datetime.strptime(str(sent_time), "%d.%m.%Y %H:%M:%S") + timedelta(hours=3)
- sent_essay = essay.Body.split('\n')
- sent_essay = [x for x in sent_essay if x not in [None, '\n', '\r', '']]
- data['sent_essay'] = sent_essay
- data['sent_time'] = f'На {text.week_number} неделе Вами уже было отправлено сочинение {new_sent_time.strftime("%d.%m.%Y {} %H:%M:%S".format("в"))} (МСК):'
- data['if_soch_already_send'] = if_soch_already_send
- elif profile.rating < 1.5:
- return redirect('/test')
- else:
- return redirect('/')
- return render(request, 'send.html', data)
- def post(self, request):
- logger.info(f': {request.user} отправлена форма со страницы /send')
- which_step_title = 'этап 1/3'
- data = {}
- # получение всей информации о тексте недели и его авторе
- text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
- request)
- data['text'] = text
- data['text_parts'] = text_parts
- data['text_week_n_author_without_star'] = text_week_n_author_without_star
- data['new_Author_description'] = new_Author_description
- form = get_essay(request.POST, initial={'Title': text.Title, 'text': text})
- profile = Profile.objects.get(user=request.user)
- users_essays = Essay.objects.filter(user=request.user, text=text)
- if users_essays.count() > 0:
- if_essay = users_essays.order_by('-id').get()
- else:
- if_essay = None
- # Надо сделать проверку на уникальность сочина к тексту другим способом.
- # Сейчас при обновлении сохранятеся второй сочин т.к. второе условие выполняется....
- if (if_essay == None) or (if_essay.text != text):
- print(form.is_valid(), users_essays.count())
- if form.is_valid() and users_essays.count() == 0:
- form.save()
- essay_sent_for_edit = True
- text.Number_of_essays = Essay.objects.filter(text=text).count() + 1
- text.save()
- # Выдача номера сочинению по этому тексту
- essay = Essay.objects.all().order_by("-id")[0:1].get()
- essay.number = text.Number_of_essays
- essay.time = timezone.now()
- essay.user = request.user
- essay.text = text
- Body = str(essay.Body)
- essay.Title = Body[0:30]
- essay.save()
- # Выдача номера сдавшему сочин
- profile = Profile.objects.get(user=request.user)
- profile.queue = text.Number_of_essays
- profile.sent = text.id
- profile.check_number = 0
- profile.save()
- # Закрепление сочина за юзером
- profile = Profile.objects.get(user=request.user)
- profile.number_of_essays = Essay.objects.filter(user=request.user).count()
- profile.essays.add(essay)
- profile.save()
- numbur_of_soch_for_google_sheets = Essay.objects.all().count()
- # upload_soch_to_google_sheets(essay.Title, essay.Body, essay.number, request.user)
- logger.info(f'{request.user} отправил сочинение : {essay.Body} - ({essay.Title})')
- return redirect('/send')
- else:
- return redirect('/send')
- else:
- error = 'Вы уже отправили сочинение на этой неделе!'
- data['already_sent_error'] = error
- data['form'] = form
- data['which_step_title'] = which_step_title
- data['profile'] = profile
- return render(request, 'send.html', data)
- # Вот время сдачи, но так не работает норм формамт
- this_essay = Essay.objects.get(user=request.user, text=text)
- _sent_time = this_essay.time
- sent_time = _sent_time.strftime("%d.%m.%Y %H:%M:%S")
- data['form'] = form
- data['profile'] = profile
- data['which_step_title'] = which_step_title
- data['new_sent_time'] = None
- data['essay_sent_for_edit'] = essay_sent_for_edit
- if Essay.objects.filter(user=request.user, text=text).exists():
- new_sent_time = datetime.strptime(str(sent_time), "%d.%m.%Y %H:%M:%S") + timedelta(hours=3)
- new_sent_time = f'Вы отправили сочинение {new_sent_time.strftime("%d.%m.%Y {} %H:%M:%S".format("в"))} (МСК)'
- data['new_sent_time'] = new_sent_time
- return render(request, 'send.html', data)
- class Edit(View):
- def get(self, request):
- get_text = Text.objects.all()
- text = get_text.order_by("-id")[0:1].get()
- profile = Profile.objects.get(user=request.user)
- get_user_profile_avatars(profile, request)
- what_time = RUBILNIK.objects.all().order_by('-id').get()
- if what_time.sent_check == 1 and profile.ban == 0 and Essay.objects.filter(text=text,
- user=request.user).exists():
- essay = Essay.objects.get(text=text, user=request.user)
- form = get_essay(initial={'Body': essay.Body})
- which_step = 'Этап сдачи сочинений'
- which_step_title = 'этап 1/3'
- data = {
- 'form': form,
- 'profile': profile,
- 'which_step': which_step,
- 'which_step_title': which_step_title,
- 'func_is_send_textarea_blocked': func_is_send_textarea_blocked(),
- }
- # получение всей информации о тексте недели и его авторе
- text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
- request)
- data['text'] = text
- data['text_parts'] = text_parts
- data['text_week_n_author_without_star'] = text_week_n_author_without_star
- data['new_Author_description'] = new_Author_description
- return render(request, 'edit.html', data)
- else:
- return redirect('/send')
- def post(self, request):
- get_text = Text.objects.all()
- text = get_text.order_by("-id")[0:1].get()
- profile = Profile.objects.get(user=request.user)
- what_time = RUBILNIK.objects.all().order_by('-id').get()
- if what_time.sent_check == 1 and profile.ban == 0 and Essay.objects.filter(text=text,
- user=request.user).exists():
- essay = Essay.objects.get(text=text, user=request.user)
- form = get_essay(request.POST, initial={'Body': essay.Body})
- essay.Body = request.POST.get("Body")
- essay.time = timezone.now()
- body = str(essay.Body)
- essay.Title = body[0:30]
- essay.save()
- which_step = 'Этап сдачи сочинений'
- which_step_title = 'этап 1/3'
- data = {
- 'form': form,
- 'profile': profile,
- 'which_step': which_step,
- 'which_step_title': which_step_title,
- 'func_is_send_textarea_blocked': func_is_send_textarea_blocked(),
- }
- # получение всей информации о тексте недели и его авторе
- text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
- request)
- data['text'] = text
- data['text_parts'] = text_parts
- data['text_week_n_author_without_star'] = text_week_n_author_without_star
- data['new_Author_description'] = new_Author_description
- return redirect('/send')# render(request, 'edit.html', data)
- else:
- return redirect('/send')
- class Check(View):
- # Требуется авторизация, чтобы фукнция внутри класса запустилась
- @method_decorator(login_required)
- def get(self, request):
- profile = Profile.objects.get(user=request.user)
- if Essay.objects.filter(user=request.user, text=Text.objects.order_by("-id")[0:1].get()).exists():
- get_user_profile_avatars(profile, request)
- what_time = RUBILNIK.objects.all().order_by('-id').get()
- if what_time.sent_check == 0 and profile.ban == 0 and profile.rating >= 1.5:
- logger.info(f': {request.user} открыта страница /check')
- which_step_title = 'этап 2/3'
- text = Text.objects.order_by('-id')[0:1].get()
- # Вывод сочина на проверку
- if Essays_list.objects.filter(user=request.user).count() == 0:
- get_essay = Essay.objects.filter(text=text)
- number_of_essays = Essay.objects.filter(text=text).count()
- _distribution_chances = []
- for essay in get_essay:
- profile_of_essay = Profile.objects.get(user=essay.user)
- # 0.1 чтоб деления на 0 не было!
- chance = random.random()*(5 / (abs(profile.rating - profile_of_essay.rating)+0.1))
- _distribution_chances.append([chance, essay])
- distribution_chances = sorted(_distribution_chances, reverse=True)
- print('> > > ', distribution_chances)
- for chance, essay in distribution_chances:
- if essay.user != profile.user:
- new_essay = Essays_list()
- new_essay.user = profile.user
- new_essay.essay = essay
- essay.checked += 1
- essay.save()
- new_essay.save()
- # Получение массива с 4 сочинами из индивидуального списка (в правильном ли порядке чекни)
- essay = []
- for e in Essays_list.objects.filter(user=request.user).order_by("id"):
- if e.essay.checked < 4:
- essay.append(e.essay)
- if len(essay) > 5:
- break
- profile.check_number = Check_Result.objects.filter(checker=request.user, Text=text).count()
- if profile.check_number < 3 and Essay.objects.filter(text=text, user=request.user).exists():
- current_essay = essay[profile.check_number]
- else:
- current_essay = None
- if current_essay is not None:
- soch_to_summernote = Essay.objects.get(id=current_essay.id).Body.split('\n')
- soch_to_summernote = ''.join(f'<p>{x}</p>' for x in soch_to_summernote if x not in [None, '\n', '\r', ''])
- form = get_check(initial={'summernote_editor': soch_to_summernote})
- else:
- form = get_check
- data = {
- 'form': form,
- 'profile': profile,
- 'essay': essay,
- 'which_step_title': which_step_title,
- 'current_essay': current_essay,
- 'content_marks_table': my_config.CHECK_ESSAY_TABLE,
- }
- # получение всей информации о тексте недели и его авторе
- text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
- request)
- data['text'] = text
- data['text_parts'] = text_parts
- data['text_week_n_author_without_star'] = text_week_n_author_without_star
- data['new_Author_description'] = new_Author_description
- essay0_parts = str(essay[0].Body).split('\n')
- essay1_parts = str(essay[1].Body).split('\n')
- essay2_parts = str(essay[2].Body).split('\n')
- if Check_Result.objects.filter(essay=essay[0], checker=request.user).exists():
- essay0_parts = str(Check_Result.objects.get(essay=essay[0], checker=request.user).summernote_editor).split('\n')
- if Check_Result.objects.filter(essay=essay[1], checker=request.user).exists():
- essay1_parts = str(Check_Result.objects.get(essay=essay[1], checker=request.user).summernote_editor).split('\n')
- if Check_Result.objects.filter(essay=essay[2], checker=request.user).exists():
- essay2_parts = str(Check_Result.objects.get(essay=essay[2], checker=request.user).summernote_editor).split('\n')
- essay0_parts = [x for x in essay0_parts if x not in [None, '\n', '\r', '']]
- essay1_parts = [x for x in essay1_parts if x not in [None, '\n', '\r', '']]
- essay2_parts = [x for x in essay2_parts if x not in [None, '\n', '\r', '']]
- current_essay_number = int(profile.check_number)
- data['current_essay_number'] = current_essay_number
- data['essay0_parts'] = essay0_parts
- data['essay1_parts'] = essay1_parts
- data['essay2_parts'] = essay2_parts
- if Check_Result.objects.filter(checker=request.user, Text=text).count() > 2:
- print(essay)
- try:
- data['next_essay'] = essay[3]
- except IndexError:
- pass
- elif profile.rating < 1.5:
- return redirect('/test')
- else:
- return redirect('/')
- return render(request, 'check.html', data)
- else:
- if Essays_list.objects.filter(user=request.user).count() == 0:
- text = Text.objects.order_by('-id')[0:1].get()
- get_essay = Essay.objects.filter(text=text)
- number_of_essays = Essay.objects.filter(text=text).count()
- _distribution_chances = []
- for essay in get_essay:
- profile_of_essay = Profile.objects.get(user=essay.user)
- # 0.1 чтоб деления на 0 не было!
- chance = random.random() * (5 / (abs(profile.rating - profile_of_essay.rating) + 0.1))
- _distribution_chances.append([chance, essay])
- distribution_chances = sorted(_distribution_chances, reverse=True)
- for chance, essay in distribution_chances:
- if essay.user != profile.user:
- new_essay = Essays_list()
- new_essay.user = profile.user
- new_essay.essay = essay
- essay.checked += 1
- essay.save()
- new_essay.save()
- next_essay = Essays_list.objects.filter(user=request.user).order_by("id")[0:1].get()
- next_essay_number = next_essay.essay.number
- print(">>> ", next_essay_number)
- return redirect(f'/check_optional/{next_essay_number}')
- def post(self, request):
- logger.info(f': {request.user} отправлена форма со страницы /check')
- which_step_title = 'этап 2/3'
- form = get_check(request.POST)
- profile = Profile.objects.get(user=request.user)
- # Подгружаются сочины из БД
- essay = []
- for e in Essays_list.objects.filter(user=request.user).order_by("id"):
- if e.essay.checked < 4:
- essay.append(e.essay)
- if len(essay) > 5:
- break
- data = {
- 'form': form,
- 'profile': profile,
- 'which_step_title': which_step_title,
- 'essay': essay,
- }
- # получение всей информации о тексте недели и его авторе
- text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
- request)
- data['text'] = text
- data['text_parts'] = text_parts
- data['text_week_n_author_without_star'] = text_week_n_author_without_star
- data['new_Author_description'] = new_Author_description
- current_essay_number = Essay.objects.filter(text=text).count()
- data['current_essay_number'] = current_essay_number
- try:
- data['next_essay'] = essay[3]
- except IndexError:
- pass
- _essays_count = Essay.objects.filter(text=text).count()
- profile.check_number = Check_Result.objects.filter(checker=request.user, Text=text).count()
- if form.is_valid() and _essays_count - 1 > profile.check_number and profile.check_number < 3:
- form.save()
- # Здесь будет закрпеление проверок за юзером
- save_check = Check_Result.objects.all()
- last_check = save_check.order_by("-id")[0:1].get()
- last_check.Text = text
- last_check.checker = request.user
- profile.checks.add(last_check)
- profile.total_checked = Check_Result.objects.filter(checker=request.user).count()
- # Счётчик баллов
- ki_to_upload = [last_check.k1, last_check.k2, last_check.k3, last_check.k4, last_check.k5, last_check.k6, \
- last_check.k7, last_check.k8, last_check.k9, last_check.k10, last_check.k11, last_check.k12]
- total_mark = 0
- for ki in ki_to_upload:
- total_mark += ki
- last_check.score = total_mark
- last_check.save()
- if profile.check_number == 2 and _essays_count > 3:
- last_check.essay = essay[2]
- profile.check_number = profile.check_number + 1
- profile.save()
- current_essay = essay[2]
- elif profile.check_number == 1 and _essays_count > 2:
- last_check.essay = essay[1]
- profile.check_number = profile.check_number + 1
- profile.save()
- current_essay = essay[1]
- elif profile.check_number == 0 and _essays_count > 1:
- last_check.essay = essay[0]
- profile.check_number = profile.check_number + 1
- profile.save()
- current_essay = essay[0]
- last_check.essay = current_essay
- last_check.save()
- check = Check_Result.objects.order_by('id')[0:1].get()
- soch_author = check.essay.user
- profile_of_essay = Profile.objects.filter(user=current_essay.user).order_by('-id')[0:1].get()
- rating_functions(current_essay, last_check, profile_of_essay, profile)
- k_comments_to_upload = [last_check.k1_comment, last_check.k2_comment, last_check.k3_comment, \
- last_check.k4_comment, last_check.k5_comment, last_check.k6_comment, \
- last_check.k7_comment, last_check.k8_comment, last_check.k9_comment, \
- last_check.k10_comment, last_check.k11_comment, last_check.k12_comment]
- # upload_check_to_google_sheets(last_check.essay, soch_author, last_check.score, request.user, ki_to_upload,
- logger.info(
- f'{request.user} отправил проверку для {soch_author} : баллы: {ki_to_upload}; комментарии: {k_comments_to_upload}')
- else:
- checked_all = 'Вы уже проверили свои 3 сочинения'
- data['checked_all'] = checked_all
- return render(request, 'check.html', data)
- if profile.check_number < 3:
- data['current_essay'] = current_essay
- return redirect('/check')
- class Optional(View):
- def essay_list(self, request) -> list:
- # Подгружаются сочины из БД
- essay = []
- i = 0
- for e in Essays_list.objects.filter(user=request.user):
- if Essay.objects.get(id=e.essay.id).checked < 3:
- essay.append(e.essay)
- if i == 2:
- break
- i += 1
- return essay
- def get(self, request, next_essay_id):
- profile = Profile.objects.get(user=request.user)
- get_user_profile_avatars(profile, request)
- what_time = RUBILNIK.objects.all().order_by('-id').get()
- text = Text.objects.order_by('-id')[0:1].get()
- checked_this_week = Check_Result.objects.filter(checker=request.user, Text=text).count()
- can_go = False
- if checked_this_week > 2 or not Essay.objects.filter(user=request.user, text=text).exists():
- can_go = True
- logger.info(f': {request.user} открыта страница /check_optional')
- if what_time.sent_check == 0 and profile.ban == 0 and profile.rating >= 1.5 and can_go:
- text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(request)
- current_essay = Essay.objects.get(number=next_essay_id, text=text)
- if not Check_Result.objects.filter(checker=request.user, essay=current_essay).exists():
- soch_to_summernote = Essay.objects.get(id=current_essay.id).Body.split('\n')
- soch_to_summernote = ''.join(f'<p>{x}</p>' for x in soch_to_summernote if x not in [None, '\n', '\r', ''])
- form = get_check(initial={'summernote_editor': soch_to_summernote})
- essay_to_show = None
- else:
- form = None
- essay_to_show = Check_Result.objects.get(essay=current_essay, checker=request.user).summernote_editor
- which_step_title = 'этап 2/3: дополнительные проверки'
- print(essay_to_show)
- # essays = self.essay_list(request)
- user_checked = Check_Result.objects.filter(checker=request.user, Text=text).count()
- num_of_essays = Essay.objects.filter(text=text).count()
- num_of_essays_ostatok = num_of_essays - user_checked - 1
- if not Essay.objects.filter(user=request.user, text=text).exists():
- num_of_essays_ostatok += 1
- essay_parts = str(current_essay.Body).split('\n')
- essay_parts = [x for x in essay_parts if x not in [None, '\n', '\r', '']]
- data = {
- 'profile': profile,
- 'current_essay': current_essay,
- 'essay_parts': essay_parts,
- 'essay_to_show': essay_to_show,
- #'essay_to_show_parts': essay_to_show_parts,
- 'which_step_title': which_step_title,
- 'user_checked': user_checked,
- 'num_of_essays': num_of_essays - 1,
- 'num_of_essays_ostatok': num_of_essays_ostatok,
- 'content_marks_table': my_config.CHECK_ESSAY_TABLE,
- }
- if current_essay.user == request.user:
- form = None
- data['your_essay_message'] = 'Это ваше сочинение лол'
- data['form'] = form
- # получение всей информации о тексте недели и его авторе
- data['text'] = text
- data['text_parts'] = text_parts
- data['text_week_n_author_without_star'] = text_week_n_author_without_star
- data['new_Author_description'] = new_Author_description
- # Подгружаются сочины из БД
- text = Text.objects.order_by('-id')[0:1].get()
- essay = []
- i = 0
- for e in Essays_list.objects.filter(user=request.user):
- essay.append(e.essay)
- if e.essay == Essay.objects.get(text=text, number=int(next_essay_id)):
- num_of_current_essay_in_list = i
- i += 1
- try:
- next_essay = essay[num_of_current_essay_in_list + 1]
- data['next_essay'] = next_essay
- except IndexError:
- pass
- if num_of_current_essay_in_list > 0:
- previous_essay = essay[num_of_current_essay_in_list - 1]
- data['previous_essay'] = previous_essay
- return render(request, 'check_optional.html', data)
- else:
- return redirect('/')
- def post(self, request, next_essay_id):
- logger.info(f': {request.user} отправлена форма со страницы /check_optional')
- # получение всей информации о тексте недели и его авторе
- text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(request)
- essays = self.essay_list(request)
- form = get_check(request.POST)
- profile = Profile.objects.get(user=request.user)
- if form.is_valid():
- form.save()
- current_essay = Essay.objects.get(number=next_essay_id, text=text)
- body = str(current_essay.Body)
- current_essay.Title = body[0:30]
- # Здесь будет закрпеление проверок за юзером
- last_check = Check_Result.objects.order_by("-id")[0:1].get()
- last_check.Text = text
- last_check.checker = request.user
- last_check.essay = current_essay
- profile.checks.add(last_check)
- profile.total_checked = Check_Result.objects.filter(checker=request.user).count()
- # Счётчик баллов
- ki_to_upload = [last_check.k1, last_check.k2, last_check.k3, last_check.k4, last_check.k5, last_check.k6, \
- last_check.k7, last_check.k8, last_check.k9, last_check.k10, last_check.k11, last_check.k12]
- total_mark = 0
- for ki in ki_to_upload:
- total_mark += ki
- last_check.score = total_mark
- last_check.save()
- check = Check_Result.objects.order_by('id')[0:1].get()
- soch_author = check.essay.user
- k_comments_to_upload = [last_check.k1_comment, last_check.k2_comment, last_check.k3_comment, \
- last_check.k4_comment, last_check.k5_comment, last_check.k6_comment, \
- last_check.k7_comment, last_check.k8_comment, last_check.k9_comment, \
- last_check.k10_comment, last_check.k11_comment, last_check.k12_comment]
- logger.info(
- f'{request.user} отправил проверку (optional) для {soch_author} : баллы: {ki_to_upload}; комментарии: {k_comments_to_upload}')
- profile_of_essay = Profile.objects.filter(user=current_essay.user).order_by('-id')[0:1].get()
- print('profile_of_essay - ', profile_of_essay)
- rating_functions(current_essay, last_check, profile_of_essay, profile)
- return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
- def login(request):
- logger.info(f': {request.user} открыта страница /login')
- return render(request, 'auth/login.html')
- # Требуется авторизация, чтобы фукнция запустилась
- @login_required
- def home(request): # бывшая IndexView функция
- logger.info(f': {request.user} открыта страница /')
- print('request.user.username:', request.user.username)
- profile = Profile.objects.get(user=request.user)
- get_user_profile_avatars(profile, request)
- what_time = RUBILNIK.objects.all().order_by('-id').get()
- if what_time.sent_check == 0:
- time_is = None
- else:
- time_is = 1
- data = {
- 'time_is': time_is,
- 'profile': profile,
- }
- if profile.ban == 1:
- data['ban_msg'] = 'Вам бан'
- return render(request, 'homepage.html', data)
- # Требуется авторизация, чтобы фукнция запустилась
- @login_required
- def profile(request): # возможно надо переделать это в класс
- logger.info(f': {request.user} открыта страница /profile')
- which_step_title = request.user.username
- step_is = bad_user = week_number = ''
- if request.user.is_superuser:
- what_time = RUBILNIK.objects.all().order_by('-id').get()
- text = Text.objects.order_by('-id')[0:1].get()
- week_number = text.week_number - 1
- if what_time.sent_check == 0:
- step_is = 'Этап сдачи проверок'
- else:
- step_is = 'Этап сдачи сочинений'
- # Список юзеров, не проверивших все 3 сочина
- bad_user = Bad_user.objects.order_by('-id')[0:1].get()
- # Стата из профиля
- profile = Profile.objects.get(user=request.user)
- get_user_profile_avatars(profile, request)
- # Дата отправки первого сочинения
- if profile.essays.count() > 0:
- first_essay = profile.essays.order_by('id')[0:1].get()
- date_of_first_essay = first_essay.time
- user_with_0_sochs = False
- else:
- # date_of_first_essay = 'вы ещё не писали сочинений'
- user_with_0_sochs = True
- date_of_first_essay = ''
- data = {
- 'date_of_first_essay': date_of_first_essay,
- 'step_is': step_is,
- 'which_step_title': which_step_title,
- 'profile': profile,
- 'admin': request.user.is_superuser,
- 'bad_user': bad_user,
- 'week_number': week_number,
- 'user_with_0_sochs': user_with_0_sochs,
- }
- return render(request, 'profile.html', data)
- # Требуется авторизация, чтобы фукнция запустилась
- class Look(View):
- def work_please(self, request):
- which_step_title = 'получение проверок'
- get_text = Text.objects.all()
- text = get_text.order_by("-id")[0:1].get()
- essay = Essay.objects.get(user=request.user, text=text)
- checks = Check_Result.objects.filter(essay=essay).order_by("id")
- return get_text, text, essay, checks, which_step_title
- # Требуется авторизация, чтобы фукнция внутри класса запустилась
- @method_decorator(login_required)
- def get(self, request):
- logger.info(f': {request.user} открыта страница /look')
- profile = Profile.objects.get(user=request.user)
- get_user_profile_avatars(profile, request)
- if profile.ban == 0:
- get_text, text, essay, checks, which_step_title = self.work_please(request)
- form = get_rate
- rated_list = []
- for rate in Rating_checker.objects.filter(user=request.user, text=text):
- rated_list.append(rate.number)
- essay_parts = essay.Body.split('\n')
- essay_parts = [x for x in essay_parts if x not in [None, '\n', '\r', '']]
- data = {
- 'rated_list': rated_list,
- 'form': form,
- 'profile': profile,
- 'essay': essay,
- 'checks': checks,
- 'which_step_title': which_step_title,
- 'essay_parts': essay_parts,
- }
- return render(request, 'look.html', data)
- else:
- return redirect('/')
- def post(self, request):
- get_text, text, essay, checks, which_step_title = self.work_please(request)
- i = 1
- form = get_rate(request.POST)
- for check in checks:
- current_profile = check.checker
- profile = Profile.objects.get(user=current_profile)
- if form.is_valid():
- if request.method == 'POST' and f'btn{i}' in request.POST:
- new_rating = Rating_checker()
- new_rating.user = current_profile
- new_rating.checker_rating = form.cleaned_data.get("checker_rating")
- new_rating.rating_of_rater = Profile.objects.get(user=request.user).rating
- new_rating.number = i
- new_rating.save()
- # Оценка умножается на рейтинг оценивающего и количество оценок увеличивается на рейтинг, а не
- # просто количество! Так что тут всё нормально, гуляй
- checker_rating = Rating_checker.objects.filter(user=current_profile)
- c_sum = 0
- num_of_checks = 0
- for c_rate in checker_rating:
- c_sum += c_rate.checker_rating * ((c_rate.rating_of_rater ** 2) / 50 + 1)
- num_of_checks += ((c_rate.rating_of_rater ** 2) / 50 + 1)
- average_checker_rating = c_sum / num_of_checks
- profile.checker_rating = average_checker_rating
- average_essay_rating = profile.essay_rating
- # Подсчёт и запись итогового рейтинга
- final_score = (1.2 * profile.checker_rating + 0.8 * average_essay_rating) / 2
- if final_score > profile.rating / 2:
- profile.rating += round(0.15 * (final_score - profile.rating / 2), 2)
- else:
- profile.rating -= round(0.15 * (profile.rating / 2 - final_score), 2)
- if profile.rating > 10:
- profile.rating = 10
- if profile.rating < 0:
- profile.rating = 0
- profile.save()
- return HttpResponseRedirect('/look')
- i += 1
- essay_parts = essay.Body.split('\n')
- essay_parts = [x for x in essay_parts if x not in [None, '\n', '\r', '']]
- data = {
- 'form': form,
- 'profile': profile,
- 'essay': essay,
- 'checks': checks,
- 'which_step_title': which_step_title,
- 'essay_parts': essay_parts,
- }
- return render(request, 'look.html', data)
- class Test(View):
- # Требуется авторизация, чтобы фукнция внутри класса запустилась
- @method_decorator(login_required)
- def get(self, request):
- logger.info(f': {request.user} открыта страница /test')
- profile = Profile.objects.get(user=request.user)
- get_user_profile_avatars(profile, request)
- if profile.ban == 0:
- form = get_answer
- test_questions = Test_question.objects.all()
- num_of_questions = test_questions.count()
- # txt_generate = ''
- # for i in test_questions.all():
- # txt_generate += '№' + str(i.number) + '\n'
- # txt_generate += i.question + '\n'
- # txt_generate += i.answer_1 + '\n'
- # txt_generate += i.answer_2 + '\n'
- # txt_generate += i.answer_3 + '\n'
- # txt_generate += i.answer_4 + '\n'
- # txt_generate += i.answer_5 + '\n'
- # txt_generate += "ответ: " + i.right_answer + '\n'
- # txt_generate += "\n-----------\n"
- #
- # with open("backup_questions.txt", "w") as text_file:
- # text_file.write(txt_generate)
- if not Questions_list.objects.filter(user=request.user).exists():
- new_question_list = Questions_list()
- new_question_list.user = request.user
- new_question_list.save()
- i = 1
- while i < 11:
- random_question = test_questions.get(number=random.randint(1, num_of_questions))
- if random_question not in new_question_list.question.all():
- new_question_list.question.add(random_question)
- new_question_list.number = i
- new_question_list.save()
- i += 1
- # Проверка, дан ли ответ на вопрос
- questions_list = Questions_list.objects.get(user=request.user)
- answered_questions_numbers = []
- for question in questions_list.question.all():
- if Answer.objects.filter(user=request.user, question=question).exists():
- answered_questions_numbers.append(question.number)
- data = {
- 'form': form,
- 'questions': Questions_list.objects.get(user=request.user),
- 'which_step_title': "обязательное тестирование",
- 'profile': Profile.objects.get(user=request.user),
- 'user': request.user,
- 'answered_questions_numbers': answered_questions_numbers,
- }
- count_user_answers = Answer.objects.filter(user=request.user).count()
- if count_user_answers > 9:
- data['is_test_passed'] = True
- mark = 0
- for answer in Answer.objects.filter(user=request.user):
- right_answer = Test_question.objects.get(question=answer.question).right_answer
- if answer.answer == right_answer:
- mark += 1
- data['number_of_correct_answers'] = mark
- return render(request, 'test.html', data)
- else:
- return redirect('/')
- def post(self, request):
- form = get_answer(request.POST)
- questions_list = Questions_list.objects.get(user=request.user)
- i = 0
- for question in questions_list.question.all():
- i += 1
- if form.is_valid():
- double_send = Answer.objects.filter(question=Test_question.objects.get(number=question.number)).exists()
- if request.method == 'POST' and f'btn{i}' in request.POST and not double_send:
- new_answer = Answer()
- new_answer.user = request.user
- new_answer.question = Test_question.objects.get(number=question.number)
- new_answer.answer = form.cleaned_data.get("answer")
- new_answer.save() # Продолжаем
- count_user_answers = Answer.objects.filter(user=request.user).count()
- if count_user_answers == 10:
- logger.info(f': {request.user} ответил на все вопросы на странице /test')
- mark = 0
- for answer in Answer.objects.filter(user=request.user):
- right_answer = Test_question.objects.get(question=answer.question).right_answer
- if answer.answer == right_answer:
- mark += 1
- profile = Profile.objects.get(user=request.user)
- profile.rating = 0.3 * mark
- profile.save()
- logger.info(f': {request.user} отправил {count_user_answers} форму на страцине /test')
- if request.method == 'POST' and f'btn{i}' in request.POST:
- return redirect('/test')
- def generate_soch_backup():
- text = Text.objects.order_by('-id')[0:1].get()
- text_parts = text.Body.split('\n')
- text_parts = '<p class="main_text">'.join(x + '</p>' for x in text_parts if x not in [None, '\n', '\r', ''])
- text_author = text.Author
- text_author_description = text.Author_description
- week_number = text.week_number
- html_generate = f"""<div class="main_content">
- <h2 class="tri_prov">3Проверочки</h2>
- <h4 class="tri_prov">Неделя {week_number}</h4>
- <div class="text"><p class="main_text">{text_parts}
- <p class="author_info_name">{text_author}</p>
- <p>{text_author_description}</p></div>
- <p style="page-break-before: always" ></p>"""
- path_to_save = f"{BASE_DIR}/work_outputs/week_{week_number}/сочинения"
- os.makedirs(path_to_save, exist_ok=True)
- all_week_soch = Essay.objects.filter(text=text)
- for soch in all_week_soch:
- soch_author = soch.user
- _soch_Body = soch.Body.split('\n')
- soch_parts = '<p class="soch_text">'.join(x + '</p>' for x in _soch_Body if x not in [None, '\n', '\r', ''])
- soch_parts = '<p class="soch_text">' + soch_parts
- soch_pass_time = soch.time
- html_generate += f"""<h5 class="what_is_it">Сочинение</h5><div class="soch">{soch_parts}</div>"""
- html_generate += f"""<div class="author">
- <li>Автор сочинения: {soch_author.first_name} {soch_author.last_name} ({soch_author})</li>
- <li>Дата отправки: {datetime.strftime(soch_pass_time, '%d.%m.%Y %H:%M:%S')}</li></div>"""
- html_generate += my_config.html_generate_css
- # html = HTML(string=html_generate)
- # html.write_pdf(f'{BASE_DIR}/example_{soch_author}.pdf')
- with open(f"{path_to_save}/soch_{soch_author}.html", "w") as text_file:
- text_file.write(html_generate)
- # weasyprint here
- html_generate = f"""<div class="main_content">
- <h2 class="tri_prov">3Проверочки</h2>
- <h4 class="tri_prov">Неделя {week_number}</h4>
- <div class="text"><p class="main_text">{text_parts}
- <p class="author_info_name">{text_author}</p>
- <p>{text_author_description}</p></div>
- <p style="page-break-before: always" ></p>"""
- def generate_checks_backup():
- text = Text.objects.order_by('-id')[0:1].get()
- text_parts = text.Body.split('\n')
- text_parts = '<p class="main_text">'.join(x + '</p>' for x in text_parts if x not in [None, '\n', '\r', ''])
- text_author = text.Author
- text_author_description = text.Author_description
- week_number = text.week_number
- html_generate = f"""<div class="main_content">
- <h2 class="tri_prov">3Проверочки</h2>
- <h4 class="tri_prov">Неделя {week_number}</h4>
- <div class="text"><p class="main_text">{text_parts}
- <p class="author_info_name">{text_author}</p>
- <p>{text_author_description}</p></div>
- <p style="page-break-before: always" ></p>"""
- path_to_save = f"{BASE_DIR}/work_outputs/week_{week_number}/проверки"
- os.makedirs(path_to_save, exist_ok=True)
- all_week_checks = Check_Result.objects.filter(Text=text)
- for check in all_week_checks:
- _essay = check.essay.Body.split('\n')
- soch_parts = '<p class="soch_text">'.join(x + '</p>' for x in _essay if x not in [None, '\n', '\r', ''])
- soch_parts = '<p class="soch_text">' + soch_parts
- html_generate += f"""<h5 class="what_is_it">Сочинение</h5><div class="soch">{soch_parts}</div>"""
- html_generate += """<p style="page-break-before: always" ></p>"""
- html_generate += """<h5 class="what_is_it">Проверка</h5>"""
- html_generate += f"""<div class="check">{check.summernote_editor}</div>"""
- html_generate += f"""<div class="author">
- <li>Автор проверки: {check.checker.first_name} {check.checker.last_name} ({check.checker})</li>"""
- html_generate += """<div class="table">"""
- # чел, удачи сделать по-другому
- html_generate += f"""<li>К1 - {check.k1} {check.k1_comment}</li>"""
- html_generate += f"""<li>К2 - {check.k2} {check.k2_comment}</li>"""
- html_generate += f"""<li>К3 - {check.k3} {check.k3_comment}</li>"""
- html_generate += f"""<li>К4 - {check.k4} {check.k4_comment}</li>"""
- html_generate += f"""<li>К5 - {check.k5} {check.k5_comment}</li>"""
- html_generate += f"""<li>К6 - {check.k6} {check.k6_comment}</li>"""
- html_generate += f"""<li>К7 - {check.k7} {check.k7_comment}</li>"""
- html_generate += f"""<li>К8 - {check.k8} {check.k8_comment}</li>"""
- html_generate += f"""<li>К9 - {check.k9} {check.k9_comment}</li>"""
- html_generate += f"""<li>К10 - {check.k10} {check.k10_comment}</li>"""
- html_generate += f"""<li>К11 - {check.k11} {check.k11_comment}</li>"""
- html_generate += f"""<li>К12 - {check.k12} {check.k12_comment}</li></div>"""
- html_generate += f"""<li>Итого: {check.score} баллов</li></div>"""
- html_generate += my_config.html_generate_css
- with open(f"{path_to_save}/check_{check.checker}_{check.essay.user}.html", "w") as text_file:
- text_file.write(html_generate)
- # weasyprint here
- html_generate = f"""<div class="main_content">
- <h2 class="tri_prov">3Проверочки</h2>
- <h4 class="tri_prov">Неделя {week_number}</h4>
- <div class="text"><p class="main_text">{text_parts}
- <p class="author_info_name">{text_author}</p>
- <p>{text_author_description}</p></div>
- <p style="page-break-before: always" ></p>"""
- def turner(request):
- if request.user.is_superuser:
- what_time = RUBILNIK.objects.all().order_by('-id').get()
- profile = Profile.objects.all()
- text = Text.objects.order_by('-id')[0:1].get()
- text.Number_of_essays = Essay.objects.filter(text=text).count()
- if what_time.sent_check == 0:
- # смена на этап сдачи сочинений
- what_time.sent_check = 1
- new_bad_user = Bad_user()
- new_bad_user.save()
- bad_user = Bad_user.objects.order_by('-id')[0:1].get()
- for _ in profile:
- # Список даунов, не проверивших все сочины...
- for is_bad_user in profile:
- if is_bad_user.check_number < 3:
- print('> ', is_bad_user.user)
- print('>>> ', is_bad_user.check_number)
- bad_user.user.add(is_bad_user.user)
- Essays_list.objects.all().delete()
- Questions_list.objects.all().delete()
- Answer.objects.all().delete()
- logger.info(f'{request.user} поменял на этап сдачи сочинений')
- logger.info('Бэкап проверок...')
- generate_checks_backup()
- else:
- # смена на этап сдачи проверок
- what_time.sent_check = 0
- Answer.objects.all().delete()
- Questions_list.objects.all().delete()
- logger.info(f'{request.user} поменял на этап сдачи проверок')
- logger.info('Бэкап сочинений...')
- generate_soch_backup()
- what_time.save()
- return redirect("/profile/#tab_1")
- else:
- return redirect('/')
- def error_404(request, exception):
- which_step_title = 'ошибка!'
- logger.error(f': {request.user} ошибка error_404 -> {exception}')
- data = {
- 'which_step_title': which_step_title,
- 'profile': profile,
- }
- return render(request, 'error_pages/error_page_404.html', data)
- def error_500(request):
- which_step_title = 'ошибка!'
- logger.error(f': {request.user} ошибка error_500')
- data = {
- 'which_step_title': which_step_title,
- 'profile': profile,
- }
- return render(request, 'error_pages/error_page_500.html', data)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement