def get_classrooms_of_one_volunteer(volunteer_id): try: volunteer = util.query_model(model=Volunteer, id=volunteer_id) classrooms = (db.session.query( Classroom, Student.name).filter_by(volunteer_id=volunteer_id).join( Student, Classroom.student_id == Student.id).order_by( Classroom.id).all()) if not classrooms: raise APIException("Resource Not Found", 404) classroom_info_list = [{ **classroom.long(), **{ "student_name": student_name } } for classroom, student_name in classrooms] response = { "volunteer_id": volunteer_id, "volunteer_name": volunteer.name, "count": len(classrooms), "classrooms": classroom_info_list } return jsonify(response), 200 except GenericException as e: raise e except Exception: raise APIException("Internal Error", 500)
async def create_task(request: Request) -> Response: """ Обработчик POST-запроса для создания задачи по сбору информации о компаниях. Ожидается json формата: { "name": "Иванов" } где "Иванов" - название компании. Ответ: < HTTP/1.1 202 Accepted < Content-Length: 180 < Content-Type: application/json < Connection: keep-alive < Keep-Alive: 5 body: { "name": "Иванов", "uuid": "d32e302c-7d86-4f1d-9295-370bbcf20c63", "link for check": "http://localhost:8000/v1/names/d32e302c-7d86-4f1d-9295-370bbcf20c63" } :param Request request: - тело запроса. """ name = None if request.json is not None: name = request.json.get('name', None) if name is None: raise APIException( message="key 'name' in body json is not found. please repeat " "the request with the key 'name'", status=400) local_uuid = generate_uuid() try: pool = request.app.pool asyncio.ensure_future(parse_data(local_uuid, name, pool)) uri_check = request.app.url_for('names.get_information', name=local_uuid) link_for_check = f"{request.scheme}://{request.host}{uri_check}" return json( { 'name': name, 'uuid': str(local_uuid), 'link for check': link_for_check, }, status=202, escape_forward_slashes=False) except Exception as error: logger.do_write_error('no database connection.', error) raise APIException( message='An error has occurred. Please try again later.', status=500)
async def get(self, request): try: logger.info(f"Get new request - {request.query}") result = await self._perform_get(dict(request.query)) return web.json_response(result) except Exception as e: if not isinstance(e, APIException): logger.exception("Unhandled error - {}", e, exc_info=True) e = APIException(message="Oops, something happens !:(", http_code=500) return web.json_response(data=e.to_error(), status=e.http_code)
def query_model(model, id=None): try: if id is not None: result = model.query.get(id) else: result = model.query.order_by('id').all() if not result: raise APIException("Resource Not Found", 404) return result except: raise APIException("Resource Not Found", 404)
def edit_student(student_id): try: body = request.get_json() student = util.query_model(model=Student, id=student_id) if 'name' in body: student.name = body['name'] if 'age' in body: student.age = util.compute_int(body['age']) if 'gender' in body: student.gender = body['gender'] if 'image_link' in body: student.image_link = body['image_link'] if 'profile_link' in body: student.profile_link = body['profile_link'] if 'seeking_volunteer' in body: student.seeking_volunteer = util.compute_boolean( body['seeking_volunteer']) if 'seeking_description' in body: student.seeking_description = body['seeking_description'] student.update() return jsonify({"success": True}), 200 except GenericException as e: raise e except Exception: raise APIException("Bad Request", 400)
def handle_form(): ''' Web entrypoint ''' try: assert request.is_json received_data = request.get_json() validate(received_data, CONTACT_FORM_SCHEMA) do_recaptcha_validation(received_data["recaptcha_response"]) drupal_response = post_drupal_contact_message(received_data) response = APP.response_class(response=json.dumps( jsend.success({'data': drupal_response})), status=201, mimetype='application/json') return response except (RecaptchaError, ValidationError, AssertionError): raise APIException("Invalid captcha or bad request") except: raise APIException("Server error", 500)
def build_config(code): url = config["oauth_url"] headers = {"Content-Type": "application/json"} payload = { "client_id": os.environ.get(config["oauth_client_id"]), "client_secret": os.environ.get(config["oauth_client_secret"]), "code": code, } # Raise exceptions if client_id or client_secret not found. if not payload["client_id"]: raise APIException("Client Id is not found in environment", status_code=422) if not payload["client_secret"]: raise APIException("Client secret is not found in environment", status_code=422) return url, headers, payload
def get_access_token(url, headers, payload): response = requests.post(url, headers=headers, params=payload) # If client id not found if response.text == "Not Found": raise APIException("Client id is invalid", status_code=404) qs = dict(parse_qsl(response.text)) creds = {item: qs[item] for item in qs} return creds
def _raise_for_status(self, response): ''' To be completed: Error and Exception Class ''' try: response.raise_for_status() except request.exceptions.HTTPError as e: # if e.response.status_code == 404: # raise NotFoundError(e, response) raise APIException(e, response)
def get_one_classroom_info(classroom_id): try: classroom = util.query_model(model=Classroom, id=classroom_id) return jsonify(classroom.long()), 200 except GenericException as e: raise e except Exception: raise APIException("Internal Error", 500)
def get_one_student_info(student_id): try: student = util.query_model(model=Student, id=student_id) return jsonify(student.long()), 200 except GenericException as e: raise e except Exception: raise APIException("Internal Error", 500)
def get_one_volunteer_info(volunteer_id): try: volunteer = util.query_model(model=Volunteer, id=volunteer_id) return jsonify(volunteer.long()), 200 except GenericException as e: raise e except Exception: raise APIException("Internal Error", 500)
def remove_classroom(classroom_id): try: classroom = util.query_model(model=Classroom, id=classroom_id) classroom.delete() return jsonify({"success": True}), 200 except GenericException as e: raise e except Exception: raise APIException("Internal Error", 500)
def get_students(): try: students = util.query_model(model=Student, id=None) students_list = [student.short() for student in students] response = {"count": len(students), "volunteers": students_list} return jsonify(response), 200 except GenericException as e: raise e except Exception: raise APIException("Internal Error", 500)
def remove_student(student_id): try: student = util.query_model(model=Student, id=student_id) student.delete() return jsonify({"success": True}), 200 except GenericException as e: raise e except Exception: raise APIException("Internal Error", 500)
def remove_volunteer(volunteer_id): try: volunteer = util.query_model(model=Volunteer, id=volunteer_id) volunteer.delete() return jsonify({"success": True}), 200 except GenericException as e: raise e except Exception: raise APIException("Internal Error", 500)
def get_volunteers(): try: volunteers = util.query_model(model=Volunteer, id=None) volunteers_list = [volunteer.short() for volunteer in volunteers] response = {"count": len(volunteers), "volunteers": volunteers_list} return jsonify(response), 200 except GenericException as e: raise e except Exception: raise APIException("Internal Error", 500)
def search_by_name_pattern(model, search_term): search = "%{}%".format(search_term.lower()) matching_by_name_list = model.query.filter( model.name.ilike(search)).order_by('id').all() matching_by_description_list = model.query.filter( model.seeking_description.ilike(search)).order_by('id').all() matching_list = list( set(matching_by_name_list + matching_by_description_list)) if not matching_list: raise APIException("Resource Not Found", 404) return matching_list
def get_emotion_stream_cut_with_timeout(video_path, detector, frame_interval_ms, start_ms, end_ms, time_limit_second): video_capture = cv2.VideoCapture(video_path) try: video_capture.isOpened() except Exception as ex: raise ex fps = video_capture.get(cv2.CAP_PROP_FPS) frame_count = video_capture.get(cv2.CAP_PROP_FRAME_COUNT) start_frame_no = ms2frame(fps, start_ms) + 1 # 加一防止为0的情况 end_frame_no = ms2frame(fps, end_ms) if end_ms < 0 or end_frame_no > frame_count: end_frame_no = frame_count if start_frame_no < 1: start_frame_no = 1 if start_frame_no > end_frame_no: return [] interval_frame_num = ms2frame(fps, frame_interval_ms) emotion_stream = [] if interval_frame_num < 1: interval_frame_num = 1 # 防止帧间隔为0的情况 start_time = Time.time() while start_frame_no <= end_frame_no: video_capture.set(cv2.CAP_PROP_POS_FRAMES, start_frame_no) frame = video_capture.read()[1] if frame is None or np.size(frame) is 0: start_frame_no += interval_frame_num continue time = int(video_capture.get(cv2.CAP_PROP_POS_MSEC)) prediction, _ = detector.detect_biggest(frame) now_time = Time.time() if now_time - start_time > time_limit_second: raise APIException(500, config.TIMEOUT) if prediction is None: start_frame_no += interval_frame_num continue # 计算最最大表情值所占百分比,再乘以1000,转为整数,再除以1000,变为float相当于保留三位小数 rate = int(np.max(prediction) / np.sum(prediction) * 1000) / 1000.0 emotion_text = get_labels('fer2013')[np.argmax(prediction)] frame_emotion = FrameEmotion(time, emotion_text, rate) # 转换为便于转成json的字典格式 emotion_stream.append(frame_emotion.__dict__) start_frame_no += interval_frame_num video_capture.release() return emotion_stream
def call_api(base_url, resource, data=None): '''an simple encapsulation for request a rest api ''' try: payload = urlencode(data) if data else None if py_version >= 3 and payload is not None: payload = payload.encode('utf-8') response = urlopen(base_url + resource, payload, timeout=10).read() return compat_response(response) except HTTPError as e: raise APIException(compat_response(e.read()), e.code)
async def _parse_response(self, response: 'ClientResponse') -> dict: """ Метод разбирает ответ сервиса OpenWeather, и подставляет в ответ только интересующие значения. """ try: data = await response.json() result = { "temp": data["main"]["temp"], "temp_min": data["main"]["temp_min"], "temp_max": data["main"]["temp_max"], } return result except ContentTypeError: logger.error('Unexpected format OpenWeather') raise APIException(message="External services error", http_code=500)
def do_recaptcha_validation(response): ''' Perform a server-side Google ReCaptcha validation ''' with requests.post('https://www.google.com/recaptcha/api/siteverify', data={ "secret": APP.config["RECAPTCHA_SECRET_KEY"], "response": response }) as req: try: req.raise_for_status() json_response = req.json() assert json_response['success'] == True except AssertionError: raise RecaptchaError("Invalid", json_response['error-codes']) except requests.exceptions.RequestException: raise APIException("Failed to connect to ReCaptcha Service", 503) else: return True
def create_classroom(): try: body = request.get_json() classroom = Classroom(description=body['description'], time=body['time'], start_date=body['start_date'], end_date=body.get('end_date'), volunteer_id=body['volunteer_id'], student_id=body['student_id']) classroom.insert() return jsonify({"success": True}), 200 except GenericException as e: raise e except Exception: raise APIException("Bad Request", 400)
def post_drupal_contact_message(contact): ''' Post contact message to Drupal ''' with requests.post(APP.config["DRUPAL_CONTACT_MESSAGE_URL"], json={ "contact_form": APP.config["DRUPAL_CONTACT_FORM_ID"], "message": [contact["message"]], "subject": ["Contato - " + contact["name"]], "mail": [contact["mail"]], "name": [contact["name"]] }, auth=(APP.config["DRUPAL_AUTH_USER"], APP.config["DRUPAL_AUTH_PASSWORD"])) as req: try: req.raise_for_status() except requests.exceptions.RequestException: raise APIException("Failed to connect to Drupal", 503) else: return req.json()
def _raise_errors(response): """ Checks the requests.Response object body for any API-level errors, then checks whether we received a 4xx- or 5xx-level response code. Raises an exception for any undesirables. """ api_error = None http_error = 400 <= response.status_code try: body = response.json() api_error = (body.get('error', False) or body.get('meta', {}).get('error_message')) except: pass if api_error: raise APIException(api_error) elif http_error: raise HTTPException("HTTP %d: %s" % (response.status_code, response.text))
def register_student(): try: body = request.get_json() student = Student(name=body['name'], age=util.compute_int(body['age']), gender=body.get('gender', 'NA'), email=body['email'], image_link=body.get('image_link', ''), profile_link=util.compute_profile_link(), seeking_volunteer=util.compute_boolean( body['seeking_volunteer']), seeking_description=body['seeking_description']) student.insert() return jsonify({"success": True}), 200 except GenericException as e: raise e except Exception: raise APIException("Bad Request", 400)
async def _perform_get(self, params: dict) -> dict: """ Метод, содержащий общую логику получения данных о погоде для запрашиваемого города. """ if not self.validator.validate(params): logger.error("Failed to validate incoming params") raise APIException(message="Unexpected request message", details=self.validator.errors) weather = await client.get_weather( city=self.validator.document["city"], units=self.validator.document["units"], ) # Добавляем к ответу единицы измерения weather["units"] = self.validator.document["units"] # Поле `response` используется для пробрасывания на клиента расширенной информации # об ошибке. В случае успешной операции так же возвращается для унификации API. result = {"weather": weather, "response": {}} return result
def search_student(): """ Search for pattern match in name and seeking_description""" try: search_term = request.get_json().get('search_term', '') matching_students = util.search_by_name_pattern( model=Student, search_term=search_term) matching_students_info = [ student.long() for student in matching_students ] response = { "search_term": search_term, "count": len(matching_students), "students": matching_students_info } return jsonify(response), 200 except GenericException as e: raise e except Exception: raise APIException("Internal Error", 500)
def replay_data(map_id, user_id): """ Queries the api for replay data from the given user on the given map. Args: String map_id: The map id to get the replay off of. String user_id: The user id to get the replay of. Returns: The lzma bytes (b64 decoded response) returned by the api, or None if the replay was not available. Raises: APIException if the api responds with an error we don't know. """ print("Requesting replay by {} on map {}".format(user_id, map_id)) response = requests.get(API_REPLAY.format(map_id, user_id)).json() error = Loader.check_response(response) if (error == Error.NO_REPLAY): print( "Could not find any replay data for user {} on map {}, skipping" .format(user_id, map_id)) return None elif (error == Error.RETRIEVAL_FAILED): print("Replay retrieval failed for user {} on map {}, skipping". format(user_id, map_id)) return None elif (error == Error.RATELIMITED): Loader.enforce_ratelimit() return Loader.replay_data(map_id, user_id) elif (error == Error.UNKOWN): raise APIException( "unkown error when requesting replay by {} on map {}. Please lodge an issue with the devs immediately" .format(user_id, map_id)) return base64.b64decode(response["content"])
def search_volunteer(): """ Search for pattern match in name and seeking_description""" try: search_term = request.get_json().get('search_term', '') matching_volunteers = util.search_by_name_pattern( model=Volunteer, search_term=search_term) matching_volunteers_info = [ volunteer.long() for volunteer in matching_volunteers ] response = { "search_term": search_term, "count": len(matching_volunteers), "volunteers": matching_volunteers_info } return jsonify(response), 200 except GenericException as e: raise e except Exception: print(sys.exc_info()) raise APIException("Internal Error", 500)