Skip to content

How To Use the Final Mile API - get_individual_images() #4

@josiahcarlson

Description

@josiahcarlson
def get_individual_images(
    pro: str,
    which: str,
    indexes: tuple = (),
    scac_or_carrier_id: Union[str, int] = "LN",
    test_output: bool = False,
):
    if not indexes:
        # up to 5 normal images, 5 issue images
        indexes = tuple(range(1, 11))

    partial_url = (
        url.format(
            method=which,
            api_key=get_api_key(scac_or_carrier_id),
            pro=pro,
            scac=scac_or_carrier_id,
        )  # providing dl=1 flag ensures we get content-disposition response header
        + "&dl=1"
    )
    written = []
    for i in indexes:
        with urllib.request.urlopen(partial_url + f"&image={i}") as resp:
            rr = resp.read()
            filename_header = resp.headers["content-disposition"]

        if not filename_header:
            # no more images
            break

        filename = filename_header.partition("=")[-1].strip('"')
        if test_output:
            expect = b"PNG" if filename.endswith(".png") else b"JFIF"
            typ = filename.rpartition(".")[-1]
            assert typ in ("png", "jpg"), f"Unexpected filetype: {typ}"
            assert (
                expect in rr[:8]
            ), f"{filename} does not have expected {typ} content"

        print("got a file from the api", filename, i)

        # image=0 will be <pro>.png
        # image=1+ will be <pro>_<image_type>.jpg
        with open(filename, "wb") as out:
            out.write(rr)

        written.append(filename)

    return written

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationinformationCode examples as-used in the docs

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions