pxwebpy 0.5.0__tar.gz → 0.5.2__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 (39) hide show
  1. pxwebpy-0.5.2/CONTRIBUTING.md +7 -0
  2. pxwebpy-0.5.2/PKG-INFO +97 -0
  3. pxwebpy-0.5.2/README.md +76 -0
  4. pxwebpy-0.5.2/README.qmd +50 -0
  5. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/docs/_brand.yml +1 -0
  6. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/docs/_quarto.yml +11 -4
  7. pxwebpy-0.5.2/docs/development.qmd +74 -0
  8. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/docs/examples.qmd +3 -1
  9. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/docs/style.css +10 -0
  10. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/pyproject.toml +9 -0
  11. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/src/pxweb/_internal/client.py +20 -3
  12. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/src/pxweb/_internal/functions.py +34 -27
  13. pxwebpy-0.5.2/src/pxweb/_version.py +1 -0
  14. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/src/pxweb/api.py +96 -54
  15. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/tests/test_api.py +10 -3
  16. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/tests/test_client.py +11 -5
  17. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/uv.lock +28 -0
  18. pxwebpy-0.5.0/PKG-INFO +0 -81
  19. pxwebpy-0.5.0/README.md +0 -61
  20. pxwebpy-0.5.0/src/pxweb/_version.py +0 -1
  21. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/.github/workflows/ci.yml +0 -0
  22. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/.github/workflows/docs.yml +0 -0
  23. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/.github/workflows/release.yml +0 -0
  24. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/.gitignore +0 -0
  25. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/.python-version +0 -0
  26. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/LICENSE +0 -0
  27. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/docs/.gitignore +0 -0
  28. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/docs/_extensions/machow/interlinks/.gitignore +0 -0
  29. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/docs/_extensions/machow/interlinks/_extension.yml +0 -0
  30. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/docs/_extensions/machow/interlinks/interlinks.lua +0 -0
  31. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/docs/index.qmd +0 -0
  32. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/docs/version_config.py +0 -0
  33. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/src/pxweb/__init__.py +0 -0
  34. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/src/pxweb/_internal/__init__.py +0 -0
  35. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/src/pxweb/py.typed +0 -0
  36. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/tests/__snapshots__/test_functions.ambr +0 -0
  37. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/tests/code_list_agg_/303/205lder10/303/245rJ.json" +0 -0
  38. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/tests/table_variables_TAB5444.json +0 -0
  39. {pxwebpy-0.5.0 → pxwebpy-0.5.2}/tests/test_functions.py +0 -0
@@ -0,0 +1,7 @@
1
+ # Contributing to pxwebpy
2
+
3
+ All contributions are welcome, from small fixes to
4
+ implementing new features.
5
+
6
+ Please refer to the [development section](https://stefur.github.io/pxwebpy/development.html) of the
7
+ documentation to get started.
pxwebpy-0.5.2/PKG-INFO ADDED
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: pxwebpy
3
+ Version: 0.5.2
4
+ Summary: Client library for the PxWeb API to easily load data into a DataFrame.
5
+ Project-URL: Repository, https://github.com/stefur/pxwebpy
6
+ Project-URL: Documentation, https://stefur.github.io/pxwebpy
7
+ Author-email: Stefan Furne <stefan@furne.net>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: dataframes,pandas,polars,pxweb,statistics
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: requests-cache>=1.2.1
19
+ Requires-Dist: requests>=2.32.3
20
+ Description-Content-Type: text/markdown
21
+
22
+ # pxwebpy
23
+
24
+
25
+ [![GitHub Actions Workflow
26
+ Status](https://img.shields.io/github/actions/workflow/status/stefur/pxwebpy/ci.yml?style=flat-square&label=ci)](https://github.com/stefur/pxwebpy/actions/workflows/ci.yml)
27
+ ![PyPI -
28
+ Version](https://img.shields.io/pypi/v/pxwebpy?style=flat-square.png)
29
+ ![PyPI - Python
30
+ Version](https://img.shields.io/pypi/pyversions/pxwebpy?style=flat-square.png)
31
+ [![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json&style=flat-square)](https://github.com/astral-sh/uv)
32
+ [![ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&style=flat-square)](https://github.com/astral-sh/ruff)
33
+ Client library for the PxWeb API to easily load data into a DataFrame.
34
+
35
+ [Get started](https://stefur.github.io/pxwebpy) \|
36
+ [Examples](https://stefur.github.io/pxwebpy/examples) \|
37
+ [Reference](https://stefur.github.io/pxwebpy/reference)
38
+
39
+ ## Features
40
+
41
+ - Automatic query batching to handle large queries to respect rate
42
+ limits
43
+ - Multithreading for faster data fetching on large queries
44
+ - In-memory caching for quicker iterative use and exploration
45
+ - Wildcard support in queries
46
+ - BYODF (Bring Your Own DataFrame): native return formats for use with
47
+ `pandas` or `polars`
48
+ - Search for tables, browse and list tables, get metadata, and more
49
+
50
+ It has been tested with [Statistics Sweden](https://scb.se) and
51
+ [Statistics Norway](https://www.ssb.no).
52
+
53
+ > \[!NOTE\]
54
+ > pxwebpy only supports version 2.0 of the PxWeb API.
55
+
56
+ ## Quick start
57
+
58
+ ``` python
59
+ from pxweb import PxApi
60
+ import polars as pl
61
+
62
+ # Prepare to get data from the Statistics Norway API by using the builtin URL
63
+ api = PxApi("ssb")
64
+
65
+ # Set the language to english
66
+ api.language = "en"
67
+
68
+ # Check the population per year in Norway during the 1990's
69
+ data = api.get_table_data(
70
+ "06913",
71
+ value_codes={"Region": "0", "ContentsCode": "Folkemengde", "Tid": "199*"},
72
+ )
73
+
74
+ # Turn it into a polars dataframe
75
+ df = pl.DataFrame(data)
76
+
77
+ # A quick look at the result
78
+ print(df)
79
+ ```
80
+
81
+ shape: (10, 4)
82
+ ┌─────────────────────┬──────────────────────┬──────┬─────────┐
83
+ │ region ┆ contents ┆ year ┆ value │
84
+ │ --- ┆ --- ┆ --- ┆ --- │
85
+ │ str ┆ str ┆ str ┆ i64 │
86
+ ╞═════════════════════╪══════════════════════╪══════╪═════════╡
87
+ │ 0 The whole country ┆ Population 1 January ┆ 1990 ┆ 4233116 │
88
+ │ 0 The whole country ┆ Population 1 January ┆ 1991 ┆ 4249830 │
89
+ │ 0 The whole country ┆ Population 1 January ┆ 1992 ┆ 4273634 │
90
+ │ 0 The whole country ┆ Population 1 January ┆ 1993 ┆ 4299167 │
91
+ │ 0 The whole country ┆ Population 1 January ┆ 1994 ┆ 4324815 │
92
+ │ 0 The whole country ┆ Population 1 January ┆ 1995 ┆ 4348410 │
93
+ │ 0 The whole country ┆ Population 1 January ┆ 1996 ┆ 4369957 │
94
+ │ 0 The whole country ┆ Population 1 January ┆ 1997 ┆ 4392714 │
95
+ │ 0 The whole country ┆ Population 1 January ┆ 1998 ┆ 4417599 │
96
+ │ 0 The whole country ┆ Population 1 January ┆ 1999 ┆ 4445329 │
97
+ └─────────────────────┴──────────────────────┴──────┴─────────┘
@@ -0,0 +1,76 @@
1
+ # pxwebpy
2
+
3
+
4
+ [![GitHub Actions Workflow
5
+ Status](https://img.shields.io/github/actions/workflow/status/stefur/pxwebpy/ci.yml?style=flat-square&label=ci)](https://github.com/stefur/pxwebpy/actions/workflows/ci.yml)
6
+ ![PyPI -
7
+ Version](https://img.shields.io/pypi/v/pxwebpy?style=flat-square.png)
8
+ ![PyPI - Python
9
+ Version](https://img.shields.io/pypi/pyversions/pxwebpy?style=flat-square.png)
10
+ [![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json&style=flat-square)](https://github.com/astral-sh/uv)
11
+ [![ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&style=flat-square)](https://github.com/astral-sh/ruff)
12
+ Client library for the PxWeb API to easily load data into a DataFrame.
13
+
14
+ [Get started](https://stefur.github.io/pxwebpy) \|
15
+ [Examples](https://stefur.github.io/pxwebpy/examples) \|
16
+ [Reference](https://stefur.github.io/pxwebpy/reference)
17
+
18
+ ## Features
19
+
20
+ - Automatic query batching to handle large queries to respect rate
21
+ limits
22
+ - Multithreading for faster data fetching on large queries
23
+ - In-memory caching for quicker iterative use and exploration
24
+ - Wildcard support in queries
25
+ - BYODF (Bring Your Own DataFrame): native return formats for use with
26
+ `pandas` or `polars`
27
+ - Search for tables, browse and list tables, get metadata, and more
28
+
29
+ It has been tested with [Statistics Sweden](https://scb.se) and
30
+ [Statistics Norway](https://www.ssb.no).
31
+
32
+ > \[!NOTE\]
33
+ > pxwebpy only supports version 2.0 of the PxWeb API.
34
+
35
+ ## Quick start
36
+
37
+ ``` python
38
+ from pxweb import PxApi
39
+ import polars as pl
40
+
41
+ # Prepare to get data from the Statistics Norway API by using the builtin URL
42
+ api = PxApi("ssb")
43
+
44
+ # Set the language to english
45
+ api.language = "en"
46
+
47
+ # Check the population per year in Norway during the 1990's
48
+ data = api.get_table_data(
49
+ "06913",
50
+ value_codes={"Region": "0", "ContentsCode": "Folkemengde", "Tid": "199*"},
51
+ )
52
+
53
+ # Turn it into a polars dataframe
54
+ df = pl.DataFrame(data)
55
+
56
+ # A quick look at the result
57
+ print(df)
58
+ ```
59
+
60
+ shape: (10, 4)
61
+ ┌─────────────────────┬──────────────────────┬──────┬─────────┐
62
+ │ region ┆ contents ┆ year ┆ value │
63
+ │ --- ┆ --- ┆ --- ┆ --- │
64
+ │ str ┆ str ┆ str ┆ i64 │
65
+ ╞═════════════════════╪══════════════════════╪══════╪═════════╡
66
+ │ 0 The whole country ┆ Population 1 January ┆ 1990 ┆ 4233116 │
67
+ │ 0 The whole country ┆ Population 1 January ┆ 1991 ┆ 4249830 │
68
+ │ 0 The whole country ┆ Population 1 January ┆ 1992 ┆ 4273634 │
69
+ │ 0 The whole country ┆ Population 1 January ┆ 1993 ┆ 4299167 │
70
+ │ 0 The whole country ┆ Population 1 January ┆ 1994 ┆ 4324815 │
71
+ │ 0 The whole country ┆ Population 1 January ┆ 1995 ┆ 4348410 │
72
+ │ 0 The whole country ┆ Population 1 January ┆ 1996 ┆ 4369957 │
73
+ │ 0 The whole country ┆ Population 1 January ┆ 1997 ┆ 4392714 │
74
+ │ 0 The whole country ┆ Population 1 January ┆ 1998 ┆ 4417599 │
75
+ │ 0 The whole country ┆ Population 1 January ┆ 1999 ┆ 4445329 │
76
+ └─────────────────────┴──────────────────────┴──────┴─────────┘
@@ -0,0 +1,50 @@
1
+ ---
2
+ format: gfm
3
+ jupyter: python3
4
+ ---
5
+ # pxwebpy
6
+ [![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/stefur/pxwebpy/ci.yml?style=flat-square&label=ci)](https://github.com/stefur/pxwebpy/actions/workflows/ci.yml)
7
+ ![PyPI - Version](https://img.shields.io/pypi/v/pxwebpy?style=flat-square)
8
+ ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pxwebpy?style=flat-square)
9
+ [![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json&style=flat-square)](https://github.com/astral-sh/uv)
10
+ [![ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&style=flat-square)](https://github.com/astral-sh/ruff)
11
+ Client library for the PxWeb API to easily load data into a DataFrame.
12
+
13
+ [Get started](https://stefur.github.io/pxwebpy) | [Examples](https://stefur.github.io/pxwebpy/examples) | [Reference](https://stefur.github.io/pxwebpy/reference)
14
+
15
+ ## Features
16
+ - Automatic query batching to handle large queries to respect rate limits
17
+ - Multithreading for faster data fetching on large queries
18
+ - In-memory caching for quicker iterative use and exploration
19
+ - Wildcard support in queries
20
+ - BYODF (Bring Your Own DataFrame): native return formats for use with `pandas` or `polars`
21
+ - Search for tables, browse and list tables, get metadata, and more
22
+
23
+ It has been tested with [Statistics Sweden](https://scb.se) and [Statistics Norway](https://www.ssb.no).
24
+
25
+ > [!NOTE]
26
+ > pxwebpy only supports version 2.0 of the PxWeb API.
27
+
28
+ ## Quick start
29
+ ```{python}
30
+ from pxweb import PxApi
31
+ import polars as pl
32
+
33
+ # Prepare to get data from the Statistics Norway API by using the builtin URL
34
+ api = PxApi("ssb")
35
+
36
+ # Set the language to english
37
+ api.language = "en"
38
+
39
+ # Check the population per year in Norway during the 1990's
40
+ data = api.get_table_data(
41
+ "06913",
42
+ value_codes={"Region": "0", "ContentsCode": "Folkemengde", "Tid": "199*"},
43
+ )
44
+
45
+ # Turn it into a polars dataframe
46
+ df = pl.DataFrame(data)
47
+
48
+ # A quick look at the result
49
+ print(df)
50
+ ```
@@ -6,6 +6,7 @@ color:
6
6
  foreground: black
7
7
  background: white
8
8
  primary: green
9
+ secondary: green
9
10
 
10
11
  typography:
11
12
  fonts:
@@ -3,8 +3,6 @@ project:
3
3
  output-dir: _site
4
4
  pre-render: version_config.py
5
5
 
6
- encoding: utf-8
7
-
8
6
  format:
9
7
  html:
10
8
  toc: true
@@ -13,11 +11,14 @@ format:
13
11
  smooth-scroll: true
14
12
  code-copy: true
15
13
  code-overflow: wrap
14
+ highlight-style: github
15
+ code-block-bg: true
16
+ code-block-border-left: secondary
16
17
 
17
18
  brand: _brand.yml
18
19
 
19
20
  website:
20
- title: "pxwebpy {{< env VERSION >}}"
21
+ title: "pxwebpy"
21
22
  description: "Client library for the PxWeb API to easily load data into a DataFrame."
22
23
  repo-url: https://github.com/stefur/pxwebpy
23
24
  repo-actions: [issue]
@@ -31,6 +32,8 @@ website:
31
32
  file: index.qmd
32
33
  - text: "Examples"
33
34
  file: examples.qmd
35
+ - text: "Development"
36
+ file: development.qmd
34
37
  - text: "Reference"
35
38
  file: reference/index.qmd
36
39
  right:
@@ -39,12 +42,16 @@ website:
39
42
  target: _blank
40
43
 
41
44
  quartodoc:
42
- title: Reference
45
+ title: "pxwebpy v{{< env VERSION >}}"
43
46
  package: pxweb
44
47
  options:
45
48
  include_attributes: false
46
49
  dynamic: false
47
50
  render_interlinks: true
51
+ renderer:
52
+ style: markdown
53
+ table_style: description-list
54
+ show_signature_annotations: true
48
55
  sections:
49
56
  - title: API interaction
50
57
  desc: |
@@ -0,0 +1,74 @@
1
+ ---
2
+ title: Development
3
+ jupyter: python3
4
+ ---
5
+
6
+ Thank you for your interest in the development of `pxwebpy`!
7
+ This page explains how you can contribute. All improvements to code, documentation, and tests are welcome.
8
+
9
+ ## Setting up `uv` and the virtual environment
10
+
11
+ This project is set up to use [`uv`](https://docs.astral.sh/uv/) to manage Python and
12
+ dependencies. First, be sure you
13
+ [have `uv` installed](https://docs.astral.sh/uv/getting-started/installation/).
14
+
15
+ To install dependencies and set up the virtual environment:
16
+ ```bash
17
+ # Clone the repository
18
+ git clone https://github.com/stefur/pxwebpy.git
19
+ cd pxwebpy
20
+
21
+ # Sync dependencies and create the virtual environment
22
+ uv sync
23
+ ```
24
+
25
+ For more details on how to use `uv`, head over to the [`uv` docs](https://docs.astral.sh/uv/).
26
+
27
+ ## Formatting
28
+
29
+ ### Code
30
+ `ruff` is used for linting and formatting. Currently, no pre-commit hooks are configured. Instead `ruff` is included in the project as a development dependency.
31
+
32
+ The `ruff` command can be used in an activated virtual environment or using `uv run` to perform `ruff check` and `ruff format`. See the [documentation](https://docs.astral.sh/ruff/installation/) on how to otherwise install `ruff`.
33
+
34
+ ### Docstrings
35
+ Follow the [`NumPy`](https://numpydoc.readthedocs.io/en/latest/format.html#overview) style guide when writing docstrings. This is important for being able to [build the documentation](#building-the-documentation).
36
+
37
+ ## Running tests
38
+ Tests are run using `pytest`, typically via `uv run`:
39
+
40
+ ```bash
41
+ uv run pytest # all tests
42
+ uv run pytest -s tests/test_client.py # one test file
43
+ uv run pytest -s tests/test_client.py::test_call_raises_http_error # one specific test
44
+ ```
45
+
46
+ To check test coverage:
47
+
48
+ ```bash
49
+ uv run pytest --cov=src --cov-report=term
50
+ ```
51
+
52
+ Some tests utilize [`syrupy`](https://github.com/syrupy-project/syrupy) for snapshot testing to ensure consistency. If snapshots for some reason need to be updated run `uv run pytest --snapshot-update`.
53
+
54
+ ## Building the documentation
55
+ Documentation is built using [`quartodoc`](https://github.com/machow/quartodoc), thus you also need [`quarto`](https://quarto.org/docs/get-started/) installed on your machine if you wish to build the documentation locally. This is usually a good idea to check that the output looks as expected. The documentation is automatically built and published upon each release.
56
+
57
+ With `quarto` installed, building the documentation is done in two steps:
58
+
59
+ ```bash
60
+ uv run quartodoc build
61
+ uv run quarto render
62
+ ```
63
+
64
+ The rendered output is found in the folder called `_site`.
65
+
66
+ ## Submitting changes
67
+ When you’re ready to contribute:
68
+
69
+ 1. Clone the repository and create a new branch for your changes.
70
+ 2. Ensure that:
71
+ * All tests pass locally (`uv run pytest`)
72
+ * Code is linted and formatted (`uv run ruff check && uv run ruff format`)
73
+ * Documentation (if relevant) builds successfully
74
+ 3. Open a pull request to the `main` branch.
@@ -11,7 +11,9 @@ from rich.pretty import pretty_repr
11
11
 
12
12
  # Define some nicer formatting for code output
13
13
  def plain_pretty_formatter(value):
14
- return pretty_repr(value, max_depth=3, max_length=5, max_string=50, expand_all=True)
14
+ return pretty_repr(
15
+ value, max_depth=3, max_length=5, max_string=50, expand_all=True
16
+ )
15
17
 
16
18
 
17
19
  ip = get_ipython()
@@ -22,4 +22,14 @@ div.cell-output {
22
22
  padding: 0.5em;
23
23
  border-radius: 4px;
24
24
  margin-bottom: 1.3em;
25
+ }
26
+
27
+ /* Background color for parameters etc */
28
+ .doc-section dt code {
29
+ background: none;
30
+ }
31
+
32
+ .doc-section dt {
33
+ background-color: #c1ddd2;
34
+ display: block;
25
35
  }
@@ -25,6 +25,7 @@ requires-python = ">= 3.10"
25
25
 
26
26
  [project.urls]
27
27
  Repository = "https://github.com/stefur/pxwebpy"
28
+ Documentation = "https://stefur.github.io/pxwebpy"
28
29
 
29
30
  [build-system]
30
31
  requires = ["hatchling", "versioningit"]
@@ -42,6 +43,13 @@ packages = ["src/pxweb"]
42
43
  [tool.versioningit.write]
43
44
  file = "src/pxweb/_version.py"
44
45
 
46
+ [tool.ruff]
47
+ line-length = 80
48
+ fix = true
49
+
50
+ [tool.ruff.format]
51
+ docstring-code-format = true
52
+
45
53
  [dependency-groups]
46
54
  dev = [
47
55
  "ipykernel>=6.29.5",
@@ -55,6 +63,7 @@ dev = [
55
63
  "pytest-cov>=6.2.1",
56
64
  "quartodoc>=0.11.1",
57
65
  "rich>=14.1.0",
66
+ "ruff>=0.14.4",
58
67
  "syrupy>=4.8.0",
59
68
  "types-requests>=2.32.0.20241016",
60
69
  ]
@@ -1,10 +1,15 @@
1
1
  import time
2
2
  from threading import Lock
3
3
 
4
+ from packaging.version import parse
4
5
  from requests.exceptions import HTTPError, JSONDecodeError
5
6
  from requests_cache import CachedSession, CacheSettings, Request
6
7
 
7
8
 
9
+ class ApiVersionError(Exception):
10
+ """Raised if the API version is not >2.0.0"""
11
+
12
+
8
13
  class Client:
9
14
  def __init__(
10
15
  self,
@@ -24,18 +29,25 @@ class Client:
24
29
  self.lock = Lock()
25
30
 
26
31
  # Setting up params used for every query
27
- self.params: dict = {"lang": language, "outputFormat": "json-stat2"}
32
+ self.params: dict = {"lang": language}
28
33
 
29
34
  # Run the init without rate limiting since it's not set up yet
30
35
  configuration = self.call(endpoint="/config", enforce_rate_limit=False)
31
36
 
37
+ if parse(configuration.get("apiVersion", "0.0.0")) < parse("2.0.0"):
38
+ raise ApiVersionError(
39
+ f"""The version of the API is {configuration.get("apiVersion")}. pxwebpy requires 2.0.0 or greater."""
40
+ )
41
+
32
42
  self.max_data_cells: int = configuration.get("maxDataCells")
33
43
  self.max_calls: int = configuration.get("maxCallsPerTimeWindow")
34
44
  self.time_window: int = configuration.get("timeWindow")
35
45
  self.call_timestamps: list[float] = []
36
46
 
37
47
  # Now that we have the configuration set up, get the language if needed
38
- self.params["lang"] = language or configuration.get("defaultLanguage", None)
48
+ self.params["lang"] = language or configuration.get(
49
+ "defaultLanguage", None
50
+ )
39
51
 
40
52
  def call(
41
53
  self,
@@ -47,11 +59,16 @@ class Client:
47
59
  ) -> dict:
48
60
  """Call the endpoint with optional query"""
49
61
 
62
+ # If we're asking for table data, set parameters to get json-stat2
63
+ if endpoint.endswith("/data"):
64
+ params = params or {}
65
+ params["outputFormat"] = "json-stat2"
66
+
50
67
  # Set up the request and prepare it for being sent
51
68
  request = Request(
52
69
  method="POST" if query else "GET",
53
70
  url=self.url + endpoint,
54
- json=query or None,
71
+ json=query,
55
72
  params=self.params | params if params else self.params,
56
73
  ).prepare()
57
74
 
@@ -1,4 +1,5 @@
1
1
  import itertools
2
+ from typing import Literal
2
3
 
3
4
 
4
5
  def count_data_cells(value_codes: dict) -> int:
@@ -92,31 +93,33 @@ def expand_wildcards(value_codes: dict, source: dict) -> dict:
92
93
  expanded = []
93
94
  # Now start expanding the wildcards
94
95
  for value in codes:
95
- # TODO Probably use match case when 3.9 is dropped
96
- if value == "*":
97
- expanded.extend(items)
98
- elif value.endswith("*") and not value.startswith("*"):
99
- expanded.extend(
100
- [code for code in items if code.startswith(value[:-1])]
101
- ) # Drop the asterisk
102
- elif value.startswith("*") and not value.endswith("*"):
103
- expanded.extend(
104
- [code for code in items if code.endswith(value[1:])]
105
- ) # Same here
106
- elif value.startswith("*") and value.endswith("*"):
107
- expanded.extend(
108
- [code for code in items if value[1:-1] in code]
109
- ) # And here!
110
- else:
111
- # Just default if no wildcard
112
- expanded.append(value)
96
+ match value:
97
+ case "*":
98
+ expanded.extend(items)
99
+ case _ if value.endswith("*") and not value.startswith("*"):
100
+ expanded.extend(
101
+ [code for code in items if code.startswith(value[:-1])]
102
+ ) # Drop the asterisk
103
+ case _ if value.startswith("*") and not value.endswith("*"):
104
+ expanded.extend(
105
+ [code for code in items if code.endswith(value[1:])]
106
+ ) # Same here
107
+ case _ if value.startswith("*") and value.endswith("*"):
108
+ expanded.extend(
109
+ [code for code in items if value[1:-1] in code]
110
+ ) # And here!
111
+ case _:
112
+ # Just default if no wildcard
113
+ expanded.append(value)
113
114
 
114
115
  result[variable] = expanded
115
116
 
116
117
  return result
117
118
 
118
119
 
119
- def unpack_table_data(json_data: dict) -> list[dict]:
120
+ def unpack_table_data(
121
+ json_data: dict, show: Literal["code", "value", "code_value"] | None = None
122
+ ) -> list[dict]:
120
123
  """
121
124
  Takes json-stat2 and flattens it into a list of dicts that can
122
125
  be used to convert into a dataframe, using either pandas or polars.
@@ -124,20 +127,22 @@ def unpack_table_data(json_data: dict) -> list[dict]:
124
127
 
125
128
  dimensions = json_data["dimension"]
126
129
  dimension_labels = {}
127
-
130
+
128
131
  # Go over each dimension by id, according to the spec it is an ordered list of the dimensions
129
132
  for dim_id in json_data["id"]:
130
-
131
133
  dimension = dimensions[dim_id]
132
134
  label = dimension["label"]
133
135
  category_labels = dimension["category"]["label"]
134
136
 
135
- show = dimension.get("extension", {}).get("show")
137
+ if not show:
138
+ show_local = dimension.get("extension", {}).get("show")
139
+ else:
140
+ show_local = show
136
141
  # If the dimension has extension data along with a key for show, use
137
142
  # that to determine the values shown in the output
138
- match show:
143
+ match show_local:
139
144
  case "code_value":
140
- values = [f"{k} {v}" for k, v in category_labels.items()]
145
+ values = [f"{k}: {v}" for k, v in category_labels.items()]
141
146
  case "code":
142
147
  values = list(category_labels.keys())
143
148
  case "value":
@@ -155,6 +160,8 @@ def unpack_table_data(json_data: dict) -> list[dict]:
155
160
 
156
161
  # The result is a list of dicts with the dimension as key and product of the category labels for values, with the value as "value" for each row
157
162
  return [
158
- {**dict(zip(dimension_labels.keys(), combo)), "value": val}
159
- for combo, val in zip(itertools.product(*dimension_labels.values()), json_data["value"])
160
- ]
163
+ {**dict(zip(dimension_labels.keys(), combo)), "value": val}
164
+ for combo, val in zip(
165
+ itertools.product(*dimension_labels.values()), json_data["value"]
166
+ )
167
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.5.2"