dataforger 0.1.2__tar.gz → 0.1.3__tar.gz

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.
Files changed (25) hide show
  1. {dataforger-0.1.2/src/dataforger.egg-info → dataforger-0.1.3}/PKG-INFO +104 -3
  2. dataforger-0.1.3/README.md +214 -0
  3. {dataforger-0.1.2 → dataforger-0.1.3}/pyproject.toml +1 -1
  4. dataforger-0.1.3/src/dataforger/__init__.py +23 -0
  5. dataforger-0.1.3/src/dataforger/api.py +284 -0
  6. dataforger-0.1.3/src/dataforger/cli.py +211 -0
  7. dataforger-0.1.3/src/dataforger/datasets.py +263 -0
  8. {dataforger-0.1.2 → dataforger-0.1.3/src/dataforger.egg-info}/PKG-INFO +104 -3
  9. {dataforger-0.1.2 → dataforger-0.1.3}/src/dataforger.egg-info/SOURCES.txt +5 -1
  10. dataforger-0.1.3/tests/test_api.py +120 -0
  11. dataforger-0.1.3/tests/test_cli.py +97 -0
  12. dataforger-0.1.3/tests/test_datasets.py +109 -0
  13. dataforger-0.1.2/README.md +0 -113
  14. dataforger-0.1.2/src/dataforger/__init__.py +0 -3
  15. dataforger-0.1.2/src/dataforger/cli.py +0 -98
  16. dataforger-0.1.2/tests/test_cli.py +0 -47
  17. {dataforger-0.1.2 → dataforger-0.1.3}/LICENSE +0 -0
  18. {dataforger-0.1.2 → dataforger-0.1.3}/setup.cfg +0 -0
  19. {dataforger-0.1.2 → dataforger-0.1.3}/src/dataforger/core.py +0 -0
  20. {dataforger-0.1.2 → dataforger-0.1.3}/src/dataforger/countries.json +0 -0
  21. {dataforger-0.1.2 → dataforger-0.1.3}/src/dataforger/data.json +0 -0
  22. {dataforger-0.1.2 → dataforger-0.1.3}/src/dataforger.egg-info/dependency_links.txt +0 -0
  23. {dataforger-0.1.2 → dataforger-0.1.3}/src/dataforger.egg-info/entry_points.txt +0 -0
  24. {dataforger-0.1.2 → dataforger-0.1.3}/src/dataforger.egg-info/top_level.txt +0 -0
  25. {dataforger-0.1.2 → dataforger-0.1.3}/tests/test_core.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dataforger
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Generate fake data from Python or the command line.
5
5
  Author-email: Karmanshi Shrivastava <karmanshishrivastava20@gmail.com>
6
6
  License: MIT License
@@ -98,9 +98,12 @@ dataforger --rows 100 --field name:name --field email:email --field age:age --fo
98
98
  | --- | --- | --- |
99
99
  | `--field NAME:TYPE` | Output column name and the type of value to generate. Repeat to add fields. | Prompts for fields if omitted |
100
100
  | `--rows COUNT` | Number of records. Must be a positive integer. | `10` |
101
- | `--format {csv,json}` | Output file format. | `json` |
102
- | `--output PATH` | Path to the output file. | `data.json` or `data.csv`, based on format |
101
+ | `--format {csv,json}` | Output format; in dataset mode, exports saved records. | `json` |
102
+ | `--output PATH` | Path for generated or exported records. | `data.json` or `data.csv`, based on format |
103
103
  | `--seed INTEGER` | Seed for repeatable output. | Random |
104
+ | `--dataset KEY` | Reuse or create a persistent JSON dataset instead of writing an output file. | |
105
+ | `--replace-dataset` | Regenerate and replace an existing persistent dataset; requires `--dataset`. | |
106
+ | `--data-dir PATH` | Directory for persistent datasets. | `~/.dataforger/datasets` |
104
107
 
105
108
  `NAME` is the column/key to write in the output; choose any non-empty name.
106
109
  `TYPE` must be one of the supported field types below. For example,
@@ -160,3 +163,101 @@ Its parameters are `fields` (a mapping of output column names to supported
160
163
  types), `rows` (positive record count), and optional `seed` (integer for
161
164
  repeatable values). `write_data` takes `records`, `output` (path), and
162
165
  `format` (`"csv"` or `"json"`).
166
+
167
+ ### Persistent datasets
168
+
169
+ Persistent datasets let separate CLI runs, Python calls, and REST requests
170
+ reuse exactly the same records. Use a unique key for each dataset:
171
+
172
+ ```console
173
+ dataforger --dataset customers --field id:uuid --field name:name --rows 100 --seed 42
174
+ ```
175
+
176
+ Repeat the same command to load the saved records rather than generating new
177
+ ones. By default, a key cannot be reused with different fields, row counts, or
178
+ seed; Dataforger reports a conflict instead of silently changing the fixture.
179
+ Use `--replace-dataset` to explicitly regenerate it. Dataset keys are limited
180
+ to letters, numbers, dots, underscores, and hyphens.
181
+ To retrieve a dataset without supplying its generation parameters, omit
182
+ `--field`; use `--output` and `--format` to export the saved records:
183
+
184
+ ```console
185
+ dataforger --dataset customers --format csv --output customers.csv
186
+ ```
187
+
188
+ Datasets are stored as JSON files in `~/.dataforger/datasets` by default. Set
189
+ `DATAFORGER_DATA_DIR` to share another location across CLI and Python usage,
190
+ or pass `--data-dir PATH` to the CLI. The API server uses the same configured
191
+ directory; `dataforger --serve --data-dir PATH` sets it for that server.
192
+ Writes are atomic and serialized across threads and processes on the same
193
+ machine. For containerized deployments, mount a persistent volume at the
194
+ configured directory.
195
+
196
+ The Python API exposes the same operations:
197
+
198
+ ```python
199
+ from dataforger import get_dataset, get_or_create_dataset, replace_dataset
200
+
201
+ customers = get_or_create_dataset(
202
+ "customers",
203
+ {"id": "uuid", "name": "name"},
204
+ rows=100,
205
+ seed=42,
206
+ )
207
+ same_customers = get_dataset("customers")
208
+ replacement = replace_dataset(
209
+ "customers",
210
+ {"id": "uuid", "name": "name"},
211
+ rows=100,
212
+ seed=43,
213
+ )
214
+ ```
215
+
216
+ `get_or_create_dataset` returns an existing dataset only when the generation
217
+ parameters match. It raises `DatasetConflictError` when they differ and
218
+ `DatasetNotFoundError` is raised when `get_dataset` cannot find a key.
219
+ `replace_dataset` explicitly generates and stores a replacement. All three
220
+ functions accept an optional `directory` argument to override the default
221
+ store directory.
222
+
223
+ ## HTTP API
224
+
225
+ Start the built-in HTTP API with:
226
+
227
+ ```console
228
+ dataforger --serve
229
+ ```
230
+
231
+ The server listens on `127.0.0.1:8000` by default. Use `--host` and `--port`
232
+ to change the bind address and port. The API has no authentication, so keep it
233
+ on localhost unless you put it behind an appropriately secured service.
234
+
235
+ Generate records with a JSON `POST` request to `/api/v1/generate`:
236
+
237
+ ```console
238
+ curl -X POST http://127.0.0.1:8000/api/v1/generate ^
239
+ -H "Content-Type: application/json" ^
240
+ -d "{\"fields\":{\"name\":\"name\",\"email\":\"email\",\"age\":\"age\"},\"rows\":2,\"seed\":42}"
241
+ ```
242
+
243
+ `fields` is a mapping of output names to supported field types, `rows` is
244
+ optional (defaults to `10`, maximum `10000`), and `seed` is optional. The
245
+ request body is limited to 1 MiB and `fields` to 100 entries. Responses use
246
+ JSON; successful generation returns `{"count": 2, "data": [...]}`, and invalid
247
+ requests return a JSON `error` with an appropriate HTTP status.
248
+
249
+ `GET /api/v1/fields` lists supported field types. `GET /health` returns the
250
+ server health status.
251
+
252
+ Persistent datasets use:
253
+
254
+ * `POST /api/v1/datasets` with `key`, `fields`, and optional `rows` and `seed`
255
+ to create or reuse a dataset. Reusing the key with different generation
256
+ parameters returns `409 Conflict`.
257
+ * `GET /api/v1/datasets/{key}` to retrieve a saved dataset.
258
+ * `PUT /api/v1/datasets/{key}` with `fields` and optional `rows` and `seed` to
259
+ explicitly generate or replace the dataset.
260
+
261
+ These routes use the same JSON file store as the Python and CLI interfaces.
262
+ The API has no authentication; keep it bound to localhost unless protected by
263
+ an appropriately secured service.
@@ -0,0 +1,214 @@
1
+ # dataforger
2
+
3
+ Generate realistic fake data from Python or the command line, and save it as
4
+ CSV or JSON. Dataforger uses only the Python standard library and has no
5
+ third-party runtime dependencies.
6
+
7
+ Built-in names, streets, companies, and email domains are stored in
8
+ `src/dataforger/data.json`. Country names and their associated cities are
9
+ stored in `src/dataforger/countries.json`; when generating a record with both
10
+ country and city fields, the city is selected from that country's list.
11
+
12
+ ## Install
13
+
14
+ Requires Python 3.10 or later.
15
+
16
+ From a checkout of this repository:
17
+
18
+ ```console
19
+ python -m pip install .
20
+ ```
21
+
22
+ After publishing the package to PyPI:
23
+
24
+ ```console
25
+ python -m pip install dataforger
26
+ ```
27
+
28
+ ## Publishing to PyPI
29
+
30
+ The GitHub Actions workflow runs the tests on Python 3.10 through 3.13 and
31
+ builds wheel and source distributions on pushes and pull requests. To publish,
32
+ configure a PyPI trusted publisher for this GitHub repository, using workflow
33
+ `.github/workflows/publish.yml` and the GitHub environment `pypi`. Then create
34
+ and publish a GitHub Release; the workflow publishes its tested distributions
35
+ to PyPI using trusted publishing.
36
+
37
+ ## Command line
38
+
39
+ Run `dataforger` without field options for an interactive prompt. Or specify
40
+ all options directly:
41
+
42
+ ```console
43
+ dataforger --rows 100 --field name:name --field email:email --field age:age --format csv --output users.csv --seed 42
44
+ ```
45
+
46
+ ### CLI options
47
+
48
+ | Option | Description | Default |
49
+ | --- | --- | --- |
50
+ | `--field NAME:TYPE` | Output column name and the type of value to generate. Repeat to add fields. | Prompts for fields if omitted |
51
+ | `--rows COUNT` | Number of records. Must be a positive integer. | `10` |
52
+ | `--format {csv,json}` | Output format; in dataset mode, exports saved records. | `json` |
53
+ | `--output PATH` | Path for generated or exported records. | `data.json` or `data.csv`, based on format |
54
+ | `--seed INTEGER` | Seed for repeatable output. | Random |
55
+ | `--dataset KEY` | Reuse or create a persistent JSON dataset instead of writing an output file. | |
56
+ | `--replace-dataset` | Regenerate and replace an existing persistent dataset; requires `--dataset`. | |
57
+ | `--data-dir PATH` | Directory for persistent datasets. | `~/.dataforger/datasets` |
58
+
59
+ `NAME` is the column/key to write in the output; choose any non-empty name.
60
+ `TYPE` must be one of the supported field types below. For example,
61
+ `--field first_name:first_name` creates a column named `first_name` using
62
+ generated first names, while `--field given:first_name` creates the same kind
63
+ of values under the column name `given`.
64
+
65
+ ### Supported field types
66
+
67
+ | Type | Generated value |
68
+ | --- | --- |
69
+ | `name` | Full name |
70
+ | `first_name` | First name |
71
+ | `last_name` | Last name |
72
+ | `email` | Email address using a reserved example domain |
73
+ | `phone` | Phone-like number |
74
+ | `address` | Street address including a generated city |
75
+ | `city` | City from the bundled country-to-city data |
76
+ | `country` | Country from the bundled country-to-city data |
77
+ | `company` | Company name |
78
+ | `uuid` | UUID |
79
+ | `date` | Date between 1970-01-01 and today |
80
+ | `age` | Integer from 0 to 100 |
81
+ | `integer` | Integer from 0 to 100,000 |
82
+ | `float` | Decimal value from 0 to 100,000 |
83
+ | `boolean` | `true` or `false` |
84
+
85
+ When a record requests both `country` and `city`, the city is selected from
86
+ that country's city list. If it also requests `address`, its city matches
87
+ those fields.
88
+
89
+ ## Python API
90
+
91
+ ```python
92
+ from dataforger import generate_data, write_data
93
+
94
+ records = generate_data(
95
+ {
96
+ "first_name": "first_name",
97
+ "last_name": "last_name",
98
+ "country": "country",
99
+ "city": "city",
100
+ "email": "email",
101
+ "age": "age",
102
+ },
103
+ rows=100,
104
+ seed=42,
105
+ )
106
+
107
+ write_data(records, "users.json", "json")
108
+ write_data(records, "users.csv", "csv")
109
+ ```
110
+
111
+ `generate_data` returns a list of dictionaries. Pass the resulting records,
112
+ an output path, and either `"csv"` or `"json"` to `write_data`.
113
+ Its parameters are `fields` (a mapping of output column names to supported
114
+ types), `rows` (positive record count), and optional `seed` (integer for
115
+ repeatable values). `write_data` takes `records`, `output` (path), and
116
+ `format` (`"csv"` or `"json"`).
117
+
118
+ ### Persistent datasets
119
+
120
+ Persistent datasets let separate CLI runs, Python calls, and REST requests
121
+ reuse exactly the same records. Use a unique key for each dataset:
122
+
123
+ ```console
124
+ dataforger --dataset customers --field id:uuid --field name:name --rows 100 --seed 42
125
+ ```
126
+
127
+ Repeat the same command to load the saved records rather than generating new
128
+ ones. By default, a key cannot be reused with different fields, row counts, or
129
+ seed; Dataforger reports a conflict instead of silently changing the fixture.
130
+ Use `--replace-dataset` to explicitly regenerate it. Dataset keys are limited
131
+ to letters, numbers, dots, underscores, and hyphens.
132
+ To retrieve a dataset without supplying its generation parameters, omit
133
+ `--field`; use `--output` and `--format` to export the saved records:
134
+
135
+ ```console
136
+ dataforger --dataset customers --format csv --output customers.csv
137
+ ```
138
+
139
+ Datasets are stored as JSON files in `~/.dataforger/datasets` by default. Set
140
+ `DATAFORGER_DATA_DIR` to share another location across CLI and Python usage,
141
+ or pass `--data-dir PATH` to the CLI. The API server uses the same configured
142
+ directory; `dataforger --serve --data-dir PATH` sets it for that server.
143
+ Writes are atomic and serialized across threads and processes on the same
144
+ machine. For containerized deployments, mount a persistent volume at the
145
+ configured directory.
146
+
147
+ The Python API exposes the same operations:
148
+
149
+ ```python
150
+ from dataforger import get_dataset, get_or_create_dataset, replace_dataset
151
+
152
+ customers = get_or_create_dataset(
153
+ "customers",
154
+ {"id": "uuid", "name": "name"},
155
+ rows=100,
156
+ seed=42,
157
+ )
158
+ same_customers = get_dataset("customers")
159
+ replacement = replace_dataset(
160
+ "customers",
161
+ {"id": "uuid", "name": "name"},
162
+ rows=100,
163
+ seed=43,
164
+ )
165
+ ```
166
+
167
+ `get_or_create_dataset` returns an existing dataset only when the generation
168
+ parameters match. It raises `DatasetConflictError` when they differ and
169
+ `DatasetNotFoundError` is raised when `get_dataset` cannot find a key.
170
+ `replace_dataset` explicitly generates and stores a replacement. All three
171
+ functions accept an optional `directory` argument to override the default
172
+ store directory.
173
+
174
+ ## HTTP API
175
+
176
+ Start the built-in HTTP API with:
177
+
178
+ ```console
179
+ dataforger --serve
180
+ ```
181
+
182
+ The server listens on `127.0.0.1:8000` by default. Use `--host` and `--port`
183
+ to change the bind address and port. The API has no authentication, so keep it
184
+ on localhost unless you put it behind an appropriately secured service.
185
+
186
+ Generate records with a JSON `POST` request to `/api/v1/generate`:
187
+
188
+ ```console
189
+ curl -X POST http://127.0.0.1:8000/api/v1/generate ^
190
+ -H "Content-Type: application/json" ^
191
+ -d "{\"fields\":{\"name\":\"name\",\"email\":\"email\",\"age\":\"age\"},\"rows\":2,\"seed\":42}"
192
+ ```
193
+
194
+ `fields` is a mapping of output names to supported field types, `rows` is
195
+ optional (defaults to `10`, maximum `10000`), and `seed` is optional. The
196
+ request body is limited to 1 MiB and `fields` to 100 entries. Responses use
197
+ JSON; successful generation returns `{"count": 2, "data": [...]}`, and invalid
198
+ requests return a JSON `error` with an appropriate HTTP status.
199
+
200
+ `GET /api/v1/fields` lists supported field types. `GET /health` returns the
201
+ server health status.
202
+
203
+ Persistent datasets use:
204
+
205
+ * `POST /api/v1/datasets` with `key`, `fields`, and optional `rows` and `seed`
206
+ to create or reuse a dataset. Reusing the key with different generation
207
+ parameters returns `409 Conflict`.
208
+ * `GET /api/v1/datasets/{key}` to retrieve a saved dataset.
209
+ * `PUT /api/v1/datasets/{key}` with `fields` and optional `rows` and `seed` to
210
+ explicitly generate or replace the dataset.
211
+
212
+ These routes use the same JSON file store as the Python and CLI interfaces.
213
+ The API has no authentication; keep it bound to localhost unless protected by
214
+ an appropriately secured service.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "dataforger"
7
- version = "0.1.2"
7
+ version = "0.1.3"
8
8
  description = "Generate fake data from Python or the command line."
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
@@ -0,0 +1,23 @@
1
+ from dataforger.core import FIELD_TYPES, generate_data, write_data
2
+ from dataforger.datasets import (
3
+ Dataset,
4
+ DatasetConflictError,
5
+ DatasetIntegrityError,
6
+ DatasetNotFoundError,
7
+ get_dataset,
8
+ get_or_create_dataset,
9
+ replace_dataset,
10
+ )
11
+
12
+ __all__ = [
13
+ "FIELD_TYPES",
14
+ "Dataset",
15
+ "DatasetConflictError",
16
+ "DatasetIntegrityError",
17
+ "DatasetNotFoundError",
18
+ "generate_data",
19
+ "get_dataset",
20
+ "get_or_create_dataset",
21
+ "replace_dataset",
22
+ "write_data",
23
+ ]
@@ -0,0 +1,284 @@
1
+ import json
2
+ import logging
3
+ from http import HTTPStatus
4
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
5
+ from pathlib import Path
6
+ from typing import Any
7
+ from urllib.parse import unquote, urlsplit
8
+
9
+ from dataforger.core import FIELD_TYPES, generate_data
10
+ from dataforger.datasets import (
11
+ Dataset,
12
+ DatasetConflictError,
13
+ DatasetIntegrityError,
14
+ DatasetNotFoundError,
15
+ get_dataset,
16
+ get_or_create_dataset,
17
+ replace_dataset,
18
+ )
19
+
20
+ MAX_REQUEST_BYTES = 1_048_576
21
+ MAX_ROWS = 10_000
22
+ MAX_FIELDS = 100
23
+ _LOGGER = logging.getLogger(__name__)
24
+
25
+
26
+ class _ApiServer(ThreadingHTTPServer):
27
+ def __init__(
28
+ self,
29
+ address: tuple[str, int],
30
+ handler: type[BaseHTTPRequestHandler],
31
+ data_directory: str | Path | None = None,
32
+ ) -> None:
33
+ self.data_directory = data_directory
34
+ super().__init__(address, handler)
35
+
36
+
37
+ class _ApiHandler(BaseHTTPRequestHandler):
38
+ server_version = "DataforgerAPI/1.0"
39
+
40
+ def do_GET(self) -> None:
41
+ path = urlsplit(self.path).path
42
+ if path == "/health":
43
+ self._send_json(HTTPStatus.OK, {"status": "ok"})
44
+ elif path == "/api/v1/fields":
45
+ self._send_json(HTTPStatus.OK, {"fields": list(FIELD_TYPES)})
46
+ elif path.startswith("/api/v1/datasets/"):
47
+ key = unquote(path.removeprefix("/api/v1/datasets/"))
48
+ try:
49
+ dataset = get_dataset(key, getattr(self.server, "data_directory", None))
50
+ except DatasetNotFoundError as error:
51
+ self._send_error(HTTPStatus.NOT_FOUND, str(error))
52
+ except ValueError as error:
53
+ self._send_error(HTTPStatus.BAD_REQUEST, str(error))
54
+ except DatasetIntegrityError:
55
+ _LOGGER.exception("Persistent dataset failed its integrity check.")
56
+ self._send_error(
57
+ HTTPStatus.INTERNAL_SERVER_ERROR,
58
+ "Stored dataset is corrupt or unsupported.",
59
+ )
60
+ except OSError:
61
+ _LOGGER.exception("Unable to read persistent dataset.")
62
+ self._send_error(
63
+ HTTPStatus.INTERNAL_SERVER_ERROR,
64
+ "Unable to access dataset storage.",
65
+ )
66
+ else:
67
+ self._send_json(HTTPStatus.OK, _dataset_payload(dataset))
68
+ else:
69
+ self._send_error(HTTPStatus.NOT_FOUND, "Endpoint not found.")
70
+
71
+ def do_POST(self) -> None:
72
+ path = urlsplit(self.path).path
73
+ if path not in ("/api/v1/generate", "/api/v1/datasets"):
74
+ self._send_error(HTTPStatus.NOT_FOUND, "Endpoint not found.")
75
+ return
76
+
77
+ request = self._read_json_request()
78
+ if request is None:
79
+ return
80
+
81
+ allowed_properties = {"fields", "rows", "seed"}
82
+ if path == "/api/v1/datasets":
83
+ allowed_properties.add("key")
84
+ unexpected = set(request) - allowed_properties
85
+ if unexpected:
86
+ self._send_error(
87
+ HTTPStatus.BAD_REQUEST,
88
+ f"Unexpected request properties: {', '.join(sorted(unexpected))}.",
89
+ )
90
+ return
91
+
92
+ try:
93
+ fields, rows, seed = _parse_generation_options(request)
94
+ except ValueError as error:
95
+ self._send_error(HTTPStatus.BAD_REQUEST, str(error))
96
+ return
97
+
98
+ if path == "/api/v1/generate":
99
+ try:
100
+ records = generate_data(fields, rows=rows, seed=seed)
101
+ except ValueError as error:
102
+ self._send_error(HTTPStatus.BAD_REQUEST, str(error))
103
+ return
104
+ self._send_json(
105
+ HTTPStatus.OK,
106
+ {"count": len(records), "data": records},
107
+ )
108
+ return
109
+
110
+ key = request.get("key")
111
+ if not isinstance(key, str):
112
+ self._send_error(HTTPStatus.BAD_REQUEST, "'key' must be a string.")
113
+ return
114
+ try:
115
+ dataset = get_or_create_dataset(
116
+ key, fields, rows, seed, getattr(self.server, "data_directory", None)
117
+ )
118
+ except DatasetConflictError as error:
119
+ self._send_error(HTTPStatus.CONFLICT, str(error))
120
+ except ValueError as error:
121
+ self._send_error(HTTPStatus.BAD_REQUEST, str(error))
122
+ except DatasetIntegrityError:
123
+ _LOGGER.exception("Persistent dataset failed its integrity check.")
124
+ self._send_error(
125
+ HTTPStatus.INTERNAL_SERVER_ERROR,
126
+ "Stored dataset is corrupt or unsupported.",
127
+ )
128
+ except OSError:
129
+ _LOGGER.exception("Unable to create or load persistent dataset.")
130
+ self._send_error(
131
+ HTTPStatus.INTERNAL_SERVER_ERROR, "Unable to access dataset storage."
132
+ )
133
+ else:
134
+ self._send_json(HTTPStatus.OK, _dataset_payload(dataset))
135
+
136
+ def do_PUT(self) -> None:
137
+ path = urlsplit(self.path).path
138
+ prefix = "/api/v1/datasets/"
139
+ if not path.startswith(prefix):
140
+ self._send_error(HTTPStatus.NOT_FOUND, "Endpoint not found.")
141
+ return
142
+
143
+ key = unquote(path.removeprefix(prefix))
144
+ request = self._read_json_request()
145
+ if request is None:
146
+ return
147
+ unexpected = set(request) - {"fields", "rows", "seed"}
148
+ if unexpected:
149
+ self._send_error(
150
+ HTTPStatus.BAD_REQUEST,
151
+ f"Unexpected request properties: {', '.join(sorted(unexpected))}.",
152
+ )
153
+ return
154
+
155
+ try:
156
+ fields, rows, seed = _parse_generation_options(request)
157
+ dataset = replace_dataset(
158
+ key, fields, rows, seed, getattr(self.server, "data_directory", None)
159
+ )
160
+ except ValueError as error:
161
+ self._send_error(HTTPStatus.BAD_REQUEST, str(error))
162
+ except DatasetIntegrityError:
163
+ _LOGGER.exception("Persistent dataset failed its integrity check.")
164
+ self._send_error(
165
+ HTTPStatus.INTERNAL_SERVER_ERROR,
166
+ "Stored dataset is corrupt or unsupported.",
167
+ )
168
+ except OSError:
169
+ _LOGGER.exception("Unable to replace persistent dataset.")
170
+ self._send_error(
171
+ HTTPStatus.INTERNAL_SERVER_ERROR, "Unable to access dataset storage."
172
+ )
173
+ else:
174
+ self._send_json(HTTPStatus.OK, _dataset_payload(dataset))
175
+
176
+ def _read_json_request(self) -> dict[str, Any] | None:
177
+ content_length = self.headers.get("Content-Length")
178
+ if content_length is None:
179
+ self._send_error(
180
+ HTTPStatus.LENGTH_REQUIRED, "Content-Length header is required."
181
+ )
182
+ return None
183
+
184
+ try:
185
+ body_length = int(content_length)
186
+ except ValueError:
187
+ self._send_error(HTTPStatus.BAD_REQUEST, "Invalid Content-Length header.")
188
+ return None
189
+
190
+ if body_length < 0:
191
+ self._send_error(HTTPStatus.BAD_REQUEST, "Invalid Content-Length header.")
192
+ return None
193
+ if body_length > MAX_REQUEST_BYTES:
194
+ self._send_error(
195
+ HTTPStatus.REQUEST_ENTITY_TOO_LARGE, "Request body is too large."
196
+ )
197
+ return None
198
+
199
+ body = self.rfile.read(body_length)
200
+ if len(body) != body_length:
201
+ self._send_error(HTTPStatus.BAD_REQUEST, "Incomplete request body.")
202
+ return None
203
+
204
+ try:
205
+ request: Any = json.loads(body)
206
+ except (UnicodeDecodeError, json.JSONDecodeError):
207
+ self._send_error(HTTPStatus.BAD_REQUEST, "Request body must be valid JSON.")
208
+ return None
209
+
210
+ if not isinstance(request, dict):
211
+ self._send_error(
212
+ HTTPStatus.BAD_REQUEST, "Request body must be a JSON object."
213
+ )
214
+ return None
215
+ return request
216
+
217
+ def _send_error(self, status: HTTPStatus, message: str) -> None:
218
+ self._send_json(status, {"error": message})
219
+
220
+ def _send_json(self, status: HTTPStatus, payload: dict[str, object]) -> None:
221
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
222
+ self.send_response(status)
223
+ self.send_header("Content-Type", "application/json; charset=utf-8")
224
+ self.send_header("Content-Length", str(len(body)))
225
+ self.end_headers()
226
+ self.wfile.write(body)
227
+
228
+
229
+ def _parse_generation_options(
230
+ request: dict[str, Any],
231
+ ) -> tuple[dict[str, str], int, int | None]:
232
+ fields = request.get("fields")
233
+ if not isinstance(fields, dict) or not fields:
234
+ raise ValueError("'fields' must be a non-empty JSON object.")
235
+ if len(fields) > MAX_FIELDS:
236
+ raise ValueError(f"'fields' cannot contain more than {MAX_FIELDS} entries.")
237
+ if any(
238
+ not isinstance(name, str) or not isinstance(value, str)
239
+ for name, value in fields.items()
240
+ ):
241
+ raise ValueError("'fields' must map string names to string field types.")
242
+
243
+ rows = request.get("rows", 10)
244
+ if (
245
+ isinstance(rows, bool)
246
+ or not isinstance(rows, int)
247
+ or not 1 <= rows <= MAX_ROWS
248
+ ):
249
+ raise ValueError(f"'rows' must be an integer from 1 to {MAX_ROWS}.")
250
+
251
+ seed = request.get("seed")
252
+ if seed is not None and (isinstance(seed, bool) or not isinstance(seed, int)):
253
+ raise ValueError("'seed' must be an integer or null.")
254
+ return fields, rows, seed
255
+
256
+
257
+ def _dataset_payload(dataset: Dataset) -> dict[str, object]:
258
+ return {
259
+ "key": dataset.key,
260
+ "fields": dataset.fields,
261
+ "rows": dataset.rows,
262
+ "seed": dataset.seed,
263
+ "created_at": dataset.created_at,
264
+ "count": len(dataset.data),
265
+ "data": dataset.data,
266
+ }
267
+
268
+
269
+ def serve(
270
+ host: str = "127.0.0.1",
271
+ port: int = 8000,
272
+ data_directory: str | Path | None = None,
273
+ ) -> None:
274
+ """Serve the Dataforger HTTP API until interrupted."""
275
+ if not host:
276
+ raise ValueError("host must not be empty.")
277
+ if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
278
+ raise ValueError("port must be an integer from 1 to 65535.")
279
+
280
+ server = _ApiServer((host, port), _ApiHandler, data_directory)
281
+ try:
282
+ server.serve_forever()
283
+ finally:
284
+ server.server_close()