Write the Save Function
Exit

Write the Save Function

Create a function that writes expenses and the counter to a JSON file

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Converting Python data to JSON

Python's json.dumps() function converts a dictionary into a JSON-formatted string. The indent=2 argument adds line breaks and spacing so the file is readable:

json.dumps({"name": "Lunch"}, indent=2)
# '{\n  "name": "Lunch"\n}'

Writing to a file with pathlib

The pathlib module provides Path objects that represent file paths. Path.write_text() writes a string to a file, creating the file if it does not exist:

from pathlib import Path
Path("data.json").write_text("hello")

What to save

You need to save two things: the expenses dictionary and the counter. Without the counter, the server would reset its identifier sequence after a restart. Two expenses could end up with the same identifier.

The save function wraps both values in a single dictionary and writes it to the file.

Instructions

Create the save_expenses function between the models and the expenses = {} line.

  1. Define a function named save_expenses that takes no arguments.
  2. Inside the function, create a dictionary named data with two keys: "counter" set to counter and "expenses" set to expenses.
  3. Call DATA_FILE.write_text(json.dumps(data, indent=2)) to write the data to the file.