Пример #1
0
 def post(self):
     """
     """
     args = file_upload.parse_args()
     try:
         file_temp = tempfile.TemporaryFile()
         args['yml_file'].save(file_temp)
         filename = os.path.splitext(
             os.path.basename(os.path.normpath(
                 args['yml_file'].filename)))[0]
         print(filename)
         file_temp.seek(0)
         yaml_input = file_temp.read().decode()
         file_out = tempfile.NamedTemporaryFile()
         fon = "%s%s" % (file_out.name, '.png')
         outputname = "%s%s" % (fon, '.png')
         resultfilename = "%s%s" % (filename, '.png')
         mimetype = 'image/png'
         if request.headers["accept"] == "image/svg+xml":
             fon = "%s%s" % (file_out.name, '.svg')
             outputname = "%s%s" % (fon, '.svg')
             mimetype = 'image/svg+xml'
             resultfilename = "%s%s" % (filename, '.svg')
         wireviz.parse(yaml_input, file_out=fon)
         return send_file(outputname,
                          as_attachment=True,
                          attachment_filename=resultfilename,
                          mimetype=mimetype)
     except Exception as e:
         print(e)
         return make_response(
             jsonify({
                 'message': 'internal error',
                 'exception': str(e)
             }), 500)
Пример #2
0
    def export_all(self):
        file_name = asksaveasfilename()
        if file_name is None or file_name.strip() == '':
            return

        try:
            parse(
                yaml_input=self._text_entry_frame.get(),
                file_out=file_name,
                generate_bom=True,
            )
        except ExecutableNotFound:
            showerror('Error', 'Graphviz executable not found; Make sure that the '
                               'executable is installed and in your system PATH')
            return
Пример #3
0
    def export_all(self):
        self.refresh_view()

        file_name = asksaveasfilename()
        if file_name is None or file_name.strip() == '':
            return

        path = Path(file_name)

        if self._text_entry_frame.get().strip() != '':
            try:
                parse(yaml_input=self._text_entry_frame.get(), file_out=path)
            except ExecutableNotFound:
                showerror(
                    'Error',
                    'Graphviz executable not found; Make sure that the '
                    'executable is installed and in your system PATH')
                return
            return

        self._harness.output(filename=path, fmt=('png', 'svg'), view=False)
Пример #4
0
 def get(self, encoded):
     """
     """
     try:
         file_out = tempfile.NamedTemporaryFile()
         fon = "%s%s" % (file_out.name, '.png')
         outputname = "%s%s" % (fon, '.png')
         resultfilename = "%s%s" % ('png_rendered', '.png')
         mimetype = 'image/png'
         wireviz.parse(plant_uml_decoder.plantuml_decode(encoded),
                       file_out=fon)
         return send_file(outputname,
                          as_attachment=True,
                          attachment_filename=resultfilename,
                          mimetype=mimetype)
     except Exception as e:
         print(e)
         return make_response(
             jsonify({
                 'message': 'internal error',
                 'exception': str(e)
             }), 500)
Пример #5
0
    def parse_text(self):
        """
        This is where the data is read from the text entry and parsed into an image

        :return:
        """
        if self._text_entry_frame.get().strip() != '':
            f_in = StringIO(self._text_entry_frame.get())

            try:
                harness = parse(f_in, return_types='harness')
            except (TypeError, ):
                showerror('Parse Error', 'Input is invalid or missing')
                return
            except (ParserError, ScannerError) as e:
                lines = str(e).lower()
                for line in lines.split('\n'):
                    if 'line' in line:
                        # determine the line number that has a problem
                        parts = [l.strip() for l in line.split(',')]
                        part = [l for l in parts if 'line' in l][0]
                        error_line = part.split(' ')[1]
                        self._text_entry_frame.highlight_line(error_line)
                        break
                showerror('Parse Error', f'Input is invalid: {e}')
                return
            except ExecutableNotFound:
                showerror(
                    'Error',
                    'Graphviz executable not found; Make sure that the '
                    'executable is installed and in your system PATH')
                return

            # copy the attributes of the new harness
            self._harness.connectors = harness.connectors
            self._harness.cables = harness.cables
            self._additional_bom_items = harness.additional_bom_items

        self._text_entry_frame.highlight_line(None)

        self.refresh_view()
Пример #6
0
    def refresh(self):
        """
        This is where the data is read from the text entry and parsed into an image

        :return:
        """
        f_in = StringIO(self._text_entry_frame.get())

        try:
            data = parse(f_in, return_types=('png', ))[0]
        except (TypeError, ):
            showerror('Parse Error', 'Input is invalid or missing')
            return
        except (ParserError, ScannerError) as e:
            lines = str(e).lower()
            for line in lines.split('\n'):
                if 'line' in line:
                    # determine the line number that has a problem
                    parts = [l.strip() for l in line.split(',')]
                    part = [l for l in parts if 'line' in l][0]
                    error_line = part.split(' ')[1]
                    self._text_entry_frame.highlight_line(error_line)
                    break
            showerror('Parse Error', f'Input is invalid: {e}')
            return
        except ExecutableNotFound:
            showerror('Error', 'Graphviz executable not found; Make sure that the '
                               'executable is installed and in your system PATH')
            return

        photo = ImageTk.PhotoImage(data=data)

        self._harness_frame\
            .update_image(photo_image=photo)

        self._text_entry_frame.highlight_line(None)
Пример #7
0
def wireviz_render(input_yaml: str, output_mimetype: str,
                   output_filename: str) -> Response:
    """
    Render WireViz output and create a Flask Response.

    :param input_yaml:      Input data in WireViz YAML format.
    :param output_mimetype: The designated output format mimetype. Currently available:
                            - image/svg+xml
                            - image/png
                            - text/html
                            - text/plain
                            - application/json
    :param output_filename: The designated output filename.
    :return:                A Flask Response object.
    """

    # Sanity checks.
    if not input_yaml.strip():
        raise BadRequest(description="No input data")

    # Compute output type from MIME type.
    return_type = mimetype_to_type(output_mimetype)

    # Parse WireViz YAML.
    try:
        harness: Harness = wireviz.parse(yaml_input=input_yaml,
                                         return_types="harness")
    except Exception as ex:
        message = f"Unable to parse WireViz YAML format: {ex}"
        logger.exception(message)
        raise BadRequest(description=message)

    # Dispatch rendering by designated output type.
    if return_type == "png":
        payload = harness.png

    elif return_type == "svg":
        payload = harness.svg

    elif return_type == "html":
        try:
            tmpfile = NamedTemporaryFile(delete=False)

            # Build list of implicitly created temporary files.
            tempfiles = []
            for suffix in [".gv", ".png", ".svg", ".bom.tsv", ".html"]:
                tempfiles.append(f"{tmpfile.name}{suffix}")

            # Render HTML output.
            harness.output(filename=tmpfile.name, fmt=("png", "svg"))
            with open(f"{tmpfile.name}.html", "rb") as f:
                payload = f.read()

        except Exception as ex:  # pragma: no cover
            message = f"Unable to produce WireViz output: {ex}"
            logger.exception(message)
            raise BadRequest(description=message)

        finally:
            # Clean up temporary files.
            for tempfile in tempfiles:
                try:
                    Path(tempfile).unlink(missing_ok=True)
                except (FileNotFoundError, TypeError):  # pragma: no cover
                    pass

    elif return_type == "bom.txt":
        harness.create_graph()
        bom_list = harness.bom_list()
        payload = tuplelist2tsv(bom_list).encode("utf-8")

    elif return_type == "bom.json":
        harness.create_graph()
        bom_list = harness.bom_list()
        payload = json.dumps(bom_list, indent=2).encode("utf-8")

    # Respond with rendered image.
    return send_file(
        io.BytesIO(payload),
        mimetype=output_mimetype,
        as_attachment=True,
        attachment_filename=output_filename,
    )