Package cloudofficeprint

This Python package provides a programmatic interface with a Cloud Office Print server.

Usage

The examples below call this package cop.

import cloudofficeprint as cop

Templates

Templates are represented by Resource. The simplest way to obtain a Resource is to load from a local path.

template = cop.Resource.from_local_file("./path/to/template.docx")

Render elements

Most render elements encapsulate the data for a single tag. An elements.ElementCollection is an element which represents a collection of elements.

Combining a simple line chart and some text tags:

line = cop.elements.LineChart(
    "linechart",
    cop.elements.LineSeries([1, 2, 3, 4], [1, 2, 3, 4], color="green"),
    cop.elements.XYSeries([1, 2, 3, 4], ["a", "b", "c", "d"])
)

text_tag = cop.elements.Property("tag-name", "Hello, world!")
# or multiple at once using ElementCollection.from_mapping
# and supplying the dictionary representation directly
text_tags = cop.elements.ElementCollection.from_mapping({
    "another-tag": "Foo",
    "one-more-tag": "Bar"
})

combined_data = cop.elements.ElementCollection()
combined_data.add(line)
combined_data.add(text_tag)
combined_data.add_all(text_tags)

The server

A Cloud Office Print server is configured as a config.Server. It takes a url and an optional config.ServerConfig which allows for various server configuration options. If you're using Cloud Office Print Cloud edition, you will need to use this to declare your API key.

server = cop.config.Server(
    "http://server.url.com/",
    cop.config.ServerConfig(api_key = "YOUR_API_KEY")
)

PrintJob combines template, data, server and an optional output configuration (config.OutputConfig) and can execute itself on the Cloud Office Print server. An example using the variables declared above:

printjob = cop.PrintJob(combined_data, server, template)
printjob.execute()

A print job can be executed asynchronously as well.

import asyncio
coroutine = printjob.execute_async()
# simply await your result when you need it
result = await coroutine

Full JSON available

If you already have the JSON to be sent to the server (not just the data, but the entire JSON body including your API key and template), this package will wrap the request to the server for you (requests are made using requests).

json_data = open("./path/to/data.json", "r").read()
cop.PrintJob.execute_full_json(
        json_data, server
    ).to_file("./test/from_full_json_output")

Server errors

In case the Cloud Office Print server returns an error, PrintJob will throw one as well. You can catch it and get either its user-readable message or an encoded stack trace that can be passed to Cloud Office Print support.

try:
    # execute some previously constructed printjob
    printjob.execute()
except cop.exceptions.COPError as err:
    print("Cloud Office Print error! " + err.user_message)
    print(err.encoded_message)
    ...

Further information

For further information, such as where to find our examples, we refer to our README.md file on our Github page.

Expand source code
"""
This Python package provides a programmatic interface with a [Cloud Office Print](https://www.cloudofficeprint.com) server.

## Usage
The examples below call this package cop.
```python
import cloudofficeprint as cop
```

### Templates
Templates are represented by `Resource`. The simplest way to obtain a `Resource` is to load from a local path.
```python
template = cop.Resource.from_local_file("./path/to/template.docx")
```

### Render elements
Most render elements encapsulate the data for a single tag. An `elements.ElementCollection` is an element which represents a collection of elements.

Combining a simple line chart and some text tags:
```python
line = cop.elements.LineChart(
    "linechart",
    cop.elements.LineSeries([1, 2, 3, 4], [1, 2, 3, 4], color="green"),
    cop.elements.XYSeries([1, 2, 3, 4], ["a", "b", "c", "d"])
)

text_tag = cop.elements.Property("tag-name", "Hello, world!")
# or multiple at once using ElementCollection.from_mapping
# and supplying the dictionary representation directly
text_tags = cop.elements.ElementCollection.from_mapping({
    "another-tag": "Foo",
    "one-more-tag": "Bar"
})

combined_data = cop.elements.ElementCollection()
combined_data.add(line)
combined_data.add(text_tag)
combined_data.add_all(text_tags)
```

### The server
A Cloud Office Print server is configured as a `config.Server`. It takes a url and an optional `config.ServerConfig` which allows for various server configuration options. If you're using Cloud Office Print Cloud edition, you will need to use this to declare your API key.

```python
server = cop.config.Server(
    "http://server.url.com/",
    cop.config.ServerConfig(api_key = "YOUR_API_KEY")
)
```

### Print job
`PrintJob` combines template, data, server and an optional output configuration (`config.OutputConfig`) and can execute itself on the Cloud Office Print server. An example using the variables declared above:

```python
printjob = cop.PrintJob(combined_data, server, template)
printjob.execute()
```

A print job can be executed asynchronously as well.

```python
import asyncio
coroutine = printjob.execute_async()
# simply await your result when you need it
result = await coroutine
```

### Full JSON available
If you already have the JSON to be sent to the server (not just the data, but the entire JSON body including your API key and template), this package will wrap the request to the server for you (requests are made using [requests](https://requests.readthedocs.io/en/master/)).
```python
json_data = open("./path/to/data.json", "r").read()
cop.PrintJob.execute_full_json(
        json_data, server
    ).to_file("./test/from_full_json_output")
```

### Server errors
In case the Cloud Office Print server returns an error, `PrintJob` will throw one as well.
You can catch it and get either its user-readable message or an encoded stack trace that can be passed to Cloud Office Print support.
```python
try:
    # execute some previously constructed printjob
    printjob.execute()
except cop.exceptions.COPError as err:
    print("Cloud Office Print error! " + err.user_message)
    print(err.encoded_message)
    ...
```

### Further information
For further information, such as where to find our examples, we refer to our README.md file on our [Github page](https://github.com/United-Codes/cloudofficeprint-python/).
"""

from . import exceptions, config, elements, own_utils

from .printjob import PrintJob
from .resource import Resource
from .template import Template
from .response import Response

# specify what is imported on "from cloudofficeprint import *"
# but that shouldn't really be used anyway
__all__ = [
    "exceptions",
    "config",
    "elements",
    "own_utils",
    "PrintJob",
    "Resource",
    "Template",
    "Response",
]

Sub-modules

cloudofficeprint.config

Module for output configurations …

cloudofficeprint.elements

Elements are used to replace the various tags in a template with actual data.

cloudofficeprint.exceptions

Custom exceptions for cloudofficeprint.

cloudofficeprint.own_utils

Helper functions.

cloudofficeprint.printjob

Module containing the PrintJob class, which is also exposed at package level.

cloudofficeprint.resource

Module containing the Resource class and its subclasses, which is also exposed at package level …

cloudofficeprint.response

Module containing the Response class, which is also exposed at package level.

cloudofficeprint.template

Classes

class PrintJob (data: Union[Element, Mapping[str, Element], RESTSource], server: Server, template: Union[TemplateResource] = None, output_config: OutputConfig = <cloudofficeprint.config.output.OutputConfig object>, subtemplates: Dict[str, Resource] = {}, prepend_files: List[Resource] = [], append_files: List[Resource] = [], cop_verbose: bool = False)

A print job for a Cloud Office Print server.

This class contains all configuration options, resources, render elements … and the PrintJob.execute() method to combine all these and send a request to the Cloud Office Print server.

Args

data : Union[Element, Mapping[str, Element], RESTSource]
This is either: An Element (e.g. an ElementCollection); A mapping, containing file names as keys and an Element as data. Multiple files will be produced from the different datas, the result is a zip file containing them. In the first case, no output file name is specified and the server will name it "file0".
server : Server
Server to be used for this print job.
template : Union[Template, Resource]
Template to use for this print job.
output_config : OutputConfig, optional
Output configuration to be used for this print job. Defaults to OutputConfig().
subtemplates : Dict[str, Resource], optional
Subtemplates for this print job, accessible (in docx) through {?include subtemplate_dict_key}. Defaults to {}.
prepend_files : List[Resource], optional
Files to prepend to the output file. Defaults to [].
append_files : List[Resource], optional
Files to append to the output file. Defaults to [].
cop_verbose : bool, optional
Whether or not verbose mode should be activated. Defaults to False.
Expand source code
class PrintJob:
    """A print job for a Cloud Office Print server.

    This class contains all configuration options, resources, render elements ...
    and the `PrintJob.execute` method to combine all these and send a request to the Cloud Office Print server.
    """

    def __init__(
        self,
        data: Union[Element, Mapping[str, Element], RESTSource],
        server: Server,
        template: Union[Template, Resource] = None,
        output_config: OutputConfig = OutputConfig(),
        subtemplates: Dict[str, Resource] = {},
        prepend_files: List[Resource] = [],
        append_files: List[Resource] = [],
        cop_verbose: bool = False,
    ):
        """
        Args:
            data (Union[Element, Mapping[str, Element], RESTSource]): This is either: An `Element` (e.g. an `ElementCollection`); A mapping, containing file names as keys and an `Element` as data. Multiple files will be produced from the different datas, the result is a zip file containing them. In the first case, no output file name is specified and the server will name it "file0".
            server (Server): Server to be used for this print job.
            template (Union[Template, Resource]): Template to use for this print job.
            output_config (OutputConfig, optional): Output configuration to be used for this print job. Defaults to `OutputConfig`().
            subtemplates (Dict[str, Resource], optional): Subtemplates for this print job, accessible (in docx) through `{?include subtemplate_dict_key}`. Defaults to {}.
            prepend_files (List[Resource], optional): Files to prepend to the output file. Defaults to [].
            append_files (List[Resource], optional): Files to append to the output file. Defaults to [].
            cop_verbose (bool, optional): Whether or not verbose mode should be activated. Defaults to False.
        """
        self.data: Union[Element, Mapping[str, Element], RESTSource] = data
        self.server: Server = server
        self.output_config: OutputConfig = output_config
        self.template: Union[Template, Resource] = template
        self.subtemplates: Dict[str, Resource] = subtemplates
        self.prepend_files: List[Resource] = prepend_files
        self.append_files: List[Resource] = append_files
        self.cop_verbose: bool = cop_verbose

    def execute(self) -> Response:
        """Execute this print job.

        Returns:
            Response: `Response`-object
        """
        self.server._raise_if_unreachable()
        proxy = self.server.config.proxies if self.server.config else None
        response = requests.post(
            self.server.url,
            json=self.as_dict,
            proxies=proxy,
            headers={"Content-type": "application/json"},
        )
        if type(self.template) is Template and self.template.should_hash:
            template_hash = response.headers["Template-Hash"]
            if template_hash:
                self.template.update_hash(template_hash)
        return self._handle_response(response)

    async def execute_async(self) -> Response:
        """Async version of `PrintJob.execute`

        Returns:
            Response: `Response`-object
        """
        self.server._raise_if_unreachable()
        proxy = self.server.config.proxies if self.server.config else None
        response = await asyncio.get_event_loop().run_in_executor(
            None,
            partial(
                requests.post,
                self.server.url,
                json=self.as_dict,
                proxies=proxy,
                headers={"Content-type": "application/json"},
            ),
        )
        if type(self.template) is Template and self.template.should_hash:
            template_hash = response.headers["Template-Hash"]
            if template_hash:
                self.template.update_hash(template_hash)
        return PrintJob._handle_response(response)

    @staticmethod
    def execute_full_json(json_data: str, server: Server) -> Response:
        """If you already have the JSON to be sent to the server (not just the data, but the entire JSON body including your API key and template), this package will wrap the request to the server.

        Args:
            json_data (str): full JSON data that needs to be sent to a Cloud Office Print server
            server (Server): `Server`-object

        Returns:
            Response: `Response`-object
        """
        server._raise_if_unreachable()
        proxy = server.config.proxies if server.config else None
        response = requests.post(
            server.url,
            data=json_data,
            proxies=proxy,
            headers={"Content-type": "application/json"},
        )
        return PrintJob._handle_response(response)

    @staticmethod
    async def execute_full_json_async(json_data: str, server: Server) -> Response:
        """Async version of `Printjob.execute_full_json`

        Args:
            json_data (str): full JSON data that needs to be sent to a Cloud Office Print server
            server (Server): `Server`-object

        Returns:
            Response: `Response`-object
        """
        server._raise_if_unreachable()
        proxy = server.config.proxies if server.config else None
        response = await asyncio.get_event_loop().run_in_executor(
            None,
            partial(
                requests.post,
                server.url,
                data=json_data,
                proxies=proxy,
                headers={"Content-type": "application/json"},
            ),
        )
        return PrintJob._handle_response(response)

    @staticmethod
    def _handle_response(res: requests.Response) -> Response:
        """Converts the HTML response to a `Response`-object

        Args:
            res (requests.Response): HTML response from the Cloud Office Print server

        Raises:
            COPError: Error when the HTML status code is not 200

        Returns:
            Response: `Response`-object of HTML response
        """
        if res.status_code != 200:
            raise COPError(res.text)
        else:
            return Response(res)

    @property
    def json(self) -> str:
        """JSON equivalent of the dict representation of this print job.
        This representation is isomorphic to the dict representation `Printjob.as_dict`.

        Returns:
            str: JSON equivalent of the dict representation of this print job
        """
        return json.dumps(self.as_dict)

    @property
    def as_dict(self) -> Dict:
        """Return the dict representation of this print job.

        Returns:
            Dict: dict representation of this print job
        """
        # Copy of STATIC_OPTS! Otherwise everything we add to 'result' will also be added to 'STATIC_OPTS'
        result = dict(STATIC_OPTS)
        # server config goes in the upper level
        if self.server.config:
            result.update(self.server.config.as_dict)

        # output config goes in "output"
        # and decides where its sub-configs go through its as_dict property
        # (e.g. PDFConfigs are just appended at this "output" level)
        result["output"] = self.output_config.as_dict

        if self.template:
            result["template"] = self.template.template_dict

        # If output_type is not specified, set this to the template filetype
        # If no template found: default docx
        if "output_type" not in self.output_config.as_dict.keys():
            if self.template:
                result["output"]["output_type"] = result["template"]["template_type"]
            else:
                result["output"]["output_type"] = "docx"

        if isinstance(self.data, Mapping):
            result["files"] = [
                {"filename": name, "data": data.as_dict}
                for name, data in self.data.items()
            ]
        elif isinstance(self.data, RESTSource):
            result["files"] = [self.data.as_dict]
        else:
            result["files"] = [{"data": self.data.as_dict}]

        if len(self.prepend_files) > 0:
            result["prepend_files"] = [
                file.secondary_file_dict for file in self.prepend_files
            ]

        if len(self.append_files) > 0:
            result["append_files"] = [
                file.secondary_file_dict for file in self.append_files
            ]

        if len(self.subtemplates) > 0:
            result["templates"] = [
                {**file.secondary_file_dict, "name": name}
                for name, file in self.subtemplates.items()
            ]

        # If verbose mode is activated, print the result to the terminal
        if self.cop_verbose:
            print("The JSON data that is sent to the Cloud Office Print server:\n")
            pprint(result)

        return result

Static methods

def execute_full_json(json_data: str, server: Server) ‑> Response

If you already have the JSON to be sent to the server (not just the data, but the entire JSON body including your API key and template), this package will wrap the request to the server.

Args

json_data : str
full JSON data that needs to be sent to a Cloud Office Print server
server : Server
Server-object

Returns

Response
Response-object
Expand source code
@staticmethod
def execute_full_json(json_data: str, server: Server) -> Response:
    """If you already have the JSON to be sent to the server (not just the data, but the entire JSON body including your API key and template), this package will wrap the request to the server.

    Args:
        json_data (str): full JSON data that needs to be sent to a Cloud Office Print server
        server (Server): `Server`-object

    Returns:
        Response: `Response`-object
    """
    server._raise_if_unreachable()
    proxy = server.config.proxies if server.config else None
    response = requests.post(
        server.url,
        data=json_data,
        proxies=proxy,
        headers={"Content-type": "application/json"},
    )
    return PrintJob._handle_response(response)
async def execute_full_json_async(json_data: str, server: Server) ‑> Response

Async version of Printjob.execute_full_json

Args

json_data : str
full JSON data that needs to be sent to a Cloud Office Print server
server : Server
Server-object

Returns

Response
Response-object
Expand source code
@staticmethod
async def execute_full_json_async(json_data: str, server: Server) -> Response:
    """Async version of `Printjob.execute_full_json`

    Args:
        json_data (str): full JSON data that needs to be sent to a Cloud Office Print server
        server (Server): `Server`-object

    Returns:
        Response: `Response`-object
    """
    server._raise_if_unreachable()
    proxy = server.config.proxies if server.config else None
    response = await asyncio.get_event_loop().run_in_executor(
        None,
        partial(
            requests.post,
            server.url,
            data=json_data,
            proxies=proxy,
            headers={"Content-type": "application/json"},
        ),
    )
    return PrintJob._handle_response(response)

Instance variables

var as_dict : Dict

Return the dict representation of this print job.

Returns

Dict
dict representation of this print job
Expand source code
@property
def as_dict(self) -> Dict:
    """Return the dict representation of this print job.

    Returns:
        Dict: dict representation of this print job
    """
    # Copy of STATIC_OPTS! Otherwise everything we add to 'result' will also be added to 'STATIC_OPTS'
    result = dict(STATIC_OPTS)
    # server config goes in the upper level
    if self.server.config:
        result.update(self.server.config.as_dict)

    # output config goes in "output"
    # and decides where its sub-configs go through its as_dict property
    # (e.g. PDFConfigs are just appended at this "output" level)
    result["output"] = self.output_config.as_dict

    if self.template:
        result["template"] = self.template.template_dict

    # If output_type is not specified, set this to the template filetype
    # If no template found: default docx
    if "output_type" not in self.output_config.as_dict.keys():
        if self.template:
            result["output"]["output_type"] = result["template"]["template_type"]
        else:
            result["output"]["output_type"] = "docx"

    if isinstance(self.data, Mapping):
        result["files"] = [
            {"filename": name, "data": data.as_dict}
            for name, data in self.data.items()
        ]
    elif isinstance(self.data, RESTSource):
        result["files"] = [self.data.as_dict]
    else:
        result["files"] = [{"data": self.data.as_dict}]

    if len(self.prepend_files) > 0:
        result["prepend_files"] = [
            file.secondary_file_dict for file in self.prepend_files
        ]

    if len(self.append_files) > 0:
        result["append_files"] = [
            file.secondary_file_dict for file in self.append_files
        ]

    if len(self.subtemplates) > 0:
        result["templates"] = [
            {**file.secondary_file_dict, "name": name}
            for name, file in self.subtemplates.items()
        ]

    # If verbose mode is activated, print the result to the terminal
    if self.cop_verbose:
        print("The JSON data that is sent to the Cloud Office Print server:\n")
        pprint(result)

    return result
var json : str

JSON equivalent of the dict representation of this print job. This representation is isomorphic to the dict representation Printjob.as_dict.

Returns

str
JSON equivalent of the dict representation of this print job
Expand source code
@property
def json(self) -> str:
    """JSON equivalent of the dict representation of this print job.
    This representation is isomorphic to the dict representation `Printjob.as_dict`.

    Returns:
        str: JSON equivalent of the dict representation of this print job
    """
    return json.dumps(self.as_dict)

Methods

def execute(self) ‑> Response

Execute this print job.

Returns

Response
Response-object
Expand source code
def execute(self) -> Response:
    """Execute this print job.

    Returns:
        Response: `Response`-object
    """
    self.server._raise_if_unreachable()
    proxy = self.server.config.proxies if self.server.config else None
    response = requests.post(
        self.server.url,
        json=self.as_dict,
        proxies=proxy,
        headers={"Content-type": "application/json"},
    )
    if type(self.template) is Template and self.template.should_hash:
        template_hash = response.headers["Template-Hash"]
        if template_hash:
            self.template.update_hash(template_hash)
    return self._handle_response(response)
async def execute_async(self) ‑> Response

Async version of PrintJob.execute()

Returns

Response
Response-object
Expand source code
async def execute_async(self) -> Response:
    """Async version of `PrintJob.execute`

    Returns:
        Response: `Response`-object
    """
    self.server._raise_if_unreachable()
    proxy = self.server.config.proxies if self.server.config else None
    response = await asyncio.get_event_loop().run_in_executor(
        None,
        partial(
            requests.post,
            self.server.url,
            json=self.as_dict,
            proxies=proxy,
            headers={"Content-type": "application/json"},
        ),
    )
    if type(self.template) is Template and self.template.should_hash:
        template_hash = response.headers["Template-Hash"]
        if template_hash:
            self.template.update_hash(template_hash)
    return PrintJob._handle_response(response)
class Resource (data: Union[str, bytes] = None, filetype: str = None)

The abstract base class for the resources.

Create a new Resource.

Args

data : Union[str, bytes], optional
the data for this Resource. Defaults to None.
filetype : str, optional
the file type of this Resource. Defaults to None.
Expand source code
class Resource(ABC):
    """The abstract base class for the resources."""

    def __init__(
        self,
        data: Union[str, bytes] = None,
        filetype: str = None,
    ):
        """Create a new Resource.

        Args:
            data (Union[str, bytes], optional): the data for this Resource. Defaults to None.
            filetype (str, optional): the file type of this Resource. Defaults to None.
        """
        self.data: Union[str, bytes] = data
        self.filetype: str = filetype

    @property
    def mimetype(self) -> str:
        """
        Returns:
            str: the mime type of the Resource
        """
        return type_utils.extension_to_mimetype(self.filetype)

    @property
    def template_json(self) -> str:
        """
        Returns:
            str: the JSON representation of this Resource.
        """
        return json.dumps(self.template_dict)

    @property
    @abstractmethod
    def template_dict(self) -> Dict:
        """
        Returns:
            Dict: the dictionary representation of this Resource.
        """
        pass

    @property
    def secondary_file_json(self) -> str:
        """
        Returns:
            str: the JSON representation of this Resource.
        """
        return json.dumps(self.secondary_file_dict)

    @property
    @abstractmethod
    def secondary_file_dict(self) -> Dict:
        """
        Returns:
            Dict: the dictionarty representation of this resource as a secondary file (prepend, append, insert, as subtemplate).
        """
        pass

    def __str__(self) -> str:
        """Override the string representation of this class to return the template-style json.

        Returns:
            str: the JSON representation of this resource as a template.
        """
        return self.template_json

    @staticmethod
    def from_raw(raw_data: bytes, filetype: str) -> "RawResource":
        """Create a RawResource from raw file data.

        Args:
            raw_data (bytes): the raw data as a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object).
            filetype (str): the file type (extension).

        Returns:
            RawResource: the created RawResource.
        """
        return RawResource(raw_data, filetype)

    @staticmethod
    def from_base64(base64string: str, filetype: str) -> "Base64Resource":
        """Create a Base64Resource from a base64 string.

        Args:
            base64string (str): the base64 encoded representation of a file.
            filetype (str): the file type (extension).

        Returns:
            Base64Resource: the created Base64Resource.
        """
        return Base64Resource(base64string, filetype)

    @staticmethod
    def from_local_file(local_path: str) -> "Base64Resource":
        """Create a Base64Resource with the contents of a local file.
        The filetype is determined by the extension of the file.

        Throws IOError if it can't read the file.

        Args:
            local_path (str): the path to local file.

        Returns:
            Base64Resource: the created Base64Resource.
        """
        return Base64Resource(
            file_utils.read_file_as_base64(local_path),
            type_utils.path_to_extension(local_path),
        )

    @staticmethod
    def from_server_path(path: str) -> "ServerPathResource":
        """Create a ServerPathResource targeting a file on the server.
        The filetype is determined by the extension of the file.

        Args:
            path (str): the location of target file on the server.

        Returns:
            ServerPathResource: the created ServerPathResource.
        """
        return ServerPathResource(path)

    @staticmethod
    def from_url(url: str, filetype: str) -> "URLResource":
        """Create an URLResource targeting the file at a given URL.

        Args:
            url (str): the file URL.
            filetype (str): the file type (extension).

        Returns:
            URLResource: the created URLResource.
        """
        return URLResource(url, filetype)

    @staticmethod
    def from_html(htmlstring: str, landscape: bool = False) -> "HTMLResource":
        """Create an HTMLResource with html data in plain text.
        Landscape is not supported for prepend/append sources, only for template resources.

        Args:
            htmlstring (str): the html content.
            landscape (bool, optional): whether or not to use the landscape option. Defaults to False.

        Returns:
            HTMLResource: the created HTMLResource.
        """
        return HTMLResource(htmlstring, landscape)

Ancestors

  • abc.ABC

Subclasses

Static methods

def from_base64(base64string: str, filetype: str) ‑> Base64Resource

Create a Base64Resource from a base64 string.

Args

base64string : str
the base64 encoded representation of a file.
filetype : str
the file type (extension).

Returns

Base64Resource
the created Base64Resource.
Expand source code
@staticmethod
def from_base64(base64string: str, filetype: str) -> "Base64Resource":
    """Create a Base64Resource from a base64 string.

    Args:
        base64string (str): the base64 encoded representation of a file.
        filetype (str): the file type (extension).

    Returns:
        Base64Resource: the created Base64Resource.
    """
    return Base64Resource(base64string, filetype)
def from_html(htmlstring: str, landscape: bool = False) ‑> HTMLResource

Create an HTMLResource with html data in plain text. Landscape is not supported for prepend/append sources, only for template resources.

Args

htmlstring : str
the html content.
landscape : bool, optional
whether or not to use the landscape option. Defaults to False.

Returns

HTMLResource
the created HTMLResource.
Expand source code
@staticmethod
def from_html(htmlstring: str, landscape: bool = False) -> "HTMLResource":
    """Create an HTMLResource with html data in plain text.
    Landscape is not supported for prepend/append sources, only for template resources.

    Args:
        htmlstring (str): the html content.
        landscape (bool, optional): whether or not to use the landscape option. Defaults to False.

    Returns:
        HTMLResource: the created HTMLResource.
    """
    return HTMLResource(htmlstring, landscape)
def from_local_file(local_path: str) ‑> Base64Resource

Create a Base64Resource with the contents of a local file. The filetype is determined by the extension of the file.

Throws IOError if it can't read the file.

Args

local_path : str
the path to local file.

Returns

Base64Resource
the created Base64Resource.
Expand source code
@staticmethod
def from_local_file(local_path: str) -> "Base64Resource":
    """Create a Base64Resource with the contents of a local file.
    The filetype is determined by the extension of the file.

    Throws IOError if it can't read the file.

    Args:
        local_path (str): the path to local file.

    Returns:
        Base64Resource: the created Base64Resource.
    """
    return Base64Resource(
        file_utils.read_file_as_base64(local_path),
        type_utils.path_to_extension(local_path),
    )
def from_raw(raw_data: bytes, filetype: str) ‑> RawResource

Create a RawResource from raw file data.

Args

raw_data : bytes
the raw data as a bytes-like object.
filetype : str
the file type (extension).

Returns

RawResource
the created RawResource.
Expand source code
@staticmethod
def from_raw(raw_data: bytes, filetype: str) -> "RawResource":
    """Create a RawResource from raw file data.

    Args:
        raw_data (bytes): the raw data as a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object).
        filetype (str): the file type (extension).

    Returns:
        RawResource: the created RawResource.
    """
    return RawResource(raw_data, filetype)
def from_server_path(path: str) ‑> ServerPathResource

Create a ServerPathResource targeting a file on the server. The filetype is determined by the extension of the file.

Args

path : str
the location of target file on the server.

Returns

ServerPathResource
the created ServerPathResource.
Expand source code
@staticmethod
def from_server_path(path: str) -> "ServerPathResource":
    """Create a ServerPathResource targeting a file on the server.
    The filetype is determined by the extension of the file.

    Args:
        path (str): the location of target file on the server.

    Returns:
        ServerPathResource: the created ServerPathResource.
    """
    return ServerPathResource(path)
def from_url(url: str, filetype: str) ‑> URLResource

Create an URLResource targeting the file at a given URL.

Args

url : str
the file URL.
filetype : str
the file type (extension).

Returns

URLResource
the created URLResource.
Expand source code
@staticmethod
def from_url(url: str, filetype: str) -> "URLResource":
    """Create an URLResource targeting the file at a given URL.

    Args:
        url (str): the file URL.
        filetype (str): the file type (extension).

    Returns:
        URLResource: the created URLResource.
    """
    return URLResource(url, filetype)

Instance variables

var mimetype : str

Returns

str
the mime type of the Resource
Expand source code
@property
def mimetype(self) -> str:
    """
    Returns:
        str: the mime type of the Resource
    """
    return type_utils.extension_to_mimetype(self.filetype)
var secondary_file_dict : Dict

Returns

Dict
the dictionarty representation of this resource as a secondary file (prepend, append, insert, as subtemplate).
Expand source code
@property
@abstractmethod
def secondary_file_dict(self) -> Dict:
    """
    Returns:
        Dict: the dictionarty representation of this resource as a secondary file (prepend, append, insert, as subtemplate).
    """
    pass
var secondary_file_json : str

Returns

str
the JSON representation of this Resource.
Expand source code
@property
def secondary_file_json(self) -> str:
    """
    Returns:
        str: the JSON representation of this Resource.
    """
    return json.dumps(self.secondary_file_dict)
var template_dict : Dict

Returns

Dict
the dictionary representation of this Resource.
Expand source code
@property
@abstractmethod
def template_dict(self) -> Dict:
    """
    Returns:
        Dict: the dictionary representation of this Resource.
    """
    pass
var template_json : str

Returns

str
the JSON representation of this Resource.
Expand source code
@property
def template_json(self) -> str:
    """
    Returns:
        str: the JSON representation of this Resource.
    """
    return json.dumps(self.template_dict)
class Response (response: requests.models.Response)

The Response class serves as a container for and interface with the Cloud Office Print server's response to a printjob request.

The Cloud Office Print server can also throw an error, in which case you will be dealing with a cloudofficeprint.exceptions.COPError instead of this class.

You should never need to construct a Response manually.

Args

response : requests.Response
Response object from the requests package
Expand source code
class Response():
    """The Response class serves as a container for and interface with the Cloud Office Print server's response to a printjob request.

    The Cloud Office Print server can also throw an error, in which case you will be dealing with a cloudofficeprint.exceptions.COPError instead of this class.
    """

    def __init__(self, response: requests.Response):
        """You should never need to construct a Response manually.

        Args:
            response (requests.Response): Response object from the requests package
        """
        self._mimetype = response.headers["Content-Type"]
        self._bytes = response.content

    @property
    def mimetype(self) -> str:
        """Mime type of this response.

        Returns:
            str: mime type of this response
        """
        return self._mimetype

    @property
    def filetype(self) -> str:
        """File type (extension) of this response. E.g. "docx".

        Returns:
            str: file type of this response
        """
        return type_utils.mimetype_to_extension(self.mimetype)

    @property
    def binary(self) -> bytes:
        """Binary representation of the output file.

        Response.to_file can be used to output to a file,
        alternatively, use this property to do something else with the binary data.

        Returns:
            bytes: response file as binary
        """
        return self._bytes

    def to_string(self) -> str:
        """Return the string representation of this buffer.
        Useful if the server returns a JSON (e.g. for output_type 'count_tags').

        Raises:
            err: raise error is bytes cannot be decoded in utf-8

        Returns:
            str: string representation of this buffer
        """
        try:
            return self._bytes.decode('utf-8')
        except UnicodeDecodeError as err:
            print("""The method 'to_string()' cannot be called on this object.
            The server response is probably not a string (e.g. JSON).
            To get the bytes of the response, use the property 'binary' instead.""")
            raise err

    def to_file(self, path: str):
        """Write the response to a file at the given path without extension.

        If the given file path does not contain an extension,
        the correct path is automatically added from the response data.
        That is how this method is intended to be used.
        You should only specify the extension in the path if you have some reason to specify the extension manually.

        Args:
            path (str): path without extension
        """

        if not splitext(path)[1]:
            path += "." + self.filetype

        # open the file in binary ("b") and write ("w") mode
        outfile = open(path, "wb")
        outfile.write(self.binary)
        outfile.close()

Instance variables

var binary : bytes

Binary representation of the output file.

Response.to_file can be used to output to a file, alternatively, use this property to do something else with the binary data.

Returns

bytes
response file as binary
Expand source code
@property
def binary(self) -> bytes:
    """Binary representation of the output file.

    Response.to_file can be used to output to a file,
    alternatively, use this property to do something else with the binary data.

    Returns:
        bytes: response file as binary
    """
    return self._bytes
var filetype : str

File type (extension) of this response. E.g. "docx".

Returns

str
file type of this response
Expand source code
@property
def filetype(self) -> str:
    """File type (extension) of this response. E.g. "docx".

    Returns:
        str: file type of this response
    """
    return type_utils.mimetype_to_extension(self.mimetype)
var mimetype : str

Mime type of this response.

Returns

str
mime type of this response
Expand source code
@property
def mimetype(self) -> str:
    """Mime type of this response.

    Returns:
        str: mime type of this response
    """
    return self._mimetype

Methods

def to_file(self, path: str)

Write the response to a file at the given path without extension.

If the given file path does not contain an extension, the correct path is automatically added from the response data. That is how this method is intended to be used. You should only specify the extension in the path if you have some reason to specify the extension manually.

Args

path : str
path without extension
Expand source code
def to_file(self, path: str):
    """Write the response to a file at the given path without extension.

    If the given file path does not contain an extension,
    the correct path is automatically added from the response data.
    That is how this method is intended to be used.
    You should only specify the extension in the path if you have some reason to specify the extension manually.

    Args:
        path (str): path without extension
    """

    if not splitext(path)[1]:
        path += "." + self.filetype

    # open the file in binary ("b") and write ("w") mode
    outfile = open(path, "wb")
    outfile.write(self.binary)
    outfile.close()
def to_string(self) ‑> str

Return the string representation of this buffer. Useful if the server returns a JSON (e.g. for output_type 'count_tags').

Raises

err
raise error is bytes cannot be decoded in utf-8

Returns

str
string representation of this buffer
Expand source code
def to_string(self) -> str:
    """Return the string representation of this buffer.
    Useful if the server returns a JSON (e.g. for output_type 'count_tags').

    Raises:
        err: raise error is bytes cannot be decoded in utf-8

    Returns:
        str: string representation of this buffer
    """
    try:
        return self._bytes.decode('utf-8')
    except UnicodeDecodeError as err:
        print("""The method 'to_string()' cannot be called on this object.
        The server response is probably not a string (e.g. JSON).
        To get the bytes of the response, use the property 'binary' instead.""")
        raise err
class Template (resource: Resource, start_delimiter: str = None, end_delimiter: str = None, should_hash: bool = None, template_hash: str = None)

The Template class

Create a new Template.

Args

resource : Resource
the resource of this template.
start_delimiter : str, optional
the starting delimiter used in the template.
end_delimiter : str, optional
the starting delimiter used in the template.
should_hash : bool, optional
whether the template should be hashed on the server.
template_hash : str, optional
the hash of the template.
Expand source code
class Template:
    """The Template class"""

    def __init__(
        self,
        resource: Resource,
        start_delimiter: str = None,
        end_delimiter: str = None,
        should_hash: bool = None,
        template_hash: str = None,
    ):
        """Create a new Template.

        Args:
            resource (Resource): the resource of this template.
            start_delimiter (str, optional): the starting delimiter used in the template.
            end_delimiter (str, optional): the starting delimiter used in the template.
            should_hash (bool, optional): whether the template should be hashed on the server.
            template_hash (str, optional): the hash of the template.
        """
        self.resource = resource
        self.start_delimiter = start_delimiter
        self.end_delimiter = end_delimiter
        self.should_hash = should_hash
        self.template_hash = template_hash

    def update_hash(self, template_hash: str):
        """Update the Template to store a hash.
        On the next request to the server, the file data will not be sent, only the hash of the template.

        Args:
            template_hash (str): the hash of the template.
        """
        self.template_hash = template_hash
        self.should_hash = False

    def reset_hash(self, should_hash: bool = True):
        """Reset the stored hash of the template.

        Args:
            should_hash (bool, optional): whether the template should be hashed on the server. Defaults to True.
        """
        self.template_hash = None
        self.should_hash = should_hash

    @property
    def mimetype(self) -> str:
        """
        Returns:
            str: the mime type of the Resource
        """
        return self.resource.mimetype

    @property
    def template_json(self) -> str:
        """
        Returns:
            str: the JSON representation of this Resource.
        """
        return json.dumps(self.template_dict)

    @property
    def template_dict(self) -> Dict:
        """
        Returns:
            Dict: the dictionary representation of this Resource.
        """
        if self.template_hash and not self.should_hash:
            dict = {
                "template_type": self.resource.filetype,
                "template_hash": self.template_hash,
            }
            if self.start_delimiter:
                dict["start_delimiter"] = self.start_delimiter
            if self.end_delimiter:
                dict["end_delimiter"] = self.end_delimiter
            return dict
        dict = self.resource.template_dict
        if self.start_delimiter:
            dict["start_delimiter"] = self.start_delimiter
        if self.end_delimiter:
            dict["end_delimiter"] = self.end_delimiter
        if self.should_hash:
            dict["should_hash"] = self.should_hash
        if self.template_hash:
            dict["template_hash"] = self.template_hash
        return dict

    def __str__(self) -> str:
        """Override the string representation of this class to return the template-style json.

        Returns:
            str: the JSON representation of this resource as a template.
        """
        return self.template_json

    @staticmethod
    def from_raw(
        raw_data: bytes,
        filetype: str,
        start_delimiter: str = None,
        end_delimiter: str = None,
        should_hash: bool = None,
        template_hash: str = None,
    ) -> "Template":
        """Create a Template with a RawResource from raw file data.

        Args:
            raw_data (bytes): the raw data as a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object).
            filetype (str): the file type (extension).
            start_delimiter (str, optional): the starting delimiter used in the template.
            end_delimiter (str, optional): the starting delimiter used in the template.
            should_hash (bool, optional): whether the template should be hashed on the server.
            template_hash (str, optional): the hash of the template.

        Returns:
            Template: the created Template.
        """
        return Template(
            Resource.from_raw(raw_data, filetype),
            start_delimiter,
            end_delimiter,
            should_hash,
            template_hash,
        )

    @staticmethod
    def from_base64(
        base64string: str,
        filetype: str,
        start_delimiter: str = None,
        end_delimiter: str = None,
        should_hash: bool = None,
        template_hash: str = None,
    ) -> "Template":
        """Create a Template with a Base64Resource from a base64 string.

        Args:
            base64string (str): the base64 encoded representation of a file.
            filetype (str): the file type (extension).
            start_delimiter (str, optional): the starting delimiter used in the template.
            end_delimiter (str, optional): the starting delimiter used in the template.
            should_hash (bool, optional): whether the template should be hashed on the server.
            template_hash (str, optional): the hash of the template.

        Returns:
            Template: the created Template.
        """
        return Template(
            Resource.from_base64(base64string, filetype),
            start_delimiter,
            end_delimiter,
            should_hash,
            template_hash,
        )

    @staticmethod
    def from_local_file(
        local_path: str,
        start_delimiter: str = None,
        end_delimiter: str = None,
        should_hash: bool = None,
        template_hash: str = None,
    ) -> "Template":
        """Create a Template with a Base64Resource with the contents of a local file.
        The filetype is determined by the extension of the file.

        Throws IOError if it can't read the file.

        Args:
            local_path (str): the path to local file.
            start_delimiter (str, optional): the starting delimiter used in the template.
            end_delimiter (str, optional): the starting delimiter used in the template.
            should_hash (bool, optional): whether the template should be hashed on the server.
            template_hash (str, optional): the hash of the template.

        Returns:
            Template: the created Template.
        """
        return Template(
            Resource.from_local_file(local_path),
            start_delimiter,
            end_delimiter,
            should_hash,
            template_hash,
        )

    @staticmethod
    def from_server_path(
        path: str,
        start_delimiter: str = None,
        end_delimiter: str = None,
        should_hash: bool = None,
        template_hash: str = None,
    ) -> "Template":
        """Create a Template with a ServerPathResource targeting a file on the server.
        The filetype is determined by the extension of the file.

        Args:
            path (str): the location of target file on the server.
            start_delimiter (str, optional): the starting delimiter used in the template.
            end_delimiter (str, optional): the starting delimiter used in the template.
            should_hash (bool, optional): whether the template should be hashed on the server.
            template_hash (str, optional): the hash of the template.

        Returns:
            Template: the created Template.
        """
        return Template(
            Resource.from_server_path(path),
            start_delimiter,
            end_delimiter,
            should_hash,
            template_hash,
        )

    @staticmethod
    def from_url(
        url: str,
        filetype: str,
        start_delimiter: str = None,
        end_delimiter: str = None,
        should_hash: bool = None,
        template_hash: str = None,
    ) -> "Template":
        """Create a Template with a URLResource targeting the file at a given url.

        Args:
            url (str): the file URL.
            filetype (str): the file type (extension).
            start_delimiter (str, optional): the starting delimiter used in the template.
            end_delimiter (str, optional): the starting delimiter used in the template.
            should_hash (bool, optional): whether the template should be hashed on the server.
            template_hash (str, optional): the hash of the template.

        Returns:
            Template: the created Template.
        """
        return Template(
            Resource.from_url(url, filetype),
            start_delimiter,
            end_delimiter,
            should_hash,
            template_hash,
        )

    @staticmethod
    def from_html(
        htmlstring: str,
        landscape: bool = False,
        start_delimiter: str = None,
        end_delimiter: str = None,
        should_hash: bool = None,
        template_hash: str = None,
    ) -> "Template":
        """Create a Template with a HTMLResource with html data in plain text.

        Args:
            htmlstring (str): the html content.
            landscape (bool, optional): whether or not to use the landscape option. Defaults to False.
            start_delimiter (str, optional): the starting delimiter used in the template.
            end_delimiter (str, optional): the starting delimiter used in the template.
            should_hash (bool, optional): whether the template should be hashed on the server.
            template_hash (str, optional): the hash of the template.

        Returns:
            Template: the created Template.
        """
        return Template(
            Resource.from_html(htmlstring, landscape),
            start_delimiter,
            end_delimiter,
            should_hash,
            template_hash,
        )

Static methods

def from_base64(base64string: str, filetype: str, start_delimiter: str = None, end_delimiter: str = None, should_hash: bool = None, template_hash: str = None) ‑> Template

Create a Template with a Base64Resource from a base64 string.

Args

base64string : str
the base64 encoded representation of a file.
filetype : str
the file type (extension).
start_delimiter : str, optional
the starting delimiter used in the template.
end_delimiter : str, optional
the starting delimiter used in the template.
should_hash : bool, optional
whether the template should be hashed on the server.
template_hash : str, optional
the hash of the template.

Returns

Template
the created Template.
Expand source code
@staticmethod
def from_base64(
    base64string: str,
    filetype: str,
    start_delimiter: str = None,
    end_delimiter: str = None,
    should_hash: bool = None,
    template_hash: str = None,
) -> "Template":
    """Create a Template with a Base64Resource from a base64 string.

    Args:
        base64string (str): the base64 encoded representation of a file.
        filetype (str): the file type (extension).
        start_delimiter (str, optional): the starting delimiter used in the template.
        end_delimiter (str, optional): the starting delimiter used in the template.
        should_hash (bool, optional): whether the template should be hashed on the server.
        template_hash (str, optional): the hash of the template.

    Returns:
        Template: the created Template.
    """
    return Template(
        Resource.from_base64(base64string, filetype),
        start_delimiter,
        end_delimiter,
        should_hash,
        template_hash,
    )
def from_html(htmlstring: str, landscape: bool = False, start_delimiter: str = None, end_delimiter: str = None, should_hash: bool = None, template_hash: str = None) ‑> Template

Create a Template with a HTMLResource with html data in plain text.

Args

htmlstring : str
the html content.
landscape : bool, optional
whether or not to use the landscape option. Defaults to False.
start_delimiter : str, optional
the starting delimiter used in the template.
end_delimiter : str, optional
the starting delimiter used in the template.
should_hash : bool, optional
whether the template should be hashed on the server.
template_hash : str, optional
the hash of the template.

Returns

Template
the created Template.
Expand source code
@staticmethod
def from_html(
    htmlstring: str,
    landscape: bool = False,
    start_delimiter: str = None,
    end_delimiter: str = None,
    should_hash: bool = None,
    template_hash: str = None,
) -> "Template":
    """Create a Template with a HTMLResource with html data in plain text.

    Args:
        htmlstring (str): the html content.
        landscape (bool, optional): whether or not to use the landscape option. Defaults to False.
        start_delimiter (str, optional): the starting delimiter used in the template.
        end_delimiter (str, optional): the starting delimiter used in the template.
        should_hash (bool, optional): whether the template should be hashed on the server.
        template_hash (str, optional): the hash of the template.

    Returns:
        Template: the created Template.
    """
    return Template(
        Resource.from_html(htmlstring, landscape),
        start_delimiter,
        end_delimiter,
        should_hash,
        template_hash,
    )
def from_local_file(local_path: str, start_delimiter: str = None, end_delimiter: str = None, should_hash: bool = None, template_hash: str = None) ‑> Template

Create a Template with a Base64Resource with the contents of a local file. The filetype is determined by the extension of the file.

Throws IOError if it can't read the file.

Args

local_path : str
the path to local file.
start_delimiter : str, optional
the starting delimiter used in the template.
end_delimiter : str, optional
the starting delimiter used in the template.
should_hash : bool, optional
whether the template should be hashed on the server.
template_hash : str, optional
the hash of the template.

Returns

Template
the created Template.
Expand source code
@staticmethod
def from_local_file(
    local_path: str,
    start_delimiter: str = None,
    end_delimiter: str = None,
    should_hash: bool = None,
    template_hash: str = None,
) -> "Template":
    """Create a Template with a Base64Resource with the contents of a local file.
    The filetype is determined by the extension of the file.

    Throws IOError if it can't read the file.

    Args:
        local_path (str): the path to local file.
        start_delimiter (str, optional): the starting delimiter used in the template.
        end_delimiter (str, optional): the starting delimiter used in the template.
        should_hash (bool, optional): whether the template should be hashed on the server.
        template_hash (str, optional): the hash of the template.

    Returns:
        Template: the created Template.
    """
    return Template(
        Resource.from_local_file(local_path),
        start_delimiter,
        end_delimiter,
        should_hash,
        template_hash,
    )
def from_raw(raw_data: bytes, filetype: str, start_delimiter: str = None, end_delimiter: str = None, should_hash: bool = None, template_hash: str = None) ‑> Template

Create a Template with a RawResource from raw file data.

Args

raw_data : bytes
the raw data as a bytes-like object.
filetype : str
the file type (extension).
start_delimiter : str, optional
the starting delimiter used in the template.
end_delimiter : str, optional
the starting delimiter used in the template.
should_hash : bool, optional
whether the template should be hashed on the server.
template_hash : str, optional
the hash of the template.

Returns

Template
the created Template.
Expand source code
@staticmethod
def from_raw(
    raw_data: bytes,
    filetype: str,
    start_delimiter: str = None,
    end_delimiter: str = None,
    should_hash: bool = None,
    template_hash: str = None,
) -> "Template":
    """Create a Template with a RawResource from raw file data.

    Args:
        raw_data (bytes): the raw data as a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object).
        filetype (str): the file type (extension).
        start_delimiter (str, optional): the starting delimiter used in the template.
        end_delimiter (str, optional): the starting delimiter used in the template.
        should_hash (bool, optional): whether the template should be hashed on the server.
        template_hash (str, optional): the hash of the template.

    Returns:
        Template: the created Template.
    """
    return Template(
        Resource.from_raw(raw_data, filetype),
        start_delimiter,
        end_delimiter,
        should_hash,
        template_hash,
    )
def from_server_path(path: str, start_delimiter: str = None, end_delimiter: str = None, should_hash: bool = None, template_hash: str = None) ‑> Template

Create a Template with a ServerPathResource targeting a file on the server. The filetype is determined by the extension of the file.

Args

path : str
the location of target file on the server.
start_delimiter : str, optional
the starting delimiter used in the template.
end_delimiter : str, optional
the starting delimiter used in the template.
should_hash : bool, optional
whether the template should be hashed on the server.
template_hash : str, optional
the hash of the template.

Returns

Template
the created Template.
Expand source code
@staticmethod
def from_server_path(
    path: str,
    start_delimiter: str = None,
    end_delimiter: str = None,
    should_hash: bool = None,
    template_hash: str = None,
) -> "Template":
    """Create a Template with a ServerPathResource targeting a file on the server.
    The filetype is determined by the extension of the file.

    Args:
        path (str): the location of target file on the server.
        start_delimiter (str, optional): the starting delimiter used in the template.
        end_delimiter (str, optional): the starting delimiter used in the template.
        should_hash (bool, optional): whether the template should be hashed on the server.
        template_hash (str, optional): the hash of the template.

    Returns:
        Template: the created Template.
    """
    return Template(
        Resource.from_server_path(path),
        start_delimiter,
        end_delimiter,
        should_hash,
        template_hash,
    )
def from_url(url: str, filetype: str, start_delimiter: str = None, end_delimiter: str = None, should_hash: bool = None, template_hash: str = None) ‑> Template

Create a Template with a URLResource targeting the file at a given url.

Args

url : str
the file URL.
filetype : str
the file type (extension).
start_delimiter : str, optional
the starting delimiter used in the template.
end_delimiter : str, optional
the starting delimiter used in the template.
should_hash : bool, optional
whether the template should be hashed on the server.
template_hash : str, optional
the hash of the template.

Returns

Template
the created Template.
Expand source code
@staticmethod
def from_url(
    url: str,
    filetype: str,
    start_delimiter: str = None,
    end_delimiter: str = None,
    should_hash: bool = None,
    template_hash: str = None,
) -> "Template":
    """Create a Template with a URLResource targeting the file at a given url.

    Args:
        url (str): the file URL.
        filetype (str): the file type (extension).
        start_delimiter (str, optional): the starting delimiter used in the template.
        end_delimiter (str, optional): the starting delimiter used in the template.
        should_hash (bool, optional): whether the template should be hashed on the server.
        template_hash (str, optional): the hash of the template.

    Returns:
        Template: the created Template.
    """
    return Template(
        Resource.from_url(url, filetype),
        start_delimiter,
        end_delimiter,
        should_hash,
        template_hash,
    )

Instance variables

var mimetype : str

Returns

str
the mime type of the Resource
Expand source code
@property
def mimetype(self) -> str:
    """
    Returns:
        str: the mime type of the Resource
    """
    return self.resource.mimetype
var template_dict : Dict

Returns

Dict
the dictionary representation of this Resource.
Expand source code
@property
def template_dict(self) -> Dict:
    """
    Returns:
        Dict: the dictionary representation of this Resource.
    """
    if self.template_hash and not self.should_hash:
        dict = {
            "template_type": self.resource.filetype,
            "template_hash": self.template_hash,
        }
        if self.start_delimiter:
            dict["start_delimiter"] = self.start_delimiter
        if self.end_delimiter:
            dict["end_delimiter"] = self.end_delimiter
        return dict
    dict = self.resource.template_dict
    if self.start_delimiter:
        dict["start_delimiter"] = self.start_delimiter
    if self.end_delimiter:
        dict["end_delimiter"] = self.end_delimiter
    if self.should_hash:
        dict["should_hash"] = self.should_hash
    if self.template_hash:
        dict["template_hash"] = self.template_hash
    return dict
var template_json : str

Returns

str
the JSON representation of this Resource.
Expand source code
@property
def template_json(self) -> str:
    """
    Returns:
        str: the JSON representation of this Resource.
    """
    return json.dumps(self.template_dict)

Methods

def reset_hash(self, should_hash: bool = True)

Reset the stored hash of the template.

Args

should_hash : bool, optional
whether the template should be hashed on the server. Defaults to True.
Expand source code
def reset_hash(self, should_hash: bool = True):
    """Reset the stored hash of the template.

    Args:
        should_hash (bool, optional): whether the template should be hashed on the server. Defaults to True.
    """
    self.template_hash = None
    self.should_hash = should_hash
def update_hash(self, template_hash: str)

Update the Template to store a hash. On the next request to the server, the file data will not be sent, only the hash of the template.

Args

template_hash : str
the hash of the template.
Expand source code
def update_hash(self, template_hash: str):
    """Update the Template to store a hash.
    On the next request to the server, the file data will not be sent, only the hash of the template.

    Args:
        template_hash (str): the hash of the template.
    """
    self.template_hash = template_hash
    self.should_hash = False