├── .github
└── workflows
│ ├── deploy-demo.yml
│ ├── publish.yml
│ └── test.yml
├── .gitignore
├── LICENSE
├── README.md
├── datasette_json_html
└── __init__.py
├── setup.py
└── tests
├── __init__.py
├── test_datasette_json_html.py
└── test_urllib_quote_plus.py
/.github/workflows/deploy-demo.yml:
--------------------------------------------------------------------------------
1 | name: Deploy demo
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 |
8 | jobs:
9 | deploy:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v2
13 | - name: Set up Python
14 | uses: actions/setup-python@v2
15 | with:
16 | python-version: 3.8
17 | - uses: actions/cache@v2
18 | name: Configure pip caching
19 | with:
20 | path: ~/.cache/pip
21 | key: ${{ runner.os }}-pip-
22 | restore-keys: |
23 | ${{ runner.os }}-pip-
24 | - name: Install Python dependencies
25 | run: pip install sqlite-utils datasette
26 | - name: Build database
27 | run: |-
28 | echo '[
29 | {
30 | "package": "datasette-cluster-map",
31 | "url": "https://github.com/simonw/datasette-cluster-map"
32 | },
33 | {
34 | "package": "datasette-jellyfish",
35 | "url": "https://github.com/simonw/datasette-jellyfish"
36 | },
37 | {
38 | "package": "datasette-jq",
39 | "url": "https://github.com/simonw/datasette-jq"
40 | },
41 | {
42 | "package": "datasette-json-html",
43 | "url": "https://github.com/simonw/datasette-json-html"
44 | },
45 | {
46 | "package": "datasette-pretty-json",
47 | "url": "https://github.com/simonw/datasette-pretty-json"
48 | },
49 | {
50 | "package": "datasette-vega",
51 | "url": "https://github.com/simonw/datasette-vega"
52 | }
53 | ]' | sqlite-utils insert demo.db packages - --pk=package
54 | - name: Create Metadata
55 | run: |
56 | echo '{
57 | "title": "datasette-json-html demo",
58 | "about": "simonw/datasette-json-html",
59 | "about_url": "https://github.com/simonw/datasette-json-html"
60 | }' > metadata.json
61 | - name: Set up Cloud Run
62 | uses: google-github-actions/setup-gcloud@v0
63 | with:
64 | version: '275.0.0'
65 | service_account_email: ${{ secrets.GCP_SA_EMAIL }}
66 | service_account_key: ${{ secrets.GCP_SA_KEY }}
67 | - name: Deploy to Cloud Run
68 | run: |-
69 | gcloud config set run/region us-central1
70 | gcloud config set project datasette-222320
71 | datasette publish cloudrun demo.db \
72 | -m metadata.json \
73 | --install=https://github.com/simonw/datasette-json-html/archive/$GITHUB_SHA.zip \
74 | --service datasette-json-html-demo
75 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish Python Package
2 |
3 | on:
4 | release:
5 | types: [created]
6 |
7 | jobs:
8 | test:
9 | runs-on: ubuntu-latest
10 | strategy:
11 | matrix:
12 | python-version: ["3.6", "3.7", "3.8", "3.9", "3.10"]
13 | steps:
14 | - uses: actions/checkout@v2
15 | - name: Set up Python ${{ matrix.python-version }}
16 | uses: actions/setup-python@v2
17 | with:
18 | python-version: ${{ matrix.python-version }}
19 | - uses: actions/cache@v2
20 | name: Configure pip caching
21 | with:
22 | path: ~/.cache/pip
23 | key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }}
24 | restore-keys: |
25 | ${{ runner.os }}-pip-
26 | - name: Install dependencies
27 | run: |
28 | pip install -e '.[test]'
29 | - name: Run tests
30 | run: |
31 | pytest
32 | deploy:
33 | runs-on: ubuntu-latest
34 | needs: [test]
35 | steps:
36 | - uses: actions/checkout@v2
37 | - name: Set up Python
38 | uses: actions/setup-python@v2
39 | with:
40 | python-version: "3.10"
41 | - uses: actions/cache@v2
42 | name: Configure pip caching
43 | with:
44 | path: ~/.cache/pip
45 | key: ${{ runner.os }}-publish-pip-${{ hashFiles('**/setup.py') }}
46 | restore-keys: |
47 | ${{ runner.os }}-publish-pip-
48 | - name: Install dependencies
49 | run: |
50 | pip install setuptools wheel twine build
51 | - name: Publish
52 | env:
53 | TWINE_USERNAME: __token__
54 | TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
55 | run: |
56 | python -m build
57 | twine upload dist/*
58 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 |
3 | on: [push]
4 |
5 | jobs:
6 | test:
7 | runs-on: ubuntu-latest
8 | strategy:
9 | matrix:
10 | python-version: ["3.6", "3.7", "3.8", "3.9", "3.10"]
11 | steps:
12 | - uses: actions/checkout@v2
13 | - name: Set up Python ${{ matrix.python-version }}
14 | uses: actions/setup-python@v2
15 | with:
16 | python-version: ${{ matrix.python-version }}
17 | - uses: actions/cache@v2
18 | name: Configure pip caching
19 | with:
20 | path: ~/.cache/pip
21 | key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }}
22 | restore-keys: |
23 | ${{ runner.os }}-pip-
24 | - name: Install dependencies
25 | run: |
26 | pip install -e '.[test]'
27 | - name: Run tests
28 | run: |
29 | pytest
30 |
31 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .venv
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 | venv
6 | .eggs
7 | .pytest_cache
8 | *.egg-info
9 | .DS_Store
10 | .vscode
11 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # datasette-json-html
2 |
3 | [](https://pypi.org/project/datasette-json-html/)
4 | [](https://github.com/simonw/datasette-json-html/releases)
5 | [](https://github.com/simonw/datasette-remote-metadata/actions?query=workflow%3ATest)
6 | [](https://github.com/simonw/datasette-json-html/blob/main/LICENSE)
7 |
8 | Datasette plugin for rendering HTML based on JSON values, using the [render_cell plugin hook](https://docs.datasette.io/en/stable/plugin_hooks.html#render-cell-value-column-table-database-datasette).
9 |
10 | This plugin looks for cell values that match a very specific JSON format and converts them into HTML when they are rendered by the Datasette interface.
11 |
12 | ## Links
13 |
14 | {
15 | "href": "https://simonwillison.net/",
16 | "label": "Simon Willison"
17 | }
18 |
19 | Will be rendered as an `` link:
20 |
21 | Simon Willison
22 |
23 | You can set a tooltip on the link using a `"title"` key:
24 |
25 |
26 | {
27 | "href": "https://simonwillison.net/",
28 | "label": "Simon Willison",
29 | "title": "My blog"
30 | }
31 |
32 | Produces:
33 |
34 | Simon Willison
35 |
36 | You can also include a description, which will be displayed below the link. If descriptions include newlines they will be converted to ` ` elements:
37 |
38 | select json_object(
39 | "href", "https://simonwillison.net/",
40 | "label", "Simon Willison",
41 | "description", "This can contain" || x'0a' || "newlines"
42 | )
43 |
44 | Produces:
45 |
46 | Simon Willison This can contain newlines
47 |
48 | * [Literal JSON link demo](https://datasette-json-html.datasette.io/demo?sql=select+%27%7B%0D%0A++++%22href%22%3A+%22https%3A%2F%2Fsimonwillison.net%2F%22%2C%0D%0A++++%22label%22%3A+%22Simon+Willison%22%2C%0D%0A++++%22title%22%3A+%22My+blog%22%0D%0A%7D%27)
49 |
50 | ## List of links
51 |
52 | [
53 | {
54 | "href": "https://simonwillison.net/",
55 | "label": "Simon Willison"
56 | },
57 | {
58 | "href": "https://github.com/simonw/datasette",
59 | "label": "Datasette"
60 | }
61 | ]
62 |
63 | Will be rendered as a comma-separated list of `` links:
64 |
65 | Simon Willison,
66 | Datasette
67 |
68 | The `href` property must begin with `https://` or `http://` or `/`, to avoid potential XSS injection attacks (for example URLs that begin with `javascript:`).
69 |
70 | Lists of links cannot include `"description"` keys.
71 |
72 | * [Literal list of links demo](https://datasette-json-html.datasette.io/demo?sql=select+%27%5B%0D%0A++++%7B%0D%0A++++++++%22href%22%3A+%22https%3A%2F%2Fsimonwillison.net%2F%22%2C%0D%0A++++++++%22label%22%3A+%22Simon+Willison%22%0D%0A++++%7D%2C%0D%0A++++%7B%0D%0A++++++++%22href%22%3A+%22https%3A%2F%2Fgithub.com%2Fsimonw%2Fdatasette%22%2C%0D%0A++++++++%22label%22%3A+%22Datasette%22%0D%0A++++%7D%0D%0A%5D%27)
73 |
74 | ## Images
75 |
76 | The image tag is more complex. The most basic version looks like this:
77 |
78 | {
79 | "img_src": "https://placekitten.com/200/300"
80 | }
81 |
82 | This will render as:
83 |
84 |
85 |
86 | But you can also include one or more of `alt`, `caption`, `width` and `href`.
87 |
88 | If you include width or alt, they will be added as attributes:
89 |
90 | {
91 | "img_src": "https://placekitten.com/200/300",
92 | "alt": "Kitten",
93 | "width": 200
94 | }
95 |
96 | Produces:
97 |
98 |
100 |
101 | * [Literal image demo](https://datasette-json-html.datasette.io/demo?sql=select+%27%7B%0D%0A++++%22img_src%22%3A+%22https%3A%2F%2Fplacekitten.com%2F200%2F300%22%2C%0D%0A++++%22alt%22%3A+%22Kitten%22%2C%0D%0A++++%22width%22%3A+200%0D%0A%7D%27)
102 |
103 | The `href` key will cause the image to be wrapped in a link:
104 |
105 | {
106 | "img_src": "https://placekitten.com/200/300",
107 | "href": "http://www.example.com"
108 | }
109 |
110 | Produces:
111 |
112 |
113 |
114 |
115 |
116 | The `caption` key wraps everything in a fancy figure/figcaption block:
117 |
118 | {
119 | "img_src": "https://placekitten.com/200/300",
120 | "caption": "Kitten caption"
121 | }
122 |
123 | Produces:
124 |
125 |
126 |
127 | Kitten caption
128 |
129 |
130 | ## Preformatted text
131 |
132 | You can use `{"pre": "text"}` to render text in a `
164 |
165 | * [Preformatted text with JSON demo](https://datasette-json-html.datasette.io/demo?sql=select+%27%7B%0D%0A++++%22pre%22%3A+%7B%0D%0A++++++++%22this%22%3A+%7B%0D%0A++++++++++++%22object%22%3A+%5B%22is%22%2C+%22nested%22%5D%0D%0A++++++++%7D%0D%0A++++%7D%0D%0A%7D%27)
166 | * [Preformatted text demo showing the Mandelbrot Set](https://datasette-json-html.datasette.io/demo?sql=WITH+RECURSIVE%0D%0A++xaxis%28x%29+AS+%28VALUES%28-2.0%29+UNION+ALL+SELECT+x%2B0.05+FROM+xaxis+WHERE+x%3C1.2%29%2C%0D%0A++yaxis%28y%29+AS+%28VALUES%28-1.0%29+UNION+ALL+SELECT+y%2B0.1+FROM+yaxis+WHERE+y%3C1.0%29%2C%0D%0A++m%28iter%2C+cx%2C+cy%2C+x%2C+y%29+AS+%28%0D%0A++++SELECT+0%2C+x%2C+y%2C+0.0%2C+0.0+FROM+xaxis%2C+yaxis%0D%0A++++UNION+ALL%0D%0A++++SELECT+iter%2B1%2C+cx%2C+cy%2C+x*x-y*y+%2B+cx%2C+2.0*x*y+%2B+cy+FROM+m+%0D%0A+++++WHERE+%28x*x+%2B+y*y%29+%3C+4.0+AND+iter%3C28%0D%0A++%29%2C%0D%0A++m2%28iter%2C+cx%2C+cy%29+AS+%28%0D%0A++++SELECT+max%28iter%29%2C+cx%2C+cy+FROM+m+GROUP+BY+cx%2C+cy%0D%0A++%29%2C%0D%0A++a%28t%29+AS+%28%0D%0A++++SELECT+group_concat%28+substr%28%27+.%2B*%23%27%2C+1%2Bmin%28iter%2F7%2C4%29%2C+1%29%2C+%27%27%29+%0D%0A++++FROM+m2+GROUP+BY+cy%0D%0A++%29%0D%0ASELECT+json_object%28%27pre%27%2C+group_concat%28rtrim%28t%29%2Cx%270a%27%29%29+FROM+a%3B) using [this example](https://www.sqlite.org/lang_with.html#outlandish_recursive_query_examples) from the SQLite documentation
167 |
168 | ## Using these with SQLite JSON functions
169 |
170 | The most powerful way to make use of this plugin is in conjunction with SQLite's [JSON functions](https://www.sqlite.org/json1.html). For example:
171 |
172 | select json_object(
173 | "href", "https://simonwillison.net/",
174 | "label", "Simon Willison"
175 | );
176 |
177 | * [json_object() link demo](https://datasette-json-html.datasette.io/demo?sql=select+json_object%28%0D%0A++++%22href%22%2C+%22https%3A%2F%2Fsimonwillison.net%2F%22%2C%0D%0A++++%22label%22%2C+%22Simon+Willison%22%0D%0A%29%3B)
178 |
179 | You can use these functions to construct JSON objects that work with the plugin from data in a table:
180 |
181 | select id, json_object(
182 | "href", url, "label", text
183 | ) from mytable;
184 |
185 | * [Demo that builds links against a table](https://datasette-json-html.datasette.io/demo?sql=select+json_object%28%22href%22%2C+url%2C+%22label%22%2C+package%2C+%22title%22%2C+package+%7C%7C+%22+%22+%7C%7C+url%29+as+package+from+packages)
186 |
187 | The `json_group_array()` function is an aggregate function similar to `group_concat()` - it allows you to construct lists of JSON objects in conjunction with a `GROUP BY` clause.
188 |
189 | This means you can use it to construct dynamic lists of links, for example:
190 |
191 | select
192 | substr(package, 0, 12) as prefix,
193 | json_group_array(
194 | json_object(
195 | "href", url,
196 | "label", package
197 | )
198 | ) as package_links
199 | from packages
200 | group by prefix
201 |
202 | * [Demo of json_group_array()](https://datasette-json-html.datasette.io/demo?sql=select%0D%0A++++substr%28package%2C+0%2C+12%29+as+prefix%2C%0D%0A++++json_group_array%28%0D%0A++++++++json_object%28%0D%0A++++++++++++%22href%22%2C+url%2C%0D%0A++++++++++++%22label%22%2C+package%0D%0A++++++++%29%0D%0A++++%29+as+package_links%0D%0Afrom+packages%0D%0Agroup+by+prefix)
203 |
204 | ## The `urllib_quote_plus()` SQL function
205 |
206 | Since this plugin is designed to be used with SQL that constructs the underlying JSON structure, it is likely you will need to construct dynamic URLs from results returned by a SQL query.
207 |
208 | This plugin registers a custom SQLite function called `urllib_quote_plus()` to help you do that. It lets you use Python's [urllib.parse.quote\_plus() function](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus) from within a SQL query.
209 |
210 | Here's an example of how you might use it:
211 |
212 | select id, json_object(
213 | "href",
214 | "/mydatabase/other_table?_search=" || urllib_quote_plus(text),
215 | "label", text
216 | ) from mytable;
217 |
--------------------------------------------------------------------------------
/datasette_json_html/__init__.py:
--------------------------------------------------------------------------------
1 | from datasette import hookimpl
2 | import json
3 | import markupsafe
4 | import urllib
5 |
6 | valid_link_keys = (
7 | {"href", "label"},
8 | {"href", "label", "title"},
9 | {"href", "label", "title", "description"},
10 | {"href", "label", "description"},
11 | )
12 | valid_link_keys_no_description = ({"href", "label"}, {"href", "label", "title"})
13 |
14 | # Add urllib_quote_plus SQLite function`
15 | @hookimpl
16 | def prepare_connection(conn):
17 | conn.create_function("urllib_quote_plus", 1, urllib.parse.quote_plus)
18 |
19 |
20 | @hookimpl
21 | def render_cell(value):
22 | if not isinstance(value, str):
23 | return None
24 | stripped = value.strip()
25 | if not (
26 | (stripped.startswith("{") and stripped.endswith("}"))
27 | or (stripped.startswith("[") and stripped.endswith("]"))
28 | ):
29 | return None
30 | try:
31 | data = json.loads(value)
32 | except ValueError:
33 | return None
34 | if isinstance(data, list):
35 | # Handle list-of-links
36 | if len(data) == 0:
37 | return None
38 | if all(
39 | isinstance(item, dict)
40 | and set(item.keys()) in valid_link_keys_no_description
41 | and is_sensible_href(item["href"])
42 | for item in data
43 | ):
44 | bits = [build_link(item) for item in data]
45 | return markupsafe.Markup(", ".join(bits))
46 | else:
47 | return None
48 | keys = set(data.keys())
49 | if keys in valid_link_keys:
50 | # Render {"href": "...", "label": "..."} as link
51 | href = data["href"]
52 | if not is_sensible_href(href):
53 | return None
54 | return markupsafe.Markup(build_link(data))
55 | elif keys == {"pre"}:
56 | value = data["pre"]
57 | if isinstance(value, str):
58 | pre = value
59 | else:
60 | pre = json.dumps(value, indent=2)
61 | return markupsafe.Markup("