Skip to content
This repository was archived by the owner on Nov 6, 2025. It is now read-only.

Commit 0b00f9a

Browse files
authored
Add dateTime parsers (#6)
### Added - Add custom exception - Add date time parser for status messages
1 parent 9eb6974 commit 0b00f9a

5 files changed

Lines changed: 45 additions & 12 deletions

File tree

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](http://keepachangelog.com/)
55
and this project adheres to [Semantic Versioning](http://semver.org/).
66

7+
## 1.0 - 2018-04-22
8+
### Added
9+
- Add custom exception
10+
- Add date time parser for status messages
11+
- Initial public release
12+
713
## 0.3 - 2018-02-04
814
### Fixed
915
- Better exception handling & less code duplication

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,12 @@ postnl = PostNL_API('email@domain.com', 'password')
1717
shipments = postnl.get_relevant_shipments()
1818

1919
for shipment in shipments:
20-
print (shipment['key'])
20+
name = shipment['settings']['title']
21+
status = shipment['status']['formatted']['short']
22+
status = postnl.parse_datetime(status, '%d-%m-%Y', '%H:%M')
2123

24+
print (shipment['key'] + ' ' + name + ' ' + status)
25+
2226
# Get letters
2327
letters = postnl.get_letters()
2428
print (letters)

postnl_api/postnl_api.py

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
""" Python wrapper for the PostNL API """
22

3-
import logging
43
from datetime import datetime, timedelta
4+
import re
5+
56
import requests
67

78
BASE_URL = 'https://jouw.postnl.nl'
@@ -17,6 +18,11 @@
1718
'user-agent': 'PostNL/1 CFNetwork/889.3 Darwin/17.2.0',
1819
}
1920

21+
22+
class UnauthorizedException(Exception):
23+
pass
24+
25+
2026
class PostNL_API(object):
2127
""" Interface class for the PostNL API """
2228

@@ -39,10 +45,10 @@ def __init__(self, user, password):
3945
data = response.json()
4046

4147
except Exception:
42-
raise(Exception)
48+
raise(UnauthorizedException())
4349

4450
if 'error' in data:
45-
raise Exception(data['error'])
51+
raise UnauthorizedException(data['error'])
4652

4753
self._access_token = data['access_token']
4854
self._refresh_token = data['refresh_token']
@@ -70,10 +76,25 @@ def _refresh_access_token(self):
7076
response = requests.request(
7177
'POST', AUTHENTICATE_URL, data=payload, headers=DEFAULT_HEADER)
7278

73-
data = response.json() # TODO Add error handling
79+
data = response.json()
7480

7581
self._access_token = data['access_token']
7682

83+
def parse_datetime(self, text, dateFormat='%d-%m-%Y', timeFormat='%H:%M'):
84+
85+
def parse_date(date):
86+
return datetime.strptime(date.group(1)
87+
.replace(' ', '')[:-6], '%Y-%m-%dT%H:%M:%S').strftime(dateFormat)
88+
89+
def parse_time(date):
90+
return datetime.strptime(date.group(1)
91+
.replace(' ', '')[:-6], '%Y-%m-%dT%H:%M:%S').strftime(timeFormat)
92+
93+
text = re.sub(r'{(?:Date|dateAbs):(.*?)}', parse_date, text)
94+
text = re.sub(r'{(?:time):(.*?)}', parse_time, text)
95+
96+
return text
97+
7798
def get_shipments(self):
7899
""" Retrieve shipments """
79100

@@ -156,7 +177,7 @@ def validate_letters(self):
156177

157178
def get_letters(self):
158179
""" Retrieve letters """
159-
180+
160181
self._is_token_expired()
161182

162183
headers = {
@@ -237,7 +258,7 @@ def get_relevant_letters(self):
237258
expected_delivery_date = datetime.strptime(
238259
letter['expectedDeliveryDate'][:19], "%Y-%m-%dT%H:%M:%S")
239260

240-
if expected_delivery_date.date() == datetime.today().date():
261+
if expected_delivery_date.date() >= datetime.today().date():
241262
relevant_letters.append(letter)
242263

243264
return relevant_letters

postnl_api/test_postnl_api.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import argparse
22
from postnl_api import PostNL_API
33

4+
45
def main():
56
"""Main function."""
67
parser = argparse.ArgumentParser(description="Run the test for PostNL_API")
@@ -19,17 +20,18 @@ def main():
1920
# Get relevant shipments
2021
print("Getting shipments")
2122
shipments = postnl.get_relevant_shipments()
22-
print("Number of shipments: ",len(shipments))
23+
print("Number of shipments: ", len(shipments))
2324
print("Listing shipments:")
2425
for shipment in shipments:
2526
print (shipment['key'])
2627

2728
# Get letters
2829
print("Getting letters")
2930
letters = postnl.get_letters()
30-
print("Number of letters: ",len(letters))
31+
print("Number of letters: ", len(letters))
3132
print("Listing letters:")
3233
print (letters)
3334

35+
3436
if __name__ == '__main__':
35-
main()
37+
main()

setup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
from setuptools import setup, find_packages
22

33
setup(name='postnl_api',
4-
version='0.3',
4+
version='1.0',
55
description='Python wrapper for the PostNL API, a way to track packages using their online portal',
66
url='https://github.com/imicknl/python-postnl-api',
77
author='Mick Vleeshouwer',
88
author_email='mick@imick.nl',
99
license='MIT',
1010
install_requires=['requests>=2.0'],
1111
packages=find_packages(),
12-
zip_safe=True)
12+
zip_safe=True)

0 commit comments

Comments
 (0)