Пример #1
0
    def __init__(self,
                 data: t.Any,
                 caption: t.Optional[str] = None,
                 responsive: bool = True,
                 id: str = None,
                 label: str = None):
        """
        Args:
            data: The `plot` object to attach
            caption: A caption to display below the plot (optional)
            responsive: Whether the plot should automatically be resized to fit, set to False if your plot looks odd (optional, default: True)
            id: A unique id for the block to aid querying (optional)
            label: A label used when displaying the block (optional)
        """
        out_fn = self._save_obj(data, as_json=False)
        if out_fn.mime == PKL_MIMETYPE:
            raise DPError("Can't embed object as a plot")

        super().__init__(file=out_fn.file,
                         caption=caption,
                         width=640,
                         height=480,
                         id=id,
                         label=label,
                         responsive=responsive)
Пример #2
0
 def _wrap_blocks(self) -> None:
     """Wrap the list of blocks in a top-level block element needed"""
     if any(isinstance(b, Page) for b in self.blocks):
         raise DPError("Page objects can only be at the top-level")
     if not all(isinstance(b, (Group, Select)) for b in self.blocks):
         # only wrap if not all blocks are a Group object
         self.blocks = [Group(blocks=self.blocks)]
Пример #3
0
    def __init__(self,
                 url: str,
                 width: int = 640,
                 height: int = 480,
                 id: str = None,
                 label: str = None):
        """
        Args:
            url: The URL of the resource to be embedded
            width: The width of the embedded object (optional)
            height: The height of the embedded object (optional)
            id: A unique id for the block to aid querying (optional)
            label: A label used when displaying the block (optional)
        """

        try:
            result = self.providers.request(url,
                                            maxwidth=width,
                                            maxheight=height)
        except ProviderException:
            raise DPError(f"No embed provider found for URL '{url}'")
        super().__init__(
            id=id,
            label=label,
            url=url,
            title=result.get("title", "Title"),
            provider_name=result.get("provider_name", "Embedding"),
        )

        # if "html" not in result:
        #     raise DPError(f"Can't embed result from provider for URL '{url}'")
        self.content = result["html"]
Пример #4
0
    def __init__(
        self,
        *arg_blocks: BlockOrPrimitive,
        blocks: t.List[BlockOrPrimitive] = None,
        type: t.Optional[SelectType] = None,
        id: str = None,
        label: str = None,
    ):
        """
        Args:
            *arg_blocks: Page to add to report
            blocks: Allows providing the report blocks as a single list
            type: An instance of SelectType that indicates if the select should use tabs or a dropdown
            id: A unique id for the blocks to aid querying (optional)
            label: A label used when displaying the block (optional)

        ..tip:: Select can be passed using either arg parameters or the `blocks` kwarg, e.g.
          `dp.Select(table, plot, type=dp.SelectType.TABS)` or `dp.Group(blocks=[table, plot])`
        """
        _type = glom(type, "value", default=None)
        super().__init__(*arg_blocks,
                         blocks=blocks,
                         id=id,
                         label=label,
                         type=_type)
        if len(self.blocks) < 2:
            raise DPError("Can't create Select with less than 2 objects")
Пример #5
0
    def __init__(
        self,
        *arg_blocks: BlockOrPrimitive,
        blocks: t.List[BlockOrPrimitive] = None,
        title: str = None,
        label: str = None,
    ):
        """
        Args:
            *arg_blocks: Blocks to add to Page
            blocks: Allows providing the report blocks as a single list
            title: The page title (optional)
            label: A label used when displaying the page (optional, deprecated)

        ..tip:: Page can be passed using either arg parameters or the `blocks` kwarg, e.g.
          `dp.Page(group, select)` or `dp.Group(blocks=[group, select])`
        """
        if label:
            warnings.warn(
                "dp.Page label= argument is deprecated, to be removed in next release, use title= instead."
            )
        label = label or title
        super().__init__(*arg_blocks, blocks=blocks, label=label)
        if len(self.blocks) < 1:
            raise DPError("Can't create Page with no objects")
        self._wrap_blocks()
Пример #6
0
def wrap_block(b: BlockOrPrimitive) -> Block:
    if isinstance(b, Page):
        raise DPError("Page objects can only be at the top-level")
    if not isinstance(b, BaseElement):
        # import here as a very slow module due to nested imports
        from ..files import convert

        return convert(b)
    return t.cast(Block, b)
Пример #7
0
    def __init__(self,
                 *arg_blocks: BlockOrPrimitive,
                 blocks: t.List[BlockOrPrimitive] = None,
                 **kwargs):
        self.blocks = blocks or list(arg_blocks)
        if len(self.blocks) == 0:
            raise DPError("Can't create container with 0 objects")
        self.blocks = [wrap_block(b) for b in self.blocks]

        super().__init__(**kwargs)
Пример #8
0
def get_embed_url(url: str, width: int = 960, height: int = 540) -> Embedded:
    """Return html for an embeddable URL"""
    try:
        r = providers.request(url, maxwidth=width, maxheight=height)
        return Embedded(html=r["html"],
                        title=r.get("title", "Title"),
                        provider=r.get("provider_name", "Embedding"))
    except ProviderException:
        raise DPError(
            f"No embed provider found for URL '{url}' - is there an active internet connection?"
        )
Пример #9
0
def save_df(df: pd.DataFrame) -> DPTmpFile:
    """Export a df for uploading"""
    fn = DPTmpFile(ArrowFormat.ext)

    # create a copy of the df to process
    df = to_df(df)
    if df.size == 0:
        raise DPError("Empty DataFrame provided")

    # process_df called in Arrow.save_file
    # process_df(df)
    ArrowFormat.save_file(fn.name, df)
    log.debug(f"Saved df to {fn} ({os.path.getsize(fn.file)} bytes)")
    return fn
Пример #10
0
    def __init__(self, name: str = None, **kwargs):
        """
        Args:
            name: A unique name to reference the block, used when referencing blocks via the report editor and when embedding
        """
        self._block_name = self._tag.lower()
        self._attributes = dict()
        self._add_attributes(**kwargs)
        self._set_name(name)

        if "caption" in kwargs:
            _caption = kwargs["caption"]
            if _caption and len(_caption) > 512:
                raise DPError("Caption must be less than 512 characters")
Пример #11
0
    def url(self, id_or_url: URL):
        # build a url to the resource on the api server
        _id: str
        id_or_url = str(id_or_url)
        if self.endpoint in id_or_url:
            url = id_or_url
            if not url.startswith("http"):
                url = f"https://{url}"
            if not v.url(url):
                raise DPError(f"{url} is not a valid object ref")
            x: up.SplitResult = up.urlsplit(url)
            _id = list(filter(None, x.path.split("/")))[-1]
        else:
            _id = id_or_url

        rel_obj_url = up.urljoin(self.endpoint, f"{_id}/")
        self.res = Resource(endpoint=rel_obj_url)
        self._url = self.res.url
Пример #12
0
    def format(self, *args: BlockOrPrimitive,
               **kwargs: BlockOrPrimitive) -> Group:
        """
        Format the markdown text template, using the supplied context to insert blocks into `{{}}` markers in the template.

        `{}` markers can be empty, hence positional, or have a name, e.g. `{{plot}}`, which is used to lookup the value from the keyword context.

        Args:
            *args: positional template context arguments
            **kwargs: keyword template context arguments

        ..tip:: Either Python objects, e.g. dataframes, and plots, or Datapane blocks as context

        Returns:
            A datapane Group object containing the list of text and embedded objects
        """

        splits = re.split(r"\{\{(\w*)\}\}", self.content)
        args = deque(args)
        blocks = []

        for (i, x) in enumerate(splits):
            is_block = bool(i % 2)

            if is_block:
                try:
                    if x:
                        blocks.append(wrap_block(kwargs[x]))
                    else:
                        blocks.append(wrap_block(args.popleft()))
                except (IndexError, KeyError):
                    raise DPError(
                        f"Unknown/missing object '{x}' referenced in Markdown format"
                    )

            else:
                x = x.strip()
                if x:
                    blocks.append(Text(x))

        return Group(blocks=blocks)
Пример #13
0
def validate_name(x: str):
    if re_check_name.match(x) is None:
        raise DPError(f"'{x}' is not a valid service name")
Пример #14
0
 def _set_name(self, name: str = None):
     if name:
         # validate name
         if not is_valid_id(name):
             raise DPError(f"Invalid name '{name}' for block")
         self.name = name