Exercise: Convert User Record To JSON And Back¶
Requirement¶
In Exercise: Refactoring - Extract Both CSV Formats Into Module, we created a set of routines around user records of the following form:
{
'id': 2, # int
'firstname': 'Jörg',
'lastname': 'Faschingbauer',
'birth': '19.6.1966',
}
Preparing for MQTT communication (Exercise: MQTT: Publish User Records), it is
advisable to create a module userdb_json.py
that defines a transport
format for transmission that is
Converted to before sending
Converted from after receiving
Usage is envisioned as follows:
import userdb_csv
import userdb_json
for user in userdb_csv.read_csv_noheader('some.csv'): # could be ANY source, of course
json_str = userdb_json.to_json(user)
... publish json_str to MQTT topic ...
Test Code¶
The following test (see pytest Introduction, By Example for how to use it) can better express the requirement,
import userdb_json
def test_user_to_json():
user_sent = {
'id': 1,
'firstname': 'Jörg',
'lastname': 'Faschingbauer',
'birth': '19.6.1966',
}
json_user_sent = userdb_json.to_json(user_sent)
user_received = userdb_json.from_json(json_user_sent)
assert user_received['id'] == 1
assert user_received['firstname'] == 'Jörg'
assert user_received['lastname'] == 'Faschingbauer'
assert user_received['birth'] == '19.6.1966'