pxwebpy 0.3.2__tar.gz → 0.4.0__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.
- pxwebpy-0.4.0/.github/workflows/ci.yml +45 -0
- pxwebpy-0.4.0/.github/workflows/release.yml +28 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/.gitignore +4 -1
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/PKG-INFO +6 -6
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/examples/example.py +5 -3
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/pyproject.toml +22 -17
- pxwebpy-0.4.0/src/pxwebpy/__init__.py +3 -0
- pxwebpy-0.4.0/src/pxwebpy/_api.py +22 -0
- pxwebpy-0.4.0/src/pxwebpy/_data.py +168 -0
- pxwebpy-0.4.0/src/pxwebpy/_version.py +1 -0
- pxwebpy-0.4.0/src/pxwebpy/table.py +218 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/test_table.py +37 -26
- pxwebpy-0.4.0/uv.lock +615 -0
- pxwebpy-0.3.2/.github/workflows/ci.yml +0 -62
- pxwebpy-0.3.2/.github/workflows/release.yml +0 -31
- pxwebpy-0.3.2/src/pxwebpy/table.py +0 -336
- pxwebpy-0.3.2/uv.lock +0 -945
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/LICENSE +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/README.md +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/examples/example_query.json +0 -0
- /pxwebpy-0.3.2/src/pxwebpy/__init__.py → /pxwebpy-0.4.0/src/pxwebpy/py.typed +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/invalid_query.json +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/mock/response_fi.json +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/mock/response_gl.json +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/mock/response_no.json +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/mock/response_table_variables.json +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/mock/result_fi.json +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/mock/result_gl.json +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/mock/result_no.json +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/queries.json +0 -0
- {pxwebpy-0.3.2 → pxwebpy-0.4.0}/tests/valid_query.json +0 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
name: ci
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: ["main"]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: ["main"]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
build:
|
|
11
|
+
name: ${{ matrix.os }} python-${{ matrix.python-version }}
|
|
12
|
+
|
|
13
|
+
strategy:
|
|
14
|
+
matrix:
|
|
15
|
+
os:
|
|
16
|
+
- ubuntu-latest
|
|
17
|
+
- windows-latest
|
|
18
|
+
- macos-latest
|
|
19
|
+
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
|
|
20
|
+
fail-fast: false
|
|
21
|
+
|
|
22
|
+
runs-on: ${{ matrix.os }}
|
|
23
|
+
|
|
24
|
+
steps:
|
|
25
|
+
- uses: actions/checkout@v4
|
|
26
|
+
with:
|
|
27
|
+
fetch-depth: 0
|
|
28
|
+
|
|
29
|
+
- name: Install uv
|
|
30
|
+
uses: astral-sh/setup-uv@v4
|
|
31
|
+
with:
|
|
32
|
+
version: "0.5.16"
|
|
33
|
+
enable-cache: true
|
|
34
|
+
cache-dependency-glob: "uv.lock"
|
|
35
|
+
|
|
36
|
+
- name: Set up Python ${{ matrix.python-version }}
|
|
37
|
+
run: uv python install ${{ matrix.python-version }}
|
|
38
|
+
|
|
39
|
+
- name: Install the project
|
|
40
|
+
run: uv sync --all-extras --dev
|
|
41
|
+
|
|
42
|
+
- name: Run tests & build
|
|
43
|
+
run: |
|
|
44
|
+
uv run pytest tests
|
|
45
|
+
uv build
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
name: release
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
build-release:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
environment: release
|
|
11
|
+
permissions:
|
|
12
|
+
id-token: write
|
|
13
|
+
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
with:
|
|
17
|
+
fetch-depth: 0
|
|
18
|
+
|
|
19
|
+
- name: Install uv
|
|
20
|
+
uses: astral-sh/setup-uv@v4
|
|
21
|
+
with:
|
|
22
|
+
version: "0.5.16"
|
|
23
|
+
|
|
24
|
+
- name: Build for distribution
|
|
25
|
+
run: uv build
|
|
26
|
+
|
|
27
|
+
- name: Publish to PyPI
|
|
28
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: pxwebpy
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Get data from PxWeb API easily.
|
|
5
5
|
Project-URL: Repository, https://github.com/stefur/pxwebpy
|
|
6
|
-
Author-email:
|
|
6
|
+
Author-email: Stefan Furne <stefan@furne.net>
|
|
7
7
|
License-Expression: MIT
|
|
8
8
|
License-File: LICENSE
|
|
9
9
|
Keywords: dataframes,pandas,polars,pxweb,statistics
|
|
@@ -13,10 +13,10 @@ Classifier: Programming Language :: Python :: 3.9
|
|
|
13
13
|
Classifier: Programming Language :: Python :: 3.10
|
|
14
14
|
Classifier: Programming Language :: Python :: 3.11
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
17
|
Requires-Python: >=3.9
|
|
17
|
-
Requires-Dist: requests>=2.
|
|
18
|
-
|
|
19
|
-
Requires-Dist: pytest>=8.2.0; extra == 'ci'
|
|
18
|
+
Requires-Dist: requests-cache>=1.2.1
|
|
19
|
+
Requires-Dist: requests>=2.32.3
|
|
20
20
|
Description-Content-Type: text/markdown
|
|
21
21
|
|
|
22
22
|
# pxwebpy
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
"""pxwebpy pulling some data to Pandas and Polars respectively"""
|
|
2
2
|
|
|
3
3
|
import pandas as pd
|
|
4
|
-
import polars as pl
|
|
5
|
-
|
|
4
|
+
import polars as pl
|
|
5
|
+
|
|
6
|
+
from pxwebpy import PxTable
|
|
6
7
|
|
|
7
8
|
URL = "https://api.scb.se/OV0104/v1/doris/sv/ssd/START/HE/HE0110/HE0110A/SamForvInk1"
|
|
8
9
|
|
|
@@ -66,7 +67,8 @@ data3 = PxTable(URL, QUERY)
|
|
|
66
67
|
# We can fetch the data later on
|
|
67
68
|
data3.get_data()
|
|
68
69
|
|
|
69
|
-
# The get_data() function can be used to refresh data as well
|
|
70
|
+
# The get_data() function can be used to refresh data as well.
|
|
71
|
+
# Though data is cached for 10 minutes.
|
|
70
72
|
|
|
71
73
|
# Everytime get_data() is called, the field "fetched"
|
|
72
74
|
# is updated with a timestamp (datetime).
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "pxwebpy"
|
|
3
|
-
|
|
3
|
+
dynamic = ["version"]
|
|
4
4
|
description = "Get data from PxWeb API easily."
|
|
5
5
|
license = "MIT"
|
|
6
6
|
repository = "https://github.com/stefur/pxwebpy/"
|
|
@@ -12,12 +12,14 @@ classifiers = [
|
|
|
12
12
|
"Programming Language :: Python :: 3.10",
|
|
13
13
|
"Programming Language :: Python :: 3.11",
|
|
14
14
|
"Programming Language :: Python :: 3.12",
|
|
15
|
+
"Programming Language :: Python :: 3.13",
|
|
15
16
|
]
|
|
16
17
|
authors = [
|
|
17
|
-
{ name = "
|
|
18
|
+
{ name = "Stefan Furne", email = "stefan@furne.net" }
|
|
18
19
|
]
|
|
19
20
|
dependencies = [
|
|
20
|
-
"requests>=2.
|
|
21
|
+
"requests>=2.32.3",
|
|
22
|
+
"requests-cache>=1.2.1",
|
|
21
23
|
]
|
|
22
24
|
readme = "README.md"
|
|
23
25
|
requires-python = ">= 3.9"
|
|
@@ -25,21 +27,24 @@ requires-python = ">= 3.9"
|
|
|
25
27
|
[project.urls]
|
|
26
28
|
Repository = "https://github.com/stefur/pxwebpy"
|
|
27
29
|
|
|
28
|
-
[project.optional-dependencies]
|
|
29
|
-
ci = [
|
|
30
|
-
"pytest>=8.2.0",
|
|
31
|
-
]
|
|
32
|
-
|
|
33
30
|
[build-system]
|
|
34
|
-
requires = ["hatchling"]
|
|
31
|
+
requires = ["hatchling", "versioningit"]
|
|
35
32
|
build-backend = "hatchling.build"
|
|
36
33
|
|
|
37
|
-
[tool.
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
34
|
+
[tool.hatch.version]
|
|
35
|
+
source = "versioningit"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build]
|
|
38
|
+
artifacts = ["src/pxwebpy/_version.py"]
|
|
39
|
+
|
|
40
|
+
[tool.versioningit.write]
|
|
41
|
+
file = "src/pxwebpy/_version.py"
|
|
42
|
+
|
|
43
|
+
[dependency-groups]
|
|
44
|
+
dev = [
|
|
45
|
+
"pandas>=2.2.3",
|
|
46
|
+
"pandas-stubs>=2.2.2.240807",
|
|
47
|
+
"polars>=1.19.0",
|
|
48
|
+
"pytest>=8.3.4",
|
|
49
|
+
"types-requests>=2.32.0.20241016",
|
|
45
50
|
]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
import requests
|
|
4
|
+
from requests_cache import CachedSession
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def call(
|
|
8
|
+
session: CachedSession, timeout: int, url: str, query: Optional[dict] = None
|
|
9
|
+
) -> dict:
|
|
10
|
+
"""Call the API using the table URL and optional query"""
|
|
11
|
+
|
|
12
|
+
if query:
|
|
13
|
+
response = session.post(url, json=query, timeout=timeout)
|
|
14
|
+
else:
|
|
15
|
+
response = session.get(url, timeout=timeout)
|
|
16
|
+
|
|
17
|
+
if response.ok:
|
|
18
|
+
return response.json()
|
|
19
|
+
else:
|
|
20
|
+
raise requests.exceptions.HTTPError(
|
|
21
|
+
f"Error {response.status_code}: {response.reason}"
|
|
22
|
+
)
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import itertools
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def build_query(json_data: dict, query: dict) -> list:
|
|
5
|
+
"""Build an API query for a table"""
|
|
6
|
+
# Set up a dictionary to use for conversion between value and valueText
|
|
7
|
+
value_mapping = {}
|
|
8
|
+
|
|
9
|
+
for variable in json_data["variables"]:
|
|
10
|
+
text = variable["text"]
|
|
11
|
+
code = variable["code"]
|
|
12
|
+
value_texts = variable["valueTexts"]
|
|
13
|
+
values = variable["values"]
|
|
14
|
+
|
|
15
|
+
value_mapping[(code, text)] = {
|
|
16
|
+
"values": [
|
|
17
|
+
(value, value_text) for value, value_text in zip(values, value_texts)
|
|
18
|
+
],
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
result = []
|
|
22
|
+
|
|
23
|
+
for variable, values in query.items():
|
|
24
|
+
# Go over the selected variables, a match can be either code or text
|
|
25
|
+
matching_variable = next(
|
|
26
|
+
(code_text for code_text in value_mapping.keys() if variable in code_text),
|
|
27
|
+
None,
|
|
28
|
+
)
|
|
29
|
+
# Extract the code from the matching variable tuple
|
|
30
|
+
if matching_variable:
|
|
31
|
+
code = matching_variable[0]
|
|
32
|
+
|
|
33
|
+
# Handle wild card filtering
|
|
34
|
+
if "*" in values[0] and len(values) == 1:
|
|
35
|
+
result.append(
|
|
36
|
+
{
|
|
37
|
+
"code": code,
|
|
38
|
+
"selection": {
|
|
39
|
+
"filter": "all",
|
|
40
|
+
"values": values,
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
)
|
|
44
|
+
else:
|
|
45
|
+
# Select the values to map
|
|
46
|
+
value_tuples = value_mapping[matching_variable]["values"]
|
|
47
|
+
|
|
48
|
+
converted_values = []
|
|
49
|
+
|
|
50
|
+
# Go over the values and convert any provided valueTexts to values
|
|
51
|
+
for value in values:
|
|
52
|
+
# Try to find a match within either code
|
|
53
|
+
matching_value = next(
|
|
54
|
+
(
|
|
55
|
+
value_valuetext
|
|
56
|
+
for value_valuetext in value_tuples
|
|
57
|
+
if value in value_valuetext
|
|
58
|
+
),
|
|
59
|
+
None,
|
|
60
|
+
)
|
|
61
|
+
# If we find a match we append the value that the API wants
|
|
62
|
+
if matching_value:
|
|
63
|
+
converted_values.append(matching_value[0])
|
|
64
|
+
else:
|
|
65
|
+
# Raise an error if the value is not found in the variable
|
|
66
|
+
raise KeyError(
|
|
67
|
+
f"Value '{value}' not found in variable '{variable}'."
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
result.append(
|
|
71
|
+
{
|
|
72
|
+
"code": code,
|
|
73
|
+
"selection": {
|
|
74
|
+
"filter": "item",
|
|
75
|
+
"values": converted_values,
|
|
76
|
+
},
|
|
77
|
+
}
|
|
78
|
+
)
|
|
79
|
+
else:
|
|
80
|
+
raise KeyError(f"Variable '{variable}' not found in table.")
|
|
81
|
+
|
|
82
|
+
return result
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def unpack_table_variables(json_data: dict) -> dict:
|
|
86
|
+
"""Takes a JSON response of variables and turns it into a more readable format"""
|
|
87
|
+
try:
|
|
88
|
+
result = {}
|
|
89
|
+
|
|
90
|
+
for var in json_data["variables"]:
|
|
91
|
+
code = var.get("code")
|
|
92
|
+
value_texts = var.get("valueTexts")
|
|
93
|
+
values = var.get("values")
|
|
94
|
+
elimination = var.get("elimination", False)
|
|
95
|
+
|
|
96
|
+
# Print values as tuples if the valueText is different from the value
|
|
97
|
+
result[code] = {
|
|
98
|
+
"values": [
|
|
99
|
+
v if v == vt else (v, vt) for v, vt in zip(values, value_texts)
|
|
100
|
+
],
|
|
101
|
+
# Flip the logic :)
|
|
102
|
+
"mandatory": not elimination,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return result
|
|
106
|
+
except KeyError as err:
|
|
107
|
+
raise KeyError(f"Failed to unpack, missing key: {err}") from None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def unpack_table_data(json_data: dict) -> list[dict]:
|
|
111
|
+
"""
|
|
112
|
+
Takes json-stat2 data and turns it into a list of dicts that can
|
|
113
|
+
be used to convert into a dataframe, using either pandas or polars.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
dimension_categories = {}
|
|
117
|
+
|
|
118
|
+
# Go over each dimension
|
|
119
|
+
for dim in json_data["dimension"]:
|
|
120
|
+
# If the dimension has extension data along with a key for show, use
|
|
121
|
+
# that to determine the values shown in the output
|
|
122
|
+
try:
|
|
123
|
+
show_value = json_data["dimension"][dim]["extension"]["show"]
|
|
124
|
+
|
|
125
|
+
if show_value == "code_value":
|
|
126
|
+
values = [
|
|
127
|
+
" ".join([str(k), str(v)])
|
|
128
|
+
for k, v in json_data["dimension"][dim]["category"]["label"].items()
|
|
129
|
+
]
|
|
130
|
+
|
|
131
|
+
elif show_value == "code":
|
|
132
|
+
values = [
|
|
133
|
+
str(k)
|
|
134
|
+
for k in json_data["dimension"][dim]["category"]["label"].keys()
|
|
135
|
+
]
|
|
136
|
+
|
|
137
|
+
elif show_value == "value":
|
|
138
|
+
values = [
|
|
139
|
+
str(v)
|
|
140
|
+
for v in json_data["dimension"][dim]["category"]["label"].values()
|
|
141
|
+
]
|
|
142
|
+
# Raise an error if we hit some value in the show key that we don't know how to handle
|
|
143
|
+
|
|
144
|
+
else:
|
|
145
|
+
raise ValueError(
|
|
146
|
+
f"""Unexpected show value. Expected "code", "value" or "code_value", got: {show_value}"""
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# If there's no show key at all we default to using the label values
|
|
150
|
+
except KeyError:
|
|
151
|
+
values = [
|
|
152
|
+
str(v)
|
|
153
|
+
for v in json_data["dimension"][dim]["category"]["label"].values()
|
|
154
|
+
]
|
|
155
|
+
|
|
156
|
+
dimension_categories.update({json_data["dimension"][dim]["label"]: values})
|
|
157
|
+
|
|
158
|
+
# The result is a list of dicts with the dimension as key and product of the category labels for values
|
|
159
|
+
result = [
|
|
160
|
+
dict(zip(dimension_categories.keys(), x))
|
|
161
|
+
for x in itertools.product(*dimension_categories.values())
|
|
162
|
+
]
|
|
163
|
+
|
|
164
|
+
# Finally add the value for each dict representing a row
|
|
165
|
+
for value, dict_row in zip(json_data["value"], result):
|
|
166
|
+
dict_row["value"] = value
|
|
167
|
+
|
|
168
|
+
return result
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.4.0"
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Make fetching data from PxWeb a bit easier"""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from tempfile import gettempdir
|
|
7
|
+
from typing import Optional, Union
|
|
8
|
+
|
|
9
|
+
from requests_cache import CachedSession
|
|
10
|
+
|
|
11
|
+
from . import _api, _data
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PxTable:
|
|
15
|
+
"""
|
|
16
|
+
A table object to retrieve data from the PxWeb API.
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
url : str
|
|
21
|
+
The PxWeb API URL for the table to query.
|
|
22
|
+
query : str | dict | None
|
|
23
|
+
The query must be a JSON structure, supplied either as a dict, string or a string representing a path to a file.
|
|
24
|
+
timeout : int
|
|
25
|
+
The timeout (in seconds) for the query sent to the API. This defines the maximum time the client will wait
|
|
26
|
+
for the server to respond before a a `ReadTimeout` exception will be raised. Defaults to 30 seconds.
|
|
27
|
+
|
|
28
|
+
Example
|
|
29
|
+
--------
|
|
30
|
+
Fetching data with a very simple query and turning it into a Pandas dataframe:
|
|
31
|
+
|
|
32
|
+
>>> from pxwebpy import PxTable
|
|
33
|
+
>>> import pandas as pd
|
|
34
|
+
|
|
35
|
+
>>> tbl = PxTable(url="https://api.scb.se/OV0104/v1/doris/sv/ssd/START/HE/HE0110/HE0110A/SamForvInk1")
|
|
36
|
+
|
|
37
|
+
>>> tbl.create_query({"region": ["17*"], "år": ["*"], "ålder": ["totalt 16+ år"], "ContentsCode": ["Medianinkomst, tkr"]})
|
|
38
|
+
|
|
39
|
+
>>> tbl.get_data()
|
|
40
|
+
|
|
41
|
+
>>> print(tbl)
|
|
42
|
+
|
|
43
|
+
PxTable(url='https://api.scb.se/OV0104/v1/doris/sv/ssd/START/HE/HE0110/HE0110A/SamForvInk1',
|
|
44
|
+
query={'query': [{'code': 'Region', 'selection': {'filter': 'all', 'values': ['17*']}}, {'code': 'Tid', 'selection': {'filter': 'all', 'values': ['*']}}, {'code': 'Alder', 'selection': {'filter': 'item', 'values': ['tot16+']}}, {'code': 'ContentsCode', 'selection': {'filter': 'item', 'values': ['HE0110J8']}}], 'response': {'format': 'json-stat2'}},
|
|
45
|
+
metadata={'label': 'Sammanräknad förvärvsinkomst, medianinkomst för boende i Sverige hela året, tkr efter region, ålder, tabellinnehåll och år', 'note': None, 'source': 'SCB', 'updated': '2024-01-12T05:52:00Z'},
|
|
46
|
+
fetched=2024-10-11 20:13:35.475254,
|
|
47
|
+
dataset=[{'region': '17 Värmlands län', 'ålder': 'totalt 16+ år', 'tabellinnehåll': 'Medianinkomst, tkr', 'år': '1999', 'value': 153.4}, {'region': '17 Värmlands län', 'ålder': 'totalt 16+ år', 'tabellinnehåll': 'Medianinkomst, tkr', 'år': '2000', 'value': 157.7}, {'region': '17 Värmlands län', 'ålder': 'totalt 16+ år', 'tabellinnehåll': 'Medianinkomst, tkr', 'år': '2001', 'value': 163.2}, ...
|
|
48
|
+
|
|
49
|
+
>>> df = pd.DataFrame(tbl.dataset)
|
|
50
|
+
>>> print(df)
|
|
51
|
+
|
|
52
|
+
region ålder tabellinnehåll år value
|
|
53
|
+
0 17 Värmlands län totalt 16+ år Medianinkomst, tkr 1999 153.4
|
|
54
|
+
1 17 Värmlands län totalt 16+ år Medianinkomst, tkr 2000 157.7
|
|
55
|
+
2 17 Värmlands län totalt 16+ år Medianinkomst, tkr 2001 163.2
|
|
56
|
+
3 17 Värmlands län totalt 16+ år Medianinkomst, tkr 2002 170.0
|
|
57
|
+
4 17 Värmlands län totalt 16+ år Medianinkomst, tkr 2003 176.8
|
|
58
|
+
.. ... ... ... ... ...
|
|
59
|
+
403 1785 Säffle totalt 16+ år Medianinkomst, tkr 2018 239.8
|
|
60
|
+
404 1785 Säffle totalt 16+ år Medianinkomst, tkr 2019 246.3
|
|
61
|
+
405 1785 Säffle totalt 16+ år Medianinkomst, tkr 2020 250.1
|
|
62
|
+
406 1785 Säffle totalt 16+ år Medianinkomst, tkr 2021 255.5
|
|
63
|
+
407 1785 Säffle totalt 16+ år Medianinkomst, tkr 2022 273.4
|
|
64
|
+
|
|
65
|
+
[408 rows x 5 columns]
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
_tmp_dir = gettempdir()
|
|
69
|
+
_cache = Path(_tmp_dir) / "pxwebpy_cache"
|
|
70
|
+
|
|
71
|
+
def __init__(self, url, query=None, timeout=30) -> None:
|
|
72
|
+
self.url: str = url
|
|
73
|
+
self.query = query
|
|
74
|
+
self.timeout: int = timeout
|
|
75
|
+
self.dataset: Optional[list[dict]] = None
|
|
76
|
+
self.metadata: dict = {
|
|
77
|
+
key: None for key in ["label", "note", "source", "updated"]
|
|
78
|
+
}
|
|
79
|
+
self.fetched: Optional[datetime] = None
|
|
80
|
+
self.__session = CachedSession(cache_name=self._cache, ttl=600)
|
|
81
|
+
|
|
82
|
+
def __repr__(self) -> str:
|
|
83
|
+
return f"""PxTable(url='{self.url}',
|
|
84
|
+
query={self.query},
|
|
85
|
+
timeout={self.timeout},
|
|
86
|
+
metadata={self.metadata},
|
|
87
|
+
fetched={self.fetched},
|
|
88
|
+
dataset={self.dataset})"""
|
|
89
|
+
|
|
90
|
+
def get_data(self) -> None:
|
|
91
|
+
"""Get data from the API, modifying the object in-place."""
|
|
92
|
+
|
|
93
|
+
json_data = _api.call(
|
|
94
|
+
session=self.__session, url=self.url, query=self.query, timeout=self.timeout
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
self.dataset = _data.unpack_table_data(json_data)
|
|
98
|
+
|
|
99
|
+
metadata_keys = ["label", "note", "source", "updated"]
|
|
100
|
+
|
|
101
|
+
self.metadata = self.metadata = {
|
|
102
|
+
key: json_data.get(key) for key in metadata_keys
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
self.fetched = datetime.now()
|
|
106
|
+
|
|
107
|
+
def __is_path(self, query: str) -> bool:
|
|
108
|
+
"""Check if query is a path or not"""
|
|
109
|
+
try:
|
|
110
|
+
return Path(query).is_file()
|
|
111
|
+
except OSError:
|
|
112
|
+
return False
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def query(self) -> Optional[dict]:
|
|
116
|
+
"""
|
|
117
|
+
Getter for the query.
|
|
118
|
+
"""
|
|
119
|
+
return self.__query
|
|
120
|
+
|
|
121
|
+
@query.setter
|
|
122
|
+
def query(
|
|
123
|
+
self,
|
|
124
|
+
query: Optional[
|
|
125
|
+
Union[
|
|
126
|
+
str,
|
|
127
|
+
dict,
|
|
128
|
+
]
|
|
129
|
+
],
|
|
130
|
+
) -> None:
|
|
131
|
+
"""
|
|
132
|
+
Set the JSON query from a string representing a path or a JSON structure that is either a string or a dict.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
if query is not None and not isinstance(query, (str, dict)):
|
|
136
|
+
raise TypeError(
|
|
137
|
+
f"""Invalid input for `query`.
|
|
138
|
+
Expected `str`, `dict` or `None`, got {type(query)!r}."""
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
if isinstance(query, dict):
|
|
142
|
+
try:
|
|
143
|
+
if (response_format := query["response"]["format"]) != "json-stat2":
|
|
144
|
+
raise TypeError(
|
|
145
|
+
f"""Response format must be 'json-stat2', \
|
|
146
|
+
got '{response_format}'."""
|
|
147
|
+
)
|
|
148
|
+
except KeyError as err:
|
|
149
|
+
raise KeyError(f"Missing key: {err}") from err
|
|
150
|
+
|
|
151
|
+
if isinstance(query, str):
|
|
152
|
+
if self.__is_path(query):
|
|
153
|
+
with open(query, mode="r", encoding="utf-8") as read_file:
|
|
154
|
+
self.__query = json.load(read_file)
|
|
155
|
+
else:
|
|
156
|
+
try:
|
|
157
|
+
self.__query = json.loads(query)
|
|
158
|
+
except json.JSONDecodeError as err:
|
|
159
|
+
raise ValueError(
|
|
160
|
+
"Provided value could not be decoded as JSON."
|
|
161
|
+
) from err
|
|
162
|
+
else:
|
|
163
|
+
self.__query = query
|
|
164
|
+
|
|
165
|
+
def create_query(self, query_struct: dict[str, list[str]]) -> None:
|
|
166
|
+
"""
|
|
167
|
+
This function will convert any textual display names of variables and value into the identifier code and values
|
|
168
|
+
that the API expects.
|
|
169
|
+
The creation of a query modifies the object in-place.
|
|
170
|
+
|
|
171
|
+
Parameters
|
|
172
|
+
----------
|
|
173
|
+
query : dict[str, list[str]]
|
|
174
|
+
A dict where each key represents a variable name and its values is a list of values to filter.
|
|
175
|
+
|
|
176
|
+
Example
|
|
177
|
+
--------
|
|
178
|
+
Creating a simple query:
|
|
179
|
+
|
|
180
|
+
>>> tbl = PxTable(url="https://api.scb.se/OV0104/v1/doris/sv/ssd/START/ME/ME0104/ME0104D/ME0104T4")
|
|
181
|
+
|
|
182
|
+
>>> tbl.create_query({"valår": ["*"], "region": ["Riket"]})
|
|
183
|
+
|
|
184
|
+
>>> tbl.query
|
|
185
|
+
|
|
186
|
+
{'query': [{'code': 'Tid', 'selection': {'filter': 'all', 'values': ['*']}},
|
|
187
|
+
{'code': 'Region', 'selection': {'filter': 'item', 'values': ['00']}}],
|
|
188
|
+
'response': {'format': 'json-stat2'}}
|
|
189
|
+
"""
|
|
190
|
+
|
|
191
|
+
# Check that the query structure holds up
|
|
192
|
+
for key, value in query_struct.items():
|
|
193
|
+
if not isinstance(key, str):
|
|
194
|
+
raise ValueError("Keys in the query must be `string`.")
|
|
195
|
+
|
|
196
|
+
if not isinstance(value, list) or not all(
|
|
197
|
+
isinstance(v, str) for v in value
|
|
198
|
+
):
|
|
199
|
+
raise ValueError("Values in the query must be a `list` of `strings`.")
|
|
200
|
+
|
|
201
|
+
# Get the table variables and values
|
|
202
|
+
json_data = _api.call(
|
|
203
|
+
session=self.__session, url=self.url, timeout=self.timeout
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
query = _data.build_query(json_data=json_data, query=query_struct)
|
|
207
|
+
|
|
208
|
+
self.query = {"query": query, "response": {"format": "json-stat2"}}
|
|
209
|
+
|
|
210
|
+
def get_table_variables(self) -> Union[dict, None]:
|
|
211
|
+
"""
|
|
212
|
+
Returns a dict of variables and the respective values with texts from the table.
|
|
213
|
+
"""
|
|
214
|
+
json_data = _api.call(
|
|
215
|
+
session=self.__session, url=self.url, timeout=self.timeout
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
return _data.unpack_table_variables(json_data)
|