Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ picnic = PicnicAPI(username='username', password='password', country_code="NL")

The country_code parameter defaults to `NL`, but you have to change it if you live in a different country than the Netherlands (ISO 3166-1 Alpha-2). This obviously only works for countries that picnic services.

Picnic identifies each app install by a device ID (the `x-picnic-did` header). `PicnicAPI` generates a random one per instance. To keep the same ID across restarts, store `picnic.device_id` and pass it back in:

```python
picnic = PicnicAPI(auth_token=token, device_id=stored_device_id)
```

### Two-factor authentication (2FA)

For new logins, Picnic may require two-factor authentication. When 2FA is required, logging in raises a `Picnic2FARequired` exception. You then need to request a code and verify it:
Expand Down
29 changes: 21 additions & 8 deletions src/python_picnic_api2/client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import secrets
from hashlib import md5
from urllib.parse import quote

Expand Down Expand Up @@ -26,10 +27,7 @@
DEFAULT_URL = "https://storefront-prod.{}.picnicinternational.com/api/{}"
DEFAULT_COUNTRY_CODE = "NL"
DEFAULT_API_VERSION = "15"
_HEADERS = {
"x-picnic-agent": "30100;1.252.0-#15626;",
"x-picnic-did": "598F770380CA54B6",
}
_PICNIC_AGENT = "30100;1.252.0-#15626;"


class PicnicAPI:
Expand All @@ -39,18 +37,31 @@ def __init__(
password: str = None,
country_code: str = DEFAULT_COUNTRY_CODE,
auth_token: str = None,
device_id: str | None = None,
):
self._country_code = country_code
self._base_url = _url_generator(
DEFAULT_URL, self._country_code, DEFAULT_API_VERSION
)

# Picnic seems to start blocking static device ids
self._device_id = device_id or secrets.token_hex(8).upper()
self._picnic_headers = {
"x-picnic-agent": _PICNIC_AGENT,
"x-picnic-did": self._device_id,
}

self.session = PicnicAPISession(auth_token=auth_token)

# Login if not authenticated
if not self.session.authenticated and username and password:
self.login(username, password)

@property
def device_id(self) -> str:
"""The ``x-picnic-did`` value sent to Picnic; persist it to reuse it."""
return self._device_id

@staticmethod
def _parse_json(response, url: str):
"""Decode a response body, raising a descriptive error if it is not JSON.
Expand All @@ -74,7 +85,7 @@ def _get(self, path: str, add_picnic_headers=False):
url = self._base_url + path

# Make the request, add special picnic headers if needed
headers = _HEADERS if add_picnic_headers else None
headers = self._picnic_headers if add_picnic_headers else None
response = self.session.get(url, headers=headers)
body = self._parse_json(response, url)

Expand All @@ -89,7 +100,7 @@ def _post(
url = (base_url_override if base_url_override else self._base_url) + path
kwargs = {"json": data}
if add_picnic_headers:
kwargs["headers"] = _HEADERS
kwargs["headers"] = self._picnic_headers
response = self.session.post(url, **kwargs)
body = self._parse_json(response, url)

Expand Down Expand Up @@ -136,7 +147,7 @@ def login(self, username: str, password: str):
def _post_2fa(self, path: str, data=None):
"""POST for 2FA endpoints that may return empty (204) or JSON error bodies."""
url = self._base_url + path
response = self.session.post(url, json=data, headers=_HEADERS)
response = self.session.post(url, json=data, headers=self._picnic_headers)

if response.status_code == 204 or not response.content:
return None
Expand Down Expand Up @@ -315,7 +326,9 @@ def get_article_by_gtin(self, etan: str, maxRedirects: int = 5):
if url == "http://picnic.app/nl/link/store/storefront":
# gtin unknown
return None
r = self.session.get(url, headers=_HEADERS, allow_redirects=False)
r = self.session.get(
url, headers=self._picnic_headers, allow_redirects=False
)
maxRedirects -= 1
if ";id=" in r.url:
# found the article id
Expand Down
26 changes: 23 additions & 3 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
PicnicAuthError,
)

DEVICE_ID = "0123456789ABCDEF"
PICNIC_HEADERS = {
"x-picnic-agent": "30100;1.252.0-#15626;",
"x-picnic-did": "598F770380CA54B6",
"x-picnic-did": DEVICE_ID,
}


Expand All @@ -37,15 +38,17 @@ def setUp(self) -> None:
self.session_patcher = patch(
"python_picnic_api2.client.PicnicAPISession")
self.session_mock = self.session_patcher.start()
self.client = PicnicAPI(username="test@test.nl", password="test")
self.client = PicnicAPI(
username="test@test.nl", password="test", device_id=DEVICE_ID
)
self.expected_base_url = DEFAULT_URL.format("nl", "15")

def tearDown(self) -> None:
self.session_patcher.stop()

def test_login_credentials(self):
self.session_mock().authenticated = False
PicnicAPI(username="test@test.nl", password="test")
PicnicAPI(username="test@test.nl", password="test", device_id=DEVICE_ID)
self.session_mock().post.assert_called_with(
self.expected_base_url + "/user/login",
json={
Expand All @@ -56,6 +59,23 @@ def test_login_credentials(self):
headers=PICNIC_HEADERS,
)

def test_device_id_generated_per_client(self):
first, second = PicnicAPI(), PicnicAPI()
self.assertRegex(first.device_id, r"^[0-9A-F]{16}$")
self.assertNotEqual(first.device_id, second.device_id)

self.session_mock().get.return_value = self.MockResponse(
{"type": "ORDER", "id": "shopping_cart"}, 200
)
first.get_cart()
self.session_mock().get.assert_called_with(
self.expected_base_url + "/cart",
headers={
"x-picnic-agent": PICNIC_HEADERS["x-picnic-agent"],
"x-picnic-did": first.device_id,
},
)

def test_login_auth_token(self):
self.session_mock().authenticated = True
PicnicAPI(
Expand Down