Skip to content

Order

The Order class enables you to place, inspect and get information on orders.

Use an existing order:

order = up42.initialize_order(order_id="ea36dee9-fed6-457e-8400-2c20ebd30f44")

Source code in up42/order.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
class Order:
    """
    The Order class enables you to place, inspect and get information on orders.

    Use an existing order:
    ```python
    order = up42.initialize_order(order_id="ea36dee9-fed6-457e-8400-2c20ebd30f44")
    ```
    """

    def __init__(
        self,
        auth: Auth,
        order_id: str,
        order_parameters: Optional[dict] = None,
        order_info: Optional[dict] = None,
    ):
        self.auth = auth
        self.workspace_id = auth.workspace_id
        self.order_id = order_id
        self.order_parameters = order_parameters
        if order_info is not None:
            self._info = order_info
        else:
            self._info = self.info

    def __repr__(self):
        return (
            f"Order(order_id: {self.order_id}, assets: {self._info['assets']}, "
            f"dataProvider: {self._info['dataProvider']}, status: {self._info['status']}, "
            f"createdAt: {self._info['createdAt']}, updatedAt: {self._info['updatedAt']})"
        )

    @property
    def info(self) -> dict:
        """
        Gets and updates the order information.
        """
        url = f"{self.auth._endpoint()}/workspaces/{self.workspace_id}/orders/{self.order_id}"
        response_json = self.auth._request(request_type="GET", url=url)
        self._info = response_json["data"]
        return self._info

    @property
    def status(self) -> str:
        """
        Gets the Order status. One of `PLACED`, `FAILED`, `FULFILLED`, `BEING_FULFILLED`, `FAILED_PERMANENTLY`.
        """
        status = self.info["status"]
        logger.info(f"Order is {status}")
        return status

    @property
    def order_details(self) -> dict:
        """
        Gets the Order Details.
        """
        if self.info["type"] == "TASKING":
            order_details = self.info["orderDetails"]
            return order_details
        logger.info("Order is not TASKING type. Order details are not provided.")
        return {}

    @property
    def is_fulfilled(self) -> bool:
        """
        Gets `True` if the order is fulfilled, `False` otherwise.
        Also see [status attribute](order-reference.md#up42.order.Order.status).
        """
        return self.status == "FULFILLED"

    def get_assets(self) -> List[Asset]:
        """
        Gets the Order assets or results.
        """
        if self.is_fulfilled:
            assets: List[str] = self.info["assets"]
            return [Asset(self.auth, asset_id=asset) for asset in assets]
        raise ValueError(
            f"Order {self.order_id} is not FULFILLED! Status is {self.status}"
        )

    @classmethod
    def place(cls, auth: Auth, order_parameters: dict) -> "Order":
        """
        Places an order.

        Args:
            auth: An authentication object.
            order_parameters: A dictionary like {dataProduct: ..., "params": {"id": ..., "aoi": ...}}

        Returns:
            Order: The placed order.
        """
        url = f"{auth._endpoint()}/workspaces/{auth.workspace_id}/orders"
        response_json = auth._request(
            request_type="POST", url=url, data=order_parameters
        )
        try:
            order_id = response_json["data"]["id"]  # type: ignore
        except KeyError as e:
            raise ValueError(f"Order was not placed: {response_json}") from e
        order = cls(auth=auth, order_id=order_id, order_parameters=order_parameters)
        logger.info(f"Order {order.order_id} is now {order.status}.")
        return order

    @staticmethod
    def estimate(auth: Auth, order_parameters: dict) -> int:
        """
        Returns an estimation of the cost of an order.

        Args:
            auth: An authentication object.
            order_parameters: A dictionary like {dataProduct: ..., "params": {"id": ..., "aoi": ...}}

        Returns:
            int: The estimated cost of the order
        """
        url = f"{auth._endpoint()}/workspaces/{auth.workspace_id}/orders/estimate"

        response_json = auth._request(
            request_type="POST", url=url, data=order_parameters
        )
        estimated_credits: int = response_json["data"]["credits"]  # type: ignore
        logger.info(
            f"Order is estimated to cost {estimated_credits} UP42 credits (order_parameters: {order_parameters})"
        )
        return estimated_credits

    def track_status(self, report_time: int = 120) -> str:
        """
        Continuously gets the order status until order is fulfilled or failed.

        Internally checks every `report_time` (s) for the status and prints the log.

        Warning:
            When placing orders of items that are in archive or cold storage,
            the order fulfillment can happen up to **24h after order placement**.
            In such cases,
            please make sure to set an appropriate `report_time`.

        Args:
            report_time: The interval (in seconds) when to get the order status.

        Returns:
            str: The final order status.
        """

        def substatus_messages(substatus: str) -> str:
            substatus_user_messages = {
                "FEASIBILITY_WAITING_UPLOAD": "Wait for feasibility.",
                "FEASIBILITY_WAITING_RESPONSE": "Feasibility is ready.",
                "QUOTATION_WAITING_UPLOAD": "Wait for quotation.",
                "QUOTATION_WAITING_RESPONSE": "Quotation is ready",
                "QUOTATION_ACCEPTED": "In progress.",
            }

            if substatus in substatus_user_messages:
                message = substatus_user_messages[substatus]
                return f"{substatus}, {message}"
            return f"{substatus}"

        logger.info(
            f"Tracking order status, reporting every {str(report_time)} seconds...",
        )
        time_asleep = 0

        # check order details and react for tasking orders.

        while not self.is_fulfilled:
            status = self.status
            substatus_message = (
                substatus_messages(self.order_details.get("subStatus", ""))
                if self.info["type"] == "TASKING"
                else ""
            )
            if status in ["PLACED", "BEING_FULFILLED"]:
                if time_asleep != 0 and time_asleep % report_time == 0:
                    logger.info(f"Order is {status}! - {self.order_id}")
                    logger.info(substatus_message)

            elif status in ["FAILED", "FAILED_PERMANENTLY"]:
                logger.info(f"Order is {status}! - {self.order_id}")
                raise ValueError("Order has failed!")

            sleep(report_time)
            time_asleep += report_time

        logger.info(f"Order is fulfilled successfully! - {self.order_id}")
        return self.status

info: dict property

Gets and updates the order information.

is_fulfilled: bool property

Gets True if the order is fulfilled, False otherwise. Also see status attribute.

order_details: dict property

Gets the Order Details.

status: str property

Gets the Order status. One of PLACED, FAILED, FULFILLED, BEING_FULFILLED, FAILED_PERMANENTLY.

estimate(auth, order_parameters) staticmethod

Returns an estimation of the cost of an order.

Parameters:

Name Type Description Default
auth Auth

An authentication object.

required
order_parameters dict

A dictionary like {dataProduct: ..., "params": {"id": ..., "aoi": ...}}

required

Returns:

Name Type Description
int int

The estimated cost of the order

Source code in up42/order.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
@staticmethod
def estimate(auth: Auth, order_parameters: dict) -> int:
    """
    Returns an estimation of the cost of an order.

    Args:
        auth: An authentication object.
        order_parameters: A dictionary like {dataProduct: ..., "params": {"id": ..., "aoi": ...}}

    Returns:
        int: The estimated cost of the order
    """
    url = f"{auth._endpoint()}/workspaces/{auth.workspace_id}/orders/estimate"

    response_json = auth._request(
        request_type="POST", url=url, data=order_parameters
    )
    estimated_credits: int = response_json["data"]["credits"]  # type: ignore
    logger.info(
        f"Order is estimated to cost {estimated_credits} UP42 credits (order_parameters: {order_parameters})"
    )
    return estimated_credits

get_assets()

Gets the Order assets or results.

Source code in up42/order.py
82
83
84
85
86
87
88
89
90
91
def get_assets(self) -> List[Asset]:
    """
    Gets the Order assets or results.
    """
    if self.is_fulfilled:
        assets: List[str] = self.info["assets"]
        return [Asset(self.auth, asset_id=asset) for asset in assets]
    raise ValueError(
        f"Order {self.order_id} is not FULFILLED! Status is {self.status}"
    )

place(auth, order_parameters) classmethod

Places an order.

Parameters:

Name Type Description Default
auth Auth

An authentication object.

required
order_parameters dict

A dictionary like {dataProduct: ..., "params": {"id": ..., "aoi": ...}}

required

Returns:

Name Type Description
Order Order

The placed order.

Source code in up42/order.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
@classmethod
def place(cls, auth: Auth, order_parameters: dict) -> "Order":
    """
    Places an order.

    Args:
        auth: An authentication object.
        order_parameters: A dictionary like {dataProduct: ..., "params": {"id": ..., "aoi": ...}}

    Returns:
        Order: The placed order.
    """
    url = f"{auth._endpoint()}/workspaces/{auth.workspace_id}/orders"
    response_json = auth._request(
        request_type="POST", url=url, data=order_parameters
    )
    try:
        order_id = response_json["data"]["id"]  # type: ignore
    except KeyError as e:
        raise ValueError(f"Order was not placed: {response_json}") from e
    order = cls(auth=auth, order_id=order_id, order_parameters=order_parameters)
    logger.info(f"Order {order.order_id} is now {order.status}.")
    return order

track_status(report_time=120)

Continuously gets the order status until order is fulfilled or failed.

Internally checks every report_time (s) for the status and prints the log.

Warning

When placing orders of items that are in archive or cold storage, the order fulfillment can happen up to 24h after order placement. In such cases, please make sure to set an appropriate report_time.

Parameters:

Name Type Description Default
report_time int

The interval (in seconds) when to get the order status.

120

Returns:

Name Type Description
str str

The final order status.

Source code in up42/order.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def track_status(self, report_time: int = 120) -> str:
    """
    Continuously gets the order status until order is fulfilled or failed.

    Internally checks every `report_time` (s) for the status and prints the log.

    Warning:
        When placing orders of items that are in archive or cold storage,
        the order fulfillment can happen up to **24h after order placement**.
        In such cases,
        please make sure to set an appropriate `report_time`.

    Args:
        report_time: The interval (in seconds) when to get the order status.

    Returns:
        str: The final order status.
    """

    def substatus_messages(substatus: str) -> str:
        substatus_user_messages = {
            "FEASIBILITY_WAITING_UPLOAD": "Wait for feasibility.",
            "FEASIBILITY_WAITING_RESPONSE": "Feasibility is ready.",
            "QUOTATION_WAITING_UPLOAD": "Wait for quotation.",
            "QUOTATION_WAITING_RESPONSE": "Quotation is ready",
            "QUOTATION_ACCEPTED": "In progress.",
        }

        if substatus in substatus_user_messages:
            message = substatus_user_messages[substatus]
            return f"{substatus}, {message}"
        return f"{substatus}"

    logger.info(
        f"Tracking order status, reporting every {str(report_time)} seconds...",
    )
    time_asleep = 0

    # check order details and react for tasking orders.

    while not self.is_fulfilled:
        status = self.status
        substatus_message = (
            substatus_messages(self.order_details.get("subStatus", ""))
            if self.info["type"] == "TASKING"
            else ""
        )
        if status in ["PLACED", "BEING_FULFILLED"]:
            if time_asleep != 0 and time_asleep % report_time == 0:
                logger.info(f"Order is {status}! - {self.order_id}")
                logger.info(substatus_message)

        elif status in ["FAILED", "FAILED_PERMANENTLY"]:
            logger.info(f"Order is {status}! - {self.order_id}")
            raise ValueError("Order has failed!")

        sleep(report_time)
        time_asleep += report_time

    logger.info(f"Order is fulfilled successfully! - {self.order_id}")
    return self.status