def get(dereg_id):
        """GET method handler, returns documents."""
        no_error = dereg_id.isdigit() and DeRegDetails.exists(dereg_id)
        if not no_error:
            return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            schema = DeRegDocumentsSchema()
            documents = DeRegDocuments.get_by_reg_id(dereg_id)
            documents = schema.dump(documents, many=True).data
            return Response(json.dumps(documents),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        except Exception as e:  # pragma: no cover
            app.logger.exception(e)
            data = {
                "message": [_("Error retrieving results. Please try later.")]
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get("BAD_REQUEST"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        finally:
            db.session.close()
Ejemplo n.º 2
0
    def get(dereg_id):
        """GET method handler, returns documents."""
        no_error = dereg_id.isdigit() and DeRegDetails.exists(dereg_id)
        if not no_error:
            return Response(json.dumps(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            schema = DeRegDocumentsSchema()
            documents = DeRegDocuments.get_by_reg_id(dereg_id)
            documents = schema.dump(documents, many=True).data
            '''if doc_id:
                if not doc_id.isdigit():
                    documents = DOC_NOT_FOUND_MSG
                else:
                    documents = list(filter(lambda doc: int(doc['id']) == int(doc_id), documents))
                    documents = documents[0] if documents else DOC_NOT_FOUND_MSG
            '''
            return Response(json.dumps(documents),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        except Exception as e:
            app.logger.exception(e)
            data = {"message": "Error retrieving results. Please try later."}

            return Response(json.dumps(data),
                            status=CODES.get("BAD_REQUEST"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        finally:
            db.session.close()
Ejemplo n.º 3
0
    def put():
        """PUT method handler, updates documents."""
        dereg_id = request.form.to_dict().get('dereg_id', None)
        if not dereg_id or not dereg_id.isdigit() or not DeRegDetails.exists(
                dereg_id):
            return Response(json.dumps(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            schema = DeRegDocumentsUpdateSchema()
            time = datetime.now().strftime('%Y%m%d%H%M%S')
            args = request.form.to_dict()
            args = Utilities.update_args_with_file(request.files, args)
            dereg_details = DeRegDetails.get_by_id(dereg_id)
            if dereg_details:
                args.update({
                    'dereg_details': dereg_details.id,
                    'status': dereg_details.status
                })
            else:
                args.update({'dereg_details': ''})
            validation_errors = schema.validate(args)
            if validation_errors:
                return Response(json.dumps(validation_errors),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            tracking_id = dereg_details.tracking_id
            updated = DeRegDocuments.bulk_update(request.files, dereg_details,
                                                 time)
            response = Utilities.store_files(request.files, tracking_id, time)
            if response:
                return Response(json.dumps(response),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if dereg_details.status == Status.get_status_id(
                    'Information Requested'):
                dereg_details.update_status('In Review')
            else:
                dereg_details.update_status('Pending Review')
            response = schema.dump(updated, many=True).data
            db.session.commit()
            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:
            db.session.rollback()
            app.logger.exception(e)

            data = {
                'message':
                'request document updation failed, please try again later.'
            }

            return Response(json.dumps(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
Ejemplo n.º 4
0
def create_dummy_documents(files, request_type, request, app=None):
    """Helper method to create dummy documents for a request.
    """
    if request_type == 'Registration':
        current_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        for file in files:
            document = Documents.get_document_by_name(file.get('label'), 1)
            reg_doc = RegDocuments(filename='{0}_{1}'.format(current_time, file.get('file_name')))
            reg_doc.reg_details_id = request.id
            reg_doc.document_id = document.id
            reg_doc.save()

            file_path = '{0}/{1}/{2}'.format(app.config['DRS_UPLOADS'], request.tracking_id, file.get('file_name'))
            if not os.path.exists(os.path.dirname(file_path)):
                os.makedirs(os.path.dirname(file_path))
            with open(file_path, 'wb') as f:
                f.seek(1073741824-1)
                f.write(b"\0")
    else:
        current_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        for file in files:
            document = Documents.get_document_by_name(file.get('label'), 2)
            dereg_doc = DeRegDocuments(filename='{0}_{1}'.format(current_time, file.get('file_name')))
            dereg_doc.dereg_id = request.id
            dereg_doc.document_id = document.id
            dereg_doc.save()

            file_path = '{0}/{1}/{2}'.format(app.config['DRS_UPLOADS'], request.tracking_id, file.get('file_name'))
            if not os.path.exists(os.path.dirname(file_path)):
                os.makedirs(os.path.dirname(file_path))
            with open(file_path, 'wb') as f:
                f.seek(1073741824-1)
                f.write(b"\0")
    return request
Ejemplo n.º 5
0
    def get(dereg_id):
        """GET method handler, to return all section of a request."""
        try:
            if not dereg_id.isdigit() or not DeRegDetails.exists(dereg_id):
                return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            dereg_details = DeRegDetails.get_by_id(dereg_id)
            dereg_schema = DeRegDetailsSchema()
            doc_schema = DeRegDocumentsSchema()
            device_schema = DeRegDeviceSchema()

            dereg_devices = DeRegDevice.get_devices_by_dereg_id(dereg_id)
            dereg_documents = DeRegDocuments.get_by_reg_id(dereg_id)

            deregistration_data = dereg_schema.dump(dereg_details).data
            device_data = device_schema.dump(dereg_devices, many=True).data
            document_data = doc_schema.dump(dereg_documents, many=True).data

            response = {
                'dereg_details': deregistration_data,
                'dereg_device': device_data,
                'dereg_docs': document_data
            }

            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            app.logger.exception(e)

            data = {
                'message': [
                    _('De-Registration request failed, check upload path or database connection'
                      )
                ]
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
Ejemplo n.º 6
0
    def post():
        """POST method handler, creates documents."""
        dereg_id = request.form.to_dict().get('dereg_id', None)
        if not dereg_id or not dereg_id.isdigit() or not DeRegDetails.exists(
                dereg_id):
            return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            schema = DeRegDocumentsSchema()
            time = datetime.now().strftime('%Y%m%d%H%M%S')
            args = request.form.to_dict()
            args = Utilities.update_args_with_file(request.files, args)
            dereg_details = DeRegDetails.get_by_id(dereg_id)
            if dereg_details:
                args.update({
                    'dereg_details': dereg_details.id,
                    'status': dereg_details.status
                })
            else:
                args.update({'dereg_details': ''})

            validation_errors = schema.validate(args)
            if validation_errors:
                return Response(app.json_encoder.encode(validation_errors),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            tracking_id = dereg_details.tracking_id
            created = DeRegDocuments.bulk_create(request.files, dereg_details,
                                                 time)
            response = Utilities.store_files(request.files, tracking_id, time)
            if response:
                return Response(app.json_encoder.encode(response),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            dereg_details.update_status('Pending Review')
            message = schema.dump(created, many=True).data
            log = EsLog.new_doc_serialize(message,
                                          request_type="De-Registration",
                                          regdetails=dereg_details,
                                          reg_status="Pending Review",
                                          method='Post',
                                          request='De-Registration')
            db.session.commit()
            EsLog.insert_log(log)
            return Response(json.dumps(message),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            db.session.rollback()
            app.logger.exception(e)

            data = {
                'message':
                _('request document addition failed, check for valid formats.')
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()