Example #1
0
 def test_rich_text_nested_new_line(self):
     script = JinjaService()
     data = {"names": [{"name": "Dan\n Funk"}]}
     data_copy = copy.deepcopy(data)
     script.rich_text_update(data_copy)
     self.assertNotEqual(data, data_copy)
     self.assertIsInstance(data_copy["names"][0]["name"], Listing)
 def test_jinja_service_word_documents(self):
     filepath = os.path.join(app.root_path, '..', 'tests', 'data', 'template.docx')
     with open(filepath, 'rb') as myfile:
         file_data = BytesIO(myfile.read())
     context = {'title': 'My Title', 'my_list': ["a", "b", "c"], 'show_table': True}
     result = JinjaService().make_template(file_data, context)
     self.assertIsNotNone(result)  # Not a lot we can do here, just assure there is not an error.
 def test_jinja_service_word_document_errors_are_sensible(self):
     filepath = os.path.join(app.root_path, '..', 'tests', 'data', 'template_error.docx')
     with open(filepath, 'rb') as myfile:
         file_data = BytesIO(myfile.read())
     context = {'title': 'My Title', 'my_list': ["a", "b", "c"], 'show_table': True}
     with self.assertRaises(ApiError) as ae:
         result = JinjaService().make_template(file_data, context)
     self.assertIn('{{% no_such_variable_error ! @ __ %}}', ae.exception.error_line)
     self.assertEquals("Word Document creation error : unexpected '%'", ae.exception.message)
     self.assertEquals(14, ae.exception.line_number)
Example #4
0
def render_docx():
    """
    Provides a quick way to verify that a Jinja docx template will work properly on a given json
    data structure.  Useful for folks that are building these templates.
    """
    try:
        file = connexion.request.files['file']
        data = connexion.request.form['data']
        # TODO: This bypasses the Jinja service and uses complete_template script
        target_stream = JinjaService().make_template(file, json.loads(data))
        return send_file(
            io.BytesIO(target_stream.read()),
            as_attachment=True,
            attachment_filename="output.docx",
            mimetype="application/octet-stream",
            cache_timeout=-1  # Don't cache these files on the browser.
        )
    except ValueError as e:
        raise ApiError(code="undefined_field", message=str(e))
    except Exception as e:
        raise ApiError(code="invalid_render", message=str(e))
Example #5
0
def render_markdown(data, template):
    """
    Provides a quick way to very that a Jinja markdown template will work properly on a given json
    data structure.  Useful for folks that are building these markdown templates.
    """
    try:
        data = json.loads(data)
        return JinjaService.get_content(template, data)
    except UndefinedError as ue:
        raise ApiError(code="undefined_field", message=ue.message)
    except Exception as e:
        raise ApiError(code="invalid_render", message=str(e))
    def process_template(self, task, study_id, workflow=None, *args, **kwargs):
        """Entry point, mostly worried about wiring it all up."""
        if len(args) < 2 or len(args) > 3:
            raise ApiError(
                code="missing_argument",
                message=
                "The CompleteTemplate script requires 2 arguments.  The first argument is "
                "the name of the docx template to use.  The second "
                "argument is a code for the document, as "
                "set in the reference document %s. " %
                FileService.DOCUMENT_LIST)
        task_study_id = task.workflow.data[WorkflowProcessor.STUDY_ID_KEY]
        file_name = args[0]

        if task_study_id != study_id:
            raise ApiError(
                code="invalid_argument",
                message="The given task does not match the given study.")

        file_data = None
        if workflow is not None:
            # Get the workflow specification file with the given name.
            file_models = SpecFileService().get_spec_files(
                workflow_spec_id=workflow.workflow_spec_id,
                file_name=file_name)
            if len(file_models) > 0:
                file_model = file_models[0]
            else:
                raise ApiError(
                    code="invalid_argument",
                    message="Uable to locate a file with the given name.")
            file_data = SpecFileService().get_spec_file_data(
                file_model.id).data

        # Get images from file/files fields
        if len(args) == 3:
            image_file_data = self.get_image_file_data(args[2], task)
        else:
            image_file_data = None

        try:
            return JinjaService().make_template(BytesIO(file_data), task.data,
                                                image_file_data)
        except ApiError as ae:
            # In some cases we want to provide a very specific error, that does not get obscured when going
            # through the python expression engine. We can do that by throwing a WorkflowTaskExecException,
            # which the expression engine should just pass through.
            raise WorkflowTaskExecException(task,
                                            ae.message,
                                            exception=ae,
                                            line_number=ae.line_number,
                                            error_line=ae.error_line)
Example #7
0
    def get_rendered_content(self, message, data):
        content = JinjaService.get_content(message, data)
        rendered_markdown = markdown.markdown(content, extensions=['nl2br'])
        content_html = self.get_cr_connect_wrapper(rendered_markdown)

        return content, content_html
Example #8
0
 def test_rich_text_update(self):
     script = JinjaService()
     data = {"name": "Dan"}
     data_copy = copy.deepcopy(data)
     script.rich_text_update(data_copy)
     self.assertEqual(data, data_copy)