cnovatech-datapharma 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ """Official Python SDK for the Cnovatech Data Pharma API.
2
+
3
+ Typical use::
4
+
5
+ from cnovatech.datapharma import DataPharma
6
+
7
+ with DataPharma() as client: # reads DATAPHARMA_API_KEY
8
+ product = client.products.get("7891058001155", state="SP")
9
+ print(product.market.median_price, product.usage.remaining)
10
+
11
+ ``AsyncDataPharma`` offers the same surface with coroutines.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from . import errors, models, types
17
+ from ._client import AsyncDataPharma, DataPharma
18
+ from ._version import __version__
19
+
20
+ __all__ = ["AsyncDataPharma", "DataPharma", "__version__", "errors", "models", "types"]
@@ -0,0 +1,145 @@
1
+ """Synchronous and asynchronous clients for the Data Pharma API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from cnovatech.sdk_core.client import BaseAsyncClient, BaseSyncClient
8
+ from cnovatech.sdk_core.config import DEFAULT_MAX_RETRIES, DEFAULT_READ_TIMEOUT_SECONDS
9
+
10
+ from ._config import PRODUCT_SETTINGS
11
+ from .resources import (
12
+ Account,
13
+ AsyncAccount,
14
+ AsyncBrands,
15
+ AsyncProducts,
16
+ AsyncStores,
17
+ Brands,
18
+ Products,
19
+ Stores,
20
+ _operations as operations,
21
+ )
22
+
23
+ if TYPE_CHECKING:
24
+ import httpx
25
+
26
+ from .models import Health
27
+
28
+ _CONSTRUCTOR_DOC = """
29
+ Args:
30
+ api_key: Key issued by Data Pharma (``dm_...``). Defaults to the
31
+ ``DATAPHARMA_API_KEY`` environment variable. Only ``health()`` works
32
+ without one.
33
+ base_url: Origin of the API. Defaults to ``DATAPHARMA_BASE_URL`` or production.
34
+ timeout: Read timeout in seconds, or an ``httpx.Timeout`` to set every
35
+ phase. The default of 150 s covers the first lookup of an uncached
36
+ product, which can take about 90 s. It applies to every request,
37
+ also through your own ``http_client``.
38
+ max_retries: Extra attempts for failures that cannot have been billed:
39
+ connection errors, 502/503 and the per-minute 429. Read timeouts,
40
+ 504 and quota errors are never retried.
41
+ max_units_per_request: Refuse, before sending, any call estimated to
42
+ cost more than this many quota units. Off by default.
43
+ http_client: Your own httpx client, for proxies, certificates or a
44
+ shared connection pool. The SDK does not close it and never follows
45
+ redirects through it, whatever its own settings.
46
+ transport: An httpx transport, used by tests to answer without a network.
47
+
48
+ The client keeps a connection pool: create one per process and close it
49
+ with ``close()`` or a ``with`` block. It can be shared between threads;
50
+ the ``usage`` counters are updated without a lock and may lag under heavy
51
+ concurrency. Responses, pages and exceptions can be pickled; a page
52
+ restored from a pickle cannot fetch the pages after it.
53
+ """
54
+
55
+
56
+ class DataPharma(BaseSyncClient):
57
+ """Client for the Data Pharma API using blocking I/O.
58
+
59
+ Attributes:
60
+ products: Catalogue, departments, brands, lookup by EAN, price history and coverage.
61
+ stores: Listing, lookup by name, assortment, competitors and price analyses.
62
+ brands: Where a brand is sold.
63
+ account: Profile, quota history, request log and API keys.
64
+ """
65
+
66
+ __doc__ = (__doc__ or "") + _CONSTRUCTOR_DOC
67
+
68
+ def __init__(
69
+ self,
70
+ api_key: str | None = None,
71
+ *,
72
+ base_url: str | None = None,
73
+ timeout: float | httpx.Timeout = DEFAULT_READ_TIMEOUT_SECONDS,
74
+ max_retries: int = DEFAULT_MAX_RETRIES,
75
+ max_units_per_request: int | None = None,
76
+ http_client: httpx.Client | None = None,
77
+ transport: httpx.BaseTransport | None = None,
78
+ ) -> None:
79
+ super().__init__(
80
+ PRODUCT_SETTINGS,
81
+ api_key,
82
+ base_url=base_url,
83
+ timeout=timeout,
84
+ max_retries=max_retries,
85
+ max_units_per_request=max_units_per_request,
86
+ http_client=http_client,
87
+ transport=transport,
88
+ )
89
+ self.products = Products(self._transport)
90
+ self.stores = Stores(self._transport)
91
+ self.brands = Brands(self._transport)
92
+ self.account = Account(self._transport)
93
+
94
+ def health(self) -> Health:
95
+ """Check that the API, its database and its cache are up.
96
+
97
+ No authentication and no quota cost.
98
+ """
99
+ return self._transport.execute(operations.health())
100
+
101
+
102
+ class AsyncDataPharma(BaseAsyncClient):
103
+ """Client for the Data Pharma API using asyncio.
104
+
105
+ Attributes:
106
+ products: Catalogue, departments, brands, lookup by EAN, price history and coverage.
107
+ stores: Listing, lookup by name, assortment, competitors and price analyses.
108
+ brands: Where a brand is sold.
109
+ account: Profile, quota history, request log and API keys.
110
+ """
111
+
112
+ __doc__ = (__doc__ or "") + _CONSTRUCTOR_DOC
113
+
114
+ def __init__(
115
+ self,
116
+ api_key: str | None = None,
117
+ *,
118
+ base_url: str | None = None,
119
+ timeout: float | httpx.Timeout = DEFAULT_READ_TIMEOUT_SECONDS,
120
+ max_retries: int = DEFAULT_MAX_RETRIES,
121
+ max_units_per_request: int | None = None,
122
+ http_client: httpx.AsyncClient | None = None,
123
+ transport: httpx.AsyncBaseTransport | None = None,
124
+ ) -> None:
125
+ super().__init__(
126
+ PRODUCT_SETTINGS,
127
+ api_key,
128
+ base_url=base_url,
129
+ timeout=timeout,
130
+ max_retries=max_retries,
131
+ max_units_per_request=max_units_per_request,
132
+ http_client=http_client,
133
+ transport=transport,
134
+ )
135
+ self.products = AsyncProducts(self._transport)
136
+ self.stores = AsyncStores(self._transport)
137
+ self.brands = AsyncBrands(self._transport)
138
+ self.account = AsyncAccount(self._transport)
139
+
140
+ async def health(self) -> Health:
141
+ """Check that the API, its database and its cache are up.
142
+
143
+ No authentication and no quota cost.
144
+ """
145
+ return await self._transport.execute(operations.health())
@@ -0,0 +1,24 @@
1
+ """Settings that bind the shared core to the Data Pharma API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from cnovatech.sdk_core.config import ProductSettings
6
+
7
+ from ._version import DISTRIBUTION_NAME, __version__
8
+ from .errors import EANNotFoundError, FilterRequiredError
9
+
10
+ PRODUCTION_BASE_URL = "https://data.pharma.cnovatech.com.br"
11
+ API_PREFIX = "/api/v1"
12
+ ENV_PREFIX = "DATAPHARMA_"
13
+
14
+ PRODUCT_SETTINGS = ProductSettings(
15
+ distribution_name=DISTRIBUTION_NAME,
16
+ version=__version__,
17
+ env_prefix=ENV_PREFIX,
18
+ default_base_url=PRODUCTION_BASE_URL,
19
+ api_prefix=API_PREFIX,
20
+ error_overrides={
21
+ "ean_not_found": EANNotFoundError,
22
+ "filter_required": FilterRequiredError,
23
+ },
24
+ )
@@ -0,0 +1,9 @@
1
+ """Version of the ``cnovatech-datapharma`` distribution, read from its installed metadata."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from cnovatech.sdk_core.metadata import read_distribution_version
6
+
7
+ DISTRIBUTION_NAME = "cnovatech-datapharma"
8
+
9
+ __version__ = read_distribution_version(DISTRIBUTION_NAME)
@@ -0,0 +1,117 @@
1
+ """Exceptions raised by the Data Pharma SDK.
2
+
3
+ Catch :class:`DataPharmaError` to handle anything the SDK raises, or one of
4
+ its subclasses for a specific situation::
5
+
6
+ from cnovatech.datapharma import DataPharma, errors
7
+
8
+ try:
9
+ product = client.products.get("7891058001155")
10
+ except errors.EANNotFoundError as exc:
11
+ print(exc.hint)
12
+ except errors.APITimeoutError:
13
+ ... # may have been billed; do not blindly repeat
14
+ except errors.DataPharmaError as exc:
15
+ print(exc)
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import TYPE_CHECKING, Any
21
+
22
+ from cnovatech.sdk_core.errors import (
23
+ APIConnectionError,
24
+ APIStatusError,
25
+ APITimeoutError,
26
+ AuthenticationError,
27
+ BadRequestError,
28
+ BudgetExceededError,
29
+ CnovatechError as DataPharmaError,
30
+ ConfigurationError,
31
+ FieldError,
32
+ InvalidRequestError,
33
+ NotFoundError,
34
+ PermissionDeniedError,
35
+ QuotaExceededError,
36
+ RateLimitError,
37
+ ServerError,
38
+ TrialExpiredError,
39
+ UnexpectedResponseError,
40
+ UnprocessableEntityError,
41
+ )
42
+
43
+ if TYPE_CHECKING:
44
+ from collections.abc import Sequence
45
+
46
+ from .models.stores import Store
47
+
48
+ __all__ = [
49
+ "APIConnectionError",
50
+ "APIStatusError",
51
+ "APITimeoutError",
52
+ "AmbiguousStoreError",
53
+ "AuthenticationError",
54
+ "BadRequestError",
55
+ "BudgetExceededError",
56
+ "ConfigurationError",
57
+ "DataPharmaError",
58
+ "EANNotFoundError",
59
+ "FieldError",
60
+ "FilterRequiredError",
61
+ "InvalidRequestError",
62
+ "NotFoundError",
63
+ "PermissionDeniedError",
64
+ "QuotaExceededError",
65
+ "RateLimitError",
66
+ "ServerError",
67
+ "StoreNotFoundError",
68
+ "TrialExpiredError",
69
+ "UnexpectedResponseError",
70
+ "UnprocessableEntityError",
71
+ ]
72
+
73
+
74
+ class EANNotFoundError(NotFoundError):
75
+ """404 ``ean_not_found``: the code is not in the catalogue. The call is not billed.
76
+
77
+ :attr:`hint` carries the API's suggestion, usually to check coverage of a
78
+ whole list with ``products.coverage()`` or to search the catalogue.
79
+ """
80
+
81
+ @property
82
+ def ean(self) -> str | None:
83
+ """The code that was looked up, as reported by the API."""
84
+ return self._body_text("ean")
85
+
86
+
87
+ class StoreNotFoundError(NotFoundError):
88
+ """404 on a ``/stores/{store_id}`` route, or ``stores.find()`` without a match.
89
+
90
+ On ``stores.compare()`` the unknown identifier may be the ``competitor_id``.
91
+ """
92
+
93
+
94
+ class FilterRequiredError(BadRequestError):
95
+ """400 ``filter_required``: beyond page 20 the catalogue needs at least one filter."""
96
+
97
+
98
+ class AmbiguousStoreError(DataPharmaError):
99
+ """``stores.find()`` matched more than one store and none by exact name.
100
+
101
+ Attributes:
102
+ name: The name that was searched.
103
+ candidates: The stores that matched, so the caller can pick one.
104
+ """
105
+
106
+ def __init__(self, name: str, candidates: Sequence[Store]) -> None:
107
+ names = ", ".join(repr(candidate.store_name) for candidate in candidates[:5])
108
+ more = f" and {len(candidates) - 5} more" if len(candidates) > 5 else ""
109
+ super().__init__(
110
+ f"{name!r} matches {len(candidates)} stores and none by exact name: {names}{more}. "
111
+ "Add state= or city=, or pick one of the candidates by store_id."
112
+ )
113
+ self.name = name
114
+ self.candidates = list(candidates)
115
+
116
+ def __reduce__(self) -> tuple[Any, ...]:
117
+ return type(self), (self.name, self.candidates), self.__dict__
@@ -0,0 +1,262 @@
1
+ """Response models of the Data Pharma API, one module per resource.
2
+
3
+ Every model is immutable and keeps fields the API adds later in
4
+ ``model_extra``. Responses produced by a client carry ``request_info``; list
5
+ responses offer ``to_dataframe()``; paginated ones are ``SyncPage`` or
6
+ ``AsyncPage`` instances.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from .account import (
12
+ AccountUsage,
13
+ ApiKey,
14
+ ApiKeys,
15
+ AsyncLogsPage,
16
+ LogEntry,
17
+ LogsPage,
18
+ LogsSummary,
19
+ Plan,
20
+ Profile,
21
+ Subscription,
22
+ Trial,
23
+ UsageDay,
24
+ UsageHistory,
25
+ UsageMonth,
26
+ )
27
+ from .brands import StoreByBrand, StoresByBrandResponse, StoresByBrandSummary
28
+ from .common import (
29
+ APIResponse,
30
+ Health,
31
+ ListMeta,
32
+ PaginationMeta,
33
+ RateLimitState,
34
+ Record,
35
+ RequestInfo,
36
+ StoreRef,
37
+ TabularResponse,
38
+ Usage,
39
+ )
40
+ from .history import MarketBucket, PriceHistory, StorePoint, StoreSeries
41
+ from .products import (
42
+ AsyncBrandsPage,
43
+ AsyncCatalogPage,
44
+ AsyncProductsByBrandPage,
45
+ Brand,
46
+ BrandProduct,
47
+ BrandsPage,
48
+ CatalogPage,
49
+ CatalogProduct,
50
+ Category,
51
+ CoverageItem,
52
+ CoverageResponse,
53
+ CoverageSummary,
54
+ Department,
55
+ DepartmentsResponse,
56
+ DepartmentsSummary,
57
+ MarketStats,
58
+ Product,
59
+ ProductsByBrandPage,
60
+ StoreOffer,
61
+ )
62
+ from .stores import (
63
+ AssortmentItem,
64
+ AssortmentPage,
65
+ AsyncAssortmentPage,
66
+ AsyncComparisonPage,
67
+ AsyncMarketPositionPage,
68
+ AsyncOpportunitiesPage,
69
+ AsyncStoresPage,
70
+ ComparisonItem,
71
+ ComparisonPage,
72
+ ComparisonSummary,
73
+ CompetitivenessItem,
74
+ CompetitivenessResponse,
75
+ CompetitivenessSummary,
76
+ Competitor,
77
+ CompetitorsResponse,
78
+ CompetitorsSummary,
79
+ MarketPositionItem,
80
+ MarketPositionPage,
81
+ MarketPositionStats,
82
+ MarketPositionSummary,
83
+ OpportunitiesPage,
84
+ OpportunitiesSummary,
85
+ Opportunity,
86
+ OpportunityMarketStats,
87
+ Store,
88
+ StoresPage,
89
+ )
90
+ from .trends import (
91
+ AsyncPriceChangesPage,
92
+ AsyncProductPriceChangesPage,
93
+ AsyncProductPromotionsPage,
94
+ AsyncProductStockoutsPage,
95
+ AsyncPromotionsPage,
96
+ AsyncStockoutsPage,
97
+ AsyncStorePromotionsPage,
98
+ AsyncStoreStockoutsPage,
99
+ CategoryPromotions,
100
+ CategoryStockouts,
101
+ DayPromotions,
102
+ DayStockouts,
103
+ PriceChange,
104
+ PriceChangeProduct,
105
+ PriceChangesPage,
106
+ PriceChangesSummary,
107
+ ProductPriceChangesPage,
108
+ ProductPriceChangesSummary,
109
+ ProductPromotionsPage,
110
+ ProductPromotionsSummary,
111
+ ProductStockoutsPage,
112
+ ProductStockoutsSummary,
113
+ PromotionMarket,
114
+ PromotionPeriod,
115
+ PromotionProduct,
116
+ PromotionsPage,
117
+ PromotionsSummary,
118
+ StatePromotions,
119
+ StateRepricing,
120
+ StateStockouts,
121
+ StockoutMarket,
122
+ StockoutPeriod,
123
+ StockoutProduct,
124
+ StockoutsPage,
125
+ StockoutsSummary,
126
+ StorePriceChanges,
127
+ StorePromotion,
128
+ StorePromotionProduct,
129
+ StorePromotionsPage,
130
+ StorePromotionsSummary,
131
+ StoreStockout,
132
+ StoreStockoutProduct,
133
+ StoreStockoutsPage,
134
+ StoreStockoutsSummary,
135
+ TrendProduct,
136
+ TrendStore,
137
+ )
138
+
139
+ __all__ = [
140
+ "APIResponse",
141
+ "AccountUsage",
142
+ "ApiKey",
143
+ "ApiKeys",
144
+ "AssortmentItem",
145
+ "AssortmentPage",
146
+ "AsyncAssortmentPage",
147
+ "AsyncBrandsPage",
148
+ "AsyncCatalogPage",
149
+ "AsyncComparisonPage",
150
+ "AsyncLogsPage",
151
+ "AsyncMarketPositionPage",
152
+ "AsyncOpportunitiesPage",
153
+ "AsyncPriceChangesPage",
154
+ "AsyncProductPriceChangesPage",
155
+ "AsyncProductPromotionsPage",
156
+ "AsyncProductStockoutsPage",
157
+ "AsyncProductsByBrandPage",
158
+ "AsyncPromotionsPage",
159
+ "AsyncStockoutsPage",
160
+ "AsyncStorePromotionsPage",
161
+ "AsyncStoreStockoutsPage",
162
+ "AsyncStoresPage",
163
+ "Brand",
164
+ "BrandProduct",
165
+ "BrandsPage",
166
+ "CatalogPage",
167
+ "CatalogProduct",
168
+ "Category",
169
+ "CategoryPromotions",
170
+ "CategoryStockouts",
171
+ "ComparisonItem",
172
+ "ComparisonPage",
173
+ "ComparisonSummary",
174
+ "CompetitivenessItem",
175
+ "CompetitivenessResponse",
176
+ "CompetitivenessSummary",
177
+ "Competitor",
178
+ "CompetitorsResponse",
179
+ "CompetitorsSummary",
180
+ "CoverageItem",
181
+ "CoverageResponse",
182
+ "CoverageSummary",
183
+ "DayPromotions",
184
+ "DayStockouts",
185
+ "Department",
186
+ "DepartmentsResponse",
187
+ "DepartmentsSummary",
188
+ "Health",
189
+ "ListMeta",
190
+ "LogEntry",
191
+ "LogsPage",
192
+ "LogsSummary",
193
+ "MarketBucket",
194
+ "MarketPositionItem",
195
+ "MarketPositionPage",
196
+ "MarketPositionStats",
197
+ "MarketPositionSummary",
198
+ "MarketStats",
199
+ "OpportunitiesPage",
200
+ "OpportunitiesSummary",
201
+ "Opportunity",
202
+ "OpportunityMarketStats",
203
+ "PaginationMeta",
204
+ "Plan",
205
+ "PriceChange",
206
+ "PriceChangeProduct",
207
+ "PriceChangesPage",
208
+ "PriceChangesSummary",
209
+ "PriceHistory",
210
+ "Product",
211
+ "ProductPriceChangesPage",
212
+ "ProductPriceChangesSummary",
213
+ "ProductPromotionsPage",
214
+ "ProductPromotionsSummary",
215
+ "ProductStockoutsPage",
216
+ "ProductStockoutsSummary",
217
+ "ProductsByBrandPage",
218
+ "Profile",
219
+ "PromotionMarket",
220
+ "PromotionPeriod",
221
+ "PromotionProduct",
222
+ "PromotionsPage",
223
+ "PromotionsSummary",
224
+ "RateLimitState",
225
+ "Record",
226
+ "RequestInfo",
227
+ "StatePromotions",
228
+ "StateRepricing",
229
+ "StateStockouts",
230
+ "StockoutMarket",
231
+ "StockoutPeriod",
232
+ "StockoutProduct",
233
+ "StockoutsPage",
234
+ "StockoutsSummary",
235
+ "Store",
236
+ "StoreByBrand",
237
+ "StoreOffer",
238
+ "StorePoint",
239
+ "StorePriceChanges",
240
+ "StorePromotion",
241
+ "StorePromotionProduct",
242
+ "StorePromotionsPage",
243
+ "StorePromotionsSummary",
244
+ "StoreRef",
245
+ "StoreSeries",
246
+ "StoreStockout",
247
+ "StoreStockoutProduct",
248
+ "StoreStockoutsPage",
249
+ "StoreStockoutsSummary",
250
+ "StoresByBrandResponse",
251
+ "StoresByBrandSummary",
252
+ "StoresPage",
253
+ "Subscription",
254
+ "TabularResponse",
255
+ "TrendProduct",
256
+ "TrendStore",
257
+ "Trial",
258
+ "Usage",
259
+ "UsageDay",
260
+ "UsageHistory",
261
+ "UsageMonth",
262
+ ]