knd_klinteplo/classes/led.py
2022-01-19 18:38:00 +03:00

131 lines
5.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import datetime
import time
from natsort import natsorted
def assign_task(session, headers, task, address):
# print('assign_task')
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/assign'
task_assign = session.put(url, headers=headers)
if task_assign.status_code == 200:
print(f'Получили задание по адресу: {address}')
complete_task(session, headers, task, address)
else:
print(f"Не смогли получить задание {address} {task['id']}!")
def complete_task(session, headers, task, address):
photos = get_photo(address, headers['uid'])
if len(photos) > 0:
# photos.sort()
photos = natsorted(photos)
"""В папке лежит фото графика, которое отправляется из модуля des, поэтому убираем отсюда"""
# if len(photos) == 11 or len(photos) == 13:
# photos.pop()
id_task = task['id']
quest = get_questions(id_task, session, headers)
# print(quest)
# length_question = get_length_questions(quest)
prepared_answers = []
if True:
prepared_answers = prepare_answer(quest, photos, session, task, headers)
# print(prepared_answers)
ans = {"question_chains": prepared_answers}
# print(ans)
session_t = session
session_t.headers.update(
{
'referer': 'https://knd.mosreg.ru/executions'+str(task['id'])+'/solve',
'x-platform': 'android',
'accept': '*/*'
}
)
complete = session_t.post('https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/answers', headers=headers, json=ans)
if complete.status_code == 200:
print(f'Задание по адресу {address} выполнено успешно!\n\n')
else:
print(f'Задание по адресу {address} не выполненно! Статус ошибки {complete.status_code}\n\n')
else:
print(f"\n\n\nНесоответствие количества вопросов и фотографий по адресу {address}!!! \
Необходимо проверить!!!\n\n\n")
# print(len(quest)) 9 and 13
def get_photo(address, email):
photos = []
month = datetime.datetime.now().month
main_path = os.path.join(os.path.abspath('.'), 'data_led', email, address)
if not os.path.exists(main_path):
return photos
else:
for images in os.listdir(main_path):
if images.endswith(".jpg") or images.endswith(".jpeg") or images.endswith(".JPG"):
photos.append(main_path + '/' + images)
return photos
def get_questions(id_task, session, headers):
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(id_task)+'/questions'
questions = session.get(url, headers=headers)
json_quest = questions.json()
return json_quest['selected_chains']
def prepare_answer(quest, photos, session, task, headers):
questions = []
question_components= []
question_chains = []
for main_chain in quest:
for second_chain in main_chain['questions']:
for third_chain in second_chain['question_components']:
question_type = third_chain['type']
if question_type == 'list':
data = {"id": third_chain['id'], "answer": 77, "answer_status": None, "start_time": int(time.time())}
time.sleep(2)
data.update({"end_time": int(time.time())})
question_components.append(data)
elif question_type == "geo":
data = {"id": third_chain['id'], "answer": {"location": task['coord']}, "answer_status": None, \
"start_time": int(time.time())}
time.sleep(2)
data.update({"end_time": int(time.time())})
question_components.append(data)
elif question_type == "gallery":
img = send_image(session, headers, task['id'], photos.pop(0))#photos.pop(0))
data = {"id": third_chain['id'], "answer": [img['id']], "answer_status": None, \
"start_time": int(time.time())}
time.sleep(2)
data.update({"end_time": int(time.time())})
question_components.append(data)
if len(question_components) > 0:
main_data = {
"id": second_chain['id'],
"question_components": question_components
}
questions.append(main_data)
question_components = []
if len(questions) > 0:
q_dict = {
"id": main_chain['id'],
"questions" : questions
}
question_chains.append(q_dict)
questions = []
return question_chains
def send_image(session, headers, url, photo):
"""Отправляем фото на сервер. Сервер должен вернуть id и url."""
files = {
'image': (photo[-5:], open(photo, 'rb')),
}
img = session.post('https://knd.mosreg.ru//api/v1/executions/'+str(url)+'/images', headers=headers, files=files)
if img.status_code == 200:
print(f"Фото {photo} успешно отправлено")
return img.json()
else:
print(f"Не удалось загрузить фото на сервер по заданию {url}, статус ошибки {img.status_code}! Повторная попытка!")
second_img = send_image(session, headers, url, photo)
return second_img