flask-spurl 0.1.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.
@@ -0,0 +1,220 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ *.lcov
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ # Pipfile.lock
97
+
98
+ # UV
99
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ uv.lock
103
+
104
+ # poetry
105
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
106
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
107
+ # commonly ignored for libraries.
108
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
109
+ # poetry.lock
110
+ # poetry.toml
111
+
112
+ # pdm
113
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
114
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
115
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
116
+ # pdm.lock
117
+ # pdm.toml
118
+ .pdm-python
119
+ .pdm-build/
120
+
121
+ # pixi
122
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
123
+ # pixi.lock
124
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
125
+ # in the .venv directory. It is recommended not to include this directory in version control.
126
+ .pixi/*
127
+ !.pixi/config.toml
128
+
129
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
130
+ __pypackages__/
131
+
132
+ # Celery stuff
133
+ celerybeat-schedule*
134
+ celerybeat.pid
135
+
136
+ # Redis
137
+ *.rdb
138
+ *.aof
139
+ *.pid
140
+
141
+ # RabbitMQ
142
+ mnesia/
143
+ rabbitmq/
144
+ rabbitmq-data/
145
+
146
+ # ActiveMQ
147
+ activemq-data/
148
+
149
+ # SageMath parsed files
150
+ *.sage.py
151
+
152
+ # Environments
153
+ .env
154
+ .envrc
155
+ .venv
156
+ env/
157
+ venv/
158
+ ENV/
159
+ env.bak/
160
+ venv.bak/
161
+
162
+ # Spyder project settings
163
+ .spyderproject
164
+ .spyproject
165
+
166
+ # Rope project settings
167
+ .ropeproject
168
+
169
+ # mkdocs documentation
170
+ /site
171
+
172
+ # mypy
173
+ .mypy_cache/
174
+ .dmypy.json
175
+ dmypy.json
176
+
177
+ # Pyre type checker
178
+ .pyre/
179
+
180
+ # pytype static type analyzer
181
+ .pytype/
182
+
183
+ # Cython debug symbols
184
+ cython_debug/
185
+
186
+ # PyCharm
187
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
188
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
189
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
190
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
191
+ # .idea/
192
+
193
+ # Abstra
194
+ # Abstra is an AI-powered process automation framework.
195
+ # Ignore directories containing user credentials, local state, and settings.
196
+ # Learn more at https://abstra.io/docs
197
+ .abstra/
198
+
199
+ # Visual Studio Code
200
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
201
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
202
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
203
+ # you could uncomment the following to ignore the entire vscode folder
204
+ # .vscode/
205
+ # Temporary file for partial code execution
206
+ tempCodeRunnerFile.py
207
+
208
+ # Ruff stuff:
209
+ .ruff_cache/
210
+
211
+ # PyPI configuration file
212
+ .pypirc
213
+
214
+ # Marimo
215
+ marimo/_static/
216
+ marimo/_lsp/
217
+ __marimo__/
218
+
219
+ # Streamlit
220
+ .streamlit/secrets.toml
@@ -0,0 +1,8 @@
1
+ Authors & Contributors
2
+ ======================
3
+
4
+ * Jamie Matthews
5
+ * Basil Shubin
6
+ * Ed Stafford
7
+ * Tom Christie
8
+ * Jakub Musil
@@ -0,0 +1,19 @@
1
+ Changes
2
+ -------
3
+
4
+ 0.1.0 (2026-11-29)
5
+ ~~~~~~~~~~~~~~~~~~
6
+
7
+ First release of flask-spurl, a port of django-spurl 0.6.9 to Flask.
8
+
9
+ * The ``{% spurl %}`` tag is replaced by the Jinja function ``spurl(...)``,
10
+ registered by the ``flask_spurl.Spurl`` extension. The same builder is
11
+ available in Python as ``flask_spurl.build_url``.
12
+ * Argument names and their meaning are kept. A repeated argument is
13
+ passed as a list, and ``as var`` is replaced by ``{% set %}``.
14
+ * Argument values are no longer rendered as templates. In django-spurl,
15
+ data passed to the tag could run template code (template injection).
16
+ * The ``autoescape`` argument is removed; escaping follows the Jinja
17
+ environment.
18
+ * Unknown arguments and calls without arguments raise ``TypeError``.
19
+ * Requires Python 3.12+, Flask 3.1+ and urlobject 3.0+.
@@ -0,0 +1,361 @@
1
+ Metadata-Version: 2.5
2
+ Name: flask-spurl
3
+ Version: 0.1.0
4
+ Summary: A Flask extension for building and changing URLs in Jinja templates.
5
+ Project-URL: download, https://github.com/bashu/flask-spurl/zipball/master
6
+ Project-URL: homepage, https://github.com/bashu/flask-spurl/
7
+ Author-email: Jamie Matthews <jamie.matthews@jamesturk.net>
8
+ Maintainer-email: Basil Shubin <basil.shubin@gmail.com>
9
+ License-Expression: Unlicense
10
+ License-File: UNLICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: Flask
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Requires-Python: >=3.12
25
+ Requires-Dist: flask>=3.1
26
+ Requires-Dist: urlobject>=3.0
27
+ Description-Content-Type: text/x-rst
28
+
29
+ Super URLs for Flask
30
+ ====================
31
+
32
+ .. code:: text
33
+
34
+ .=.,
35
+ ;c =\
36
+ __| _/
37
+ .'-'-._/-'-._
38
+ /.. ____ \
39
+ / {{spurl()}} \
40
+ ( / \--\_>/-/'._ )
41
+ \-;_/\__;__/ _/ _/
42
+ '._}|==o==\{_\/
43
+ / /-._.--\ \_
44
+ // / /| \ \ \
45
+ / | | | \; | \ \
46
+ / / | :/ \: \ \_\
47
+ / | /.'| /: | \ \
48
+ | | |--| . |--| \_\
49
+ / _/ \ | : | /___--._) \
50
+ |_(---'-| >-'-| | '-'
51
+ /_/ \_\
52
+
53
+ .. image:: https://img.shields.io/pypi/v/flask-spurl.svg
54
+ :target: https://pypi.org/project/flask-spurl/
55
+
56
+ .. image:: https://img.shields.io/pypi/pyversions/flask-spurl.svg
57
+ :target: https://pypi.org/project/flask-spurl/
58
+
59
+ .. image:: https://github.com/bashu/flask-spurl/actions/workflows/test.yml/badge.svg
60
+ :target: https://github.com/bashu/flask-spurl/actions/workflows/test.yml
61
+
62
+ **Spurl** is a Flask extension for building and changing URLs in Jinja
63
+ templates. Flask's ``url_for()`` builds links to your own routes; Spurl
64
+ works on any URL, yours or external: it adds, replaces, toggles or
65
+ removes query parameters, switches between ``http`` and ``https``,
66
+ changes the host, the path or the fragment, and so on. Typical uses are
67
+ pagination and sorting links, filters that keep the rest of the query,
68
+ and links to external sites that need extra parameters.
69
+
70
+ It is a port of `django-spurl <https://github.com/j4mie/django-spurl>`__
71
+ by `Jamie Matthews <http://www.j4mie.org/>`__ and is built on top of
72
+ Zachary Voase's `urlobject <https://github.com/zacharyvoase/urlobject/>`__.
73
+
74
+ Installation
75
+ ------------
76
+
77
+ Spurl needs Python 3.12+ and Flask 3.1+.
78
+
79
+ .. code:: shell
80
+
81
+ pip install flask-spurl
82
+
83
+ Set the extension up for your application:
84
+
85
+ .. code:: python
86
+
87
+ from flask import Flask
88
+ from flask_spurl import Spurl
89
+
90
+ app = Flask(__name__)
91
+ Spurl(app)
92
+
93
+ With the application factory pattern, create ``spurl = Spurl()`` once
94
+ and call ``spurl.init_app(app)`` inside the factory.
95
+
96
+ Usage
97
+ -----
98
+
99
+ The extension adds one function to your templates, ``spurl``. You call
100
+ it with keyword arguments, which are applied in the order you pass them.
101
+ The arguments are described fully below.
102
+
103
+ .. code:: html+jinja
104
+
105
+ <a href="{{ spurl(base=request.url, set_query={"page": page + 1}) }}">Next page</a>
106
+
107
+ Values are ordinary Jinja expressions: literals, template variables,
108
+ ``url_for()`` calls and so on. To keep the result for later, use
109
+ ``{% set %}``:
110
+
111
+ .. code:: html+jinja
112
+
113
+ {% set next_url = spurl(base=request.url, set_query={"page": 2}) %}
114
+
115
+ The same function is available in Python code as
116
+ ``flask_spurl.build_url``.
117
+
118
+ Adding query parameters to URLs
119
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
120
+
121
+ Say you have a list of external URLs and need to add a
122
+ ``referrer=mysite.com`` parameter to each. Writing
123
+ ``{{ url }}?referrer=mysite.com`` breaks any URL that already has a
124
+ query: you get ``http://www.example.com?foo=bar?referrer=mysite.com``.
125
+ Spurl knows where the query is and adds the parameter to it:
126
+
127
+ .. code:: html+jinja
128
+
129
+ {% for url, title in links %}
130
+ <a href="{{ spurl(base=url, add_query="referrer=mysite.com") }}">{{ title }}</a>
131
+ {% endfor %}
132
+
133
+ Matching the page's scheme
134
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
135
+
136
+ To load images from a third-party API over ``https`` when the page
137
+ itself is served over ``https``:
138
+
139
+ .. code:: html+jinja
140
+
141
+ {% for image_url in image_urls %}
142
+ <img src="{{ spurl(base=image_url, secure=request.is_secure) }}">
143
+ {% endfor %}
144
+
145
+ Using with ``url_for()``
146
+ ~~~~~~~~~~~~~~~~~~~~~~~~
147
+
148
+ Spurl does not know your routes, but you can pass the result of
149
+ ``url_for()`` to it:
150
+
151
+ .. code:: html+jinja
152
+
153
+ <a href="{{ spurl(path=url_for("index"), query="foo=bar&bar=baz") }}">Click here!</a>
154
+
155
+ Available arguments
156
+ -------------------
157
+
158
+ base
159
+ Parse the given URL and use it as the starting point. Without
160
+ ``base``, Spurl builds the URL from the parts you pass.
161
+
162
+ scheme
163
+ Set the scheme: ``spurl(base="http://example.com", scheme="ftp")``
164
+ gives ``ftp://example.com``. ``scheme`` and ``secure`` only make
165
+ sense for URLs that have a host: ``spurl(base="/foo/bar", scheme="https")``
166
+ gives ``https:///foo/bar``.
167
+
168
+ secure
169
+ Use ``https`` when the value is ``True`` or one of the strings
170
+ ``"true"`` and ``"on"`` (in any case), and ``http`` otherwise.
171
+
172
+ host
173
+ Set the host: ``spurl(base="http://example.com/some/path/", host="google.com")``
174
+ gives ``http://google.com/some/path/``. A URL with a host and no
175
+ scheme gets ``http``.
176
+
177
+ auth
178
+ Set the user name and the password:
179
+ ``spurl(base="https://example.com", auth="user:pass")`` gives
180
+ ``https://user:pass@example.com``.
181
+
182
+ port
183
+ Set the port from a number or a string:
184
+ ``spurl(base="http://example.com/some/path/", port=8080)`` gives
185
+ ``http://example.com:8080/some/path/``.
186
+
187
+ path
188
+ Replace the path:
189
+ ``spurl(base="http://example.com/some/path/", path="/different/")``
190
+ gives ``http://example.com/different/``.
191
+
192
+ add_path
193
+ Append to the path:
194
+ ``spurl(base=static_url, add_path=["javascript", "lib", "jquery.js"])``
195
+ gives ``http://cdn.example.com/javascript/lib/jquery.js`` when
196
+ ``static_url`` is ``http://cdn.example.com``.
197
+
198
+ fragment
199
+ Set the fragment:
200
+ ``spurl(base="http://example.com/#old", fragment="new")`` gives
201
+ ``http://example.com/#new``.
202
+
203
+ query
204
+ Replace the whole query with a query string or a dict:
205
+ ``spurl(base="http://example.com/", query="foo=bar&bar=baz")`` gives
206
+ ``http://example.com/?foo=bar&bar=baz``.
207
+
208
+ add_query
209
+ Add parameters (a query string or a dict) to the existing query:
210
+ ``spurl(base="http://example.com/?foo=bar", add_query="bar=baz")``
211
+ gives ``http://example.com/?foo=bar&bar=baz``.
212
+
213
+ set_query
214
+ Like ``add_query``, but replaces existing parameters with the same
215
+ name: ``spurl(base="http://example.com/?foo=bar", set_query="foo=baz")``
216
+ gives ``http://example.com/?foo=baz``.
217
+
218
+ toggle_query
219
+ Switch a parameter between two values, which is handy for sort
220
+ links. The values are given as ``"name=first,second"`` or as a dict
221
+ of pairs, ``{"sort": ("ascending", "descending")}``. If the
222
+ parameter is set to the first value, it gets the second one;
223
+ otherwise it gets the first one:
224
+
225
+ .. code:: html+jinja
226
+
227
+ <a href="{{ spurl(base=request.full_path, toggle_query="sort=ascending,descending") }}">Reverse order</a>
228
+
229
+ remove_query_param
230
+ Remove a parameter, or only one of its values:
231
+ ``spurl(base="http://example.com/?foo=bar&bar=baz&bar=foo", remove_query_param="bar=foo")``
232
+ gives ``http://example.com/?foo=bar&bar=baz``.
233
+
234
+ remove_query_params_except
235
+ Remove all parameters except the ones listed, separated by spaces:
236
+ ``spurl(base="http://example.com/?foo=bar&bar=baz&baz=foo", remove_query_params_except="baz")``
237
+ gives ``http://example.com/?baz=foo``.
238
+
239
+ ``_from`` arguments
240
+ ~~~~~~~~~~~~~~~~~~~
241
+
242
+ These take a full URL, extract one part of it, and apply it as the
243
+ argument without ``_from`` would: ``query_from``, ``add_query_from``,
244
+ ``set_query_from``, ``scheme_from``, ``host_from``, ``path_from``,
245
+ ``add_path_from``, ``fragment_from`` and ``port_from``. For example,
246
+ ``spurl(base="http://example.com/foo/bar/?foo=bar", path_from="http://another.com/something/?bar=foo")``
247
+ gives ``http://example.com/something/?foo=bar``.
248
+
249
+ Repeating an argument
250
+ ~~~~~~~~~~~~~~~~~~~~~
251
+
252
+ To apply an argument several times, pass a list:
253
+ ``spurl(base="http://example.com/?foo=bar&bar=baz", remove_query_param=["foo", "bar"])``
254
+ gives ``http://example.com/``. Each argument is applied once, with all
255
+ its items, in the order of the call. If you need, say, ``add_query``,
256
+ then ``set_query``, then ``add_query`` again, nest the calls:
257
+ ``spurl(base=spurl(base=url, add_query="a=1", set_query="b=2"), add_query="c=3")``.
258
+
259
+ Unknown arguments, and calls without arguments, raise ``TypeError``.
260
+
261
+ Escaping and security
262
+ ---------------------
263
+
264
+ Spurl returns a plain string, so Jinja escapes it like any other value:
265
+ an ``&`` in an HTML template is rendered as ``&amp;``, which is correct
266
+ inside ``href`` attributes. Do not add ``|safe`` to Spurl output that
267
+ contains user data.
268
+
269
+ Argument values are used as they are and are never rendered as
270
+ templates, so they are safe to take from user input. Spurl does not
271
+ check the resulting URL, though: if ``base`` or ``scheme`` comes from
272
+ user input, the link can point anywhere, including ``javascript:`` URLs.
273
+ Pass only trusted values there.
274
+
275
+ Coming from django-spurl
276
+ ------------------------
277
+
278
+ The arguments and their meaning are the same. The differences:
279
+
280
+ - ``{% spurl a=1 b=2 %}`` becomes ``{{ spurl(a=1, b=2) }}``, and
281
+ ``{% spurl ... as var %}`` becomes ``{% set var = spurl(...) %}``.
282
+ - A keyword repeated in the tag becomes a list:
283
+ ``add_query="a=1" add_query="b=2"`` becomes ``add_query=["a=1", "b=2"]``.
284
+ - Nested tags such as ``path="{\% url 'home' %\}"`` and inner variables
285
+ such as ``query="foo={{ bar }}"`` are gone: use Jinja expressions
286
+ instead, ``path=url_for("home")`` and ``query="foo=" ~ bar`` (or
287
+ ``set_query={"foo": bar}``). django-spurl rendered every string
288
+ argument as a template, so data passed to it could run template code;
289
+ flask-spurl never does this.
290
+ - The ``autoescape`` argument is gone; escaping follows the Jinja
291
+ environment.
292
+ - Unknown arguments raise ``TypeError`` instead of being ignored.
293
+
294
+ Development
295
+ -----------
296
+
297
+ To contribute, fork the `repository <https://github.com/bashu/flask-spurl/>`__,
298
+ make your changes, add tests, and open a pull request. Run the tests with
299
+ `uv <https://docs.astral.sh/uv/>`__:
300
+
301
+ .. code:: shell
302
+
303
+ uv run pytest
304
+
305
+ To run them for every supported Python version, use
306
+ `tox <https://tox.wiki>`__:
307
+
308
+ .. code:: shell
309
+
310
+ uvx --with tox-uv --with tox-gh tox
311
+
312
+ (Un)license
313
+ -----------
314
+
315
+ This is free and unencumbered software released into the public domain.
316
+
317
+ Anyone is free to copy, modify, publish, use, compile, sell, or
318
+ distribute this software, either in source code form or as a compiled
319
+ binary, for any purpose, commercial or non-commercial, and by any means.
320
+
321
+ In jurisdictions that recognize copyright laws, the author or authors of
322
+ this software dedicate any and all copyright interest in the software to
323
+ the public domain. We make this dedication for the benefit of the public
324
+ at large and to the detriment of our heirs and successors. We intend
325
+ this dedication to be an overt act of relinquishment in perpetuity of
326
+ all present and future rights to this software under copyright law.
327
+
328
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
329
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
330
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
331
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
332
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
333
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
334
+ DEALINGS IN THE SOFTWARE.
335
+
336
+ For more information, please refer to http://unlicense.org/
337
+
338
+ Artwork credit
339
+ --------------
340
+
341
+ Superman ASCII art comes from http://ascii.co.uk/art/superman
342
+
343
+ Changes
344
+ -------
345
+
346
+ 0.1.0 (2026-11-29)
347
+ ~~~~~~~~~~~~~~~~~~
348
+
349
+ First release of flask-spurl, a port of django-spurl 0.6.9 to Flask.
350
+
351
+ * The ``{% spurl %}`` tag is replaced by the Jinja function ``spurl(...)``,
352
+ registered by the ``flask_spurl.Spurl`` extension. The same builder is
353
+ available in Python as ``flask_spurl.build_url``.
354
+ * Argument names and their meaning are kept. A repeated argument is
355
+ passed as a list, and ``as var`` is replaced by ``{% set %}``.
356
+ * Argument values are no longer rendered as templates. In django-spurl,
357
+ data passed to the tag could run template code (template injection).
358
+ * The ``autoescape`` argument is removed; escaping follows the Jinja
359
+ environment.
360
+ * Unknown arguments and calls without arguments raise ``TypeError``.
361
+ * Requires Python 3.12+, Flask 3.1+ and urlobject 3.0+.
@@ -0,0 +1,313 @@
1
+ Super URLs for Flask
2
+ ====================
3
+
4
+ .. code:: text
5
+
6
+ .=.,
7
+ ;c =\
8
+ __| _/
9
+ .'-'-._/-'-._
10
+ /.. ____ \
11
+ / {{spurl()}} \
12
+ ( / \--\_>/-/'._ )
13
+ \-;_/\__;__/ _/ _/
14
+ '._}|==o==\{_\/
15
+ / /-._.--\ \_
16
+ // / /| \ \ \
17
+ / | | | \; | \ \
18
+ / / | :/ \: \ \_\
19
+ / | /.'| /: | \ \
20
+ | | |--| . |--| \_\
21
+ / _/ \ | : | /___--._) \
22
+ |_(---'-| >-'-| | '-'
23
+ /_/ \_\
24
+
25
+ .. image:: https://img.shields.io/pypi/v/flask-spurl.svg
26
+ :target: https://pypi.org/project/flask-spurl/
27
+
28
+ .. image:: https://img.shields.io/pypi/pyversions/flask-spurl.svg
29
+ :target: https://pypi.org/project/flask-spurl/
30
+
31
+ .. image:: https://github.com/bashu/flask-spurl/actions/workflows/test.yml/badge.svg
32
+ :target: https://github.com/bashu/flask-spurl/actions/workflows/test.yml
33
+
34
+ **Spurl** is a Flask extension for building and changing URLs in Jinja
35
+ templates. Flask's ``url_for()`` builds links to your own routes; Spurl
36
+ works on any URL, yours or external: it adds, replaces, toggles or
37
+ removes query parameters, switches between ``http`` and ``https``,
38
+ changes the host, the path or the fragment, and so on. Typical uses are
39
+ pagination and sorting links, filters that keep the rest of the query,
40
+ and links to external sites that need extra parameters.
41
+
42
+ It is a port of `django-spurl <https://github.com/j4mie/django-spurl>`__
43
+ by `Jamie Matthews <http://www.j4mie.org/>`__ and is built on top of
44
+ Zachary Voase's `urlobject <https://github.com/zacharyvoase/urlobject/>`__.
45
+
46
+ Installation
47
+ ------------
48
+
49
+ Spurl needs Python 3.12+ and Flask 3.1+.
50
+
51
+ .. code:: shell
52
+
53
+ pip install flask-spurl
54
+
55
+ Set the extension up for your application:
56
+
57
+ .. code:: python
58
+
59
+ from flask import Flask
60
+ from flask_spurl import Spurl
61
+
62
+ app = Flask(__name__)
63
+ Spurl(app)
64
+
65
+ With the application factory pattern, create ``spurl = Spurl()`` once
66
+ and call ``spurl.init_app(app)`` inside the factory.
67
+
68
+ Usage
69
+ -----
70
+
71
+ The extension adds one function to your templates, ``spurl``. You call
72
+ it with keyword arguments, which are applied in the order you pass them.
73
+ The arguments are described fully below.
74
+
75
+ .. code:: html+jinja
76
+
77
+ <a href="{{ spurl(base=request.url, set_query={"page": page + 1}) }}">Next page</a>
78
+
79
+ Values are ordinary Jinja expressions: literals, template variables,
80
+ ``url_for()`` calls and so on. To keep the result for later, use
81
+ ``{% set %}``:
82
+
83
+ .. code:: html+jinja
84
+
85
+ {% set next_url = spurl(base=request.url, set_query={"page": 2}) %}
86
+
87
+ The same function is available in Python code as
88
+ ``flask_spurl.build_url``.
89
+
90
+ Adding query parameters to URLs
91
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
92
+
93
+ Say you have a list of external URLs and need to add a
94
+ ``referrer=mysite.com`` parameter to each. Writing
95
+ ``{{ url }}?referrer=mysite.com`` breaks any URL that already has a
96
+ query: you get ``http://www.example.com?foo=bar?referrer=mysite.com``.
97
+ Spurl knows where the query is and adds the parameter to it:
98
+
99
+ .. code:: html+jinja
100
+
101
+ {% for url, title in links %}
102
+ <a href="{{ spurl(base=url, add_query="referrer=mysite.com") }}">{{ title }}</a>
103
+ {% endfor %}
104
+
105
+ Matching the page's scheme
106
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
107
+
108
+ To load images from a third-party API over ``https`` when the page
109
+ itself is served over ``https``:
110
+
111
+ .. code:: html+jinja
112
+
113
+ {% for image_url in image_urls %}
114
+ <img src="{{ spurl(base=image_url, secure=request.is_secure) }}">
115
+ {% endfor %}
116
+
117
+ Using with ``url_for()``
118
+ ~~~~~~~~~~~~~~~~~~~~~~~~
119
+
120
+ Spurl does not know your routes, but you can pass the result of
121
+ ``url_for()`` to it:
122
+
123
+ .. code:: html+jinja
124
+
125
+ <a href="{{ spurl(path=url_for("index"), query="foo=bar&bar=baz") }}">Click here!</a>
126
+
127
+ Available arguments
128
+ -------------------
129
+
130
+ base
131
+ Parse the given URL and use it as the starting point. Without
132
+ ``base``, Spurl builds the URL from the parts you pass.
133
+
134
+ scheme
135
+ Set the scheme: ``spurl(base="http://example.com", scheme="ftp")``
136
+ gives ``ftp://example.com``. ``scheme`` and ``secure`` only make
137
+ sense for URLs that have a host: ``spurl(base="/foo/bar", scheme="https")``
138
+ gives ``https:///foo/bar``.
139
+
140
+ secure
141
+ Use ``https`` when the value is ``True`` or one of the strings
142
+ ``"true"`` and ``"on"`` (in any case), and ``http`` otherwise.
143
+
144
+ host
145
+ Set the host: ``spurl(base="http://example.com/some/path/", host="google.com")``
146
+ gives ``http://google.com/some/path/``. A URL with a host and no
147
+ scheme gets ``http``.
148
+
149
+ auth
150
+ Set the user name and the password:
151
+ ``spurl(base="https://example.com", auth="user:pass")`` gives
152
+ ``https://user:pass@example.com``.
153
+
154
+ port
155
+ Set the port from a number or a string:
156
+ ``spurl(base="http://example.com/some/path/", port=8080)`` gives
157
+ ``http://example.com:8080/some/path/``.
158
+
159
+ path
160
+ Replace the path:
161
+ ``spurl(base="http://example.com/some/path/", path="/different/")``
162
+ gives ``http://example.com/different/``.
163
+
164
+ add_path
165
+ Append to the path:
166
+ ``spurl(base=static_url, add_path=["javascript", "lib", "jquery.js"])``
167
+ gives ``http://cdn.example.com/javascript/lib/jquery.js`` when
168
+ ``static_url`` is ``http://cdn.example.com``.
169
+
170
+ fragment
171
+ Set the fragment:
172
+ ``spurl(base="http://example.com/#old", fragment="new")`` gives
173
+ ``http://example.com/#new``.
174
+
175
+ query
176
+ Replace the whole query with a query string or a dict:
177
+ ``spurl(base="http://example.com/", query="foo=bar&bar=baz")`` gives
178
+ ``http://example.com/?foo=bar&bar=baz``.
179
+
180
+ add_query
181
+ Add parameters (a query string or a dict) to the existing query:
182
+ ``spurl(base="http://example.com/?foo=bar", add_query="bar=baz")``
183
+ gives ``http://example.com/?foo=bar&bar=baz``.
184
+
185
+ set_query
186
+ Like ``add_query``, but replaces existing parameters with the same
187
+ name: ``spurl(base="http://example.com/?foo=bar", set_query="foo=baz")``
188
+ gives ``http://example.com/?foo=baz``.
189
+
190
+ toggle_query
191
+ Switch a parameter between two values, which is handy for sort
192
+ links. The values are given as ``"name=first,second"`` or as a dict
193
+ of pairs, ``{"sort": ("ascending", "descending")}``. If the
194
+ parameter is set to the first value, it gets the second one;
195
+ otherwise it gets the first one:
196
+
197
+ .. code:: html+jinja
198
+
199
+ <a href="{{ spurl(base=request.full_path, toggle_query="sort=ascending,descending") }}">Reverse order</a>
200
+
201
+ remove_query_param
202
+ Remove a parameter, or only one of its values:
203
+ ``spurl(base="http://example.com/?foo=bar&bar=baz&bar=foo", remove_query_param="bar=foo")``
204
+ gives ``http://example.com/?foo=bar&bar=baz``.
205
+
206
+ remove_query_params_except
207
+ Remove all parameters except the ones listed, separated by spaces:
208
+ ``spurl(base="http://example.com/?foo=bar&bar=baz&baz=foo", remove_query_params_except="baz")``
209
+ gives ``http://example.com/?baz=foo``.
210
+
211
+ ``_from`` arguments
212
+ ~~~~~~~~~~~~~~~~~~~
213
+
214
+ These take a full URL, extract one part of it, and apply it as the
215
+ argument without ``_from`` would: ``query_from``, ``add_query_from``,
216
+ ``set_query_from``, ``scheme_from``, ``host_from``, ``path_from``,
217
+ ``add_path_from``, ``fragment_from`` and ``port_from``. For example,
218
+ ``spurl(base="http://example.com/foo/bar/?foo=bar", path_from="http://another.com/something/?bar=foo")``
219
+ gives ``http://example.com/something/?foo=bar``.
220
+
221
+ Repeating an argument
222
+ ~~~~~~~~~~~~~~~~~~~~~
223
+
224
+ To apply an argument several times, pass a list:
225
+ ``spurl(base="http://example.com/?foo=bar&bar=baz", remove_query_param=["foo", "bar"])``
226
+ gives ``http://example.com/``. Each argument is applied once, with all
227
+ its items, in the order of the call. If you need, say, ``add_query``,
228
+ then ``set_query``, then ``add_query`` again, nest the calls:
229
+ ``spurl(base=spurl(base=url, add_query="a=1", set_query="b=2"), add_query="c=3")``.
230
+
231
+ Unknown arguments, and calls without arguments, raise ``TypeError``.
232
+
233
+ Escaping and security
234
+ ---------------------
235
+
236
+ Spurl returns a plain string, so Jinja escapes it like any other value:
237
+ an ``&`` in an HTML template is rendered as ``&amp;``, which is correct
238
+ inside ``href`` attributes. Do not add ``|safe`` to Spurl output that
239
+ contains user data.
240
+
241
+ Argument values are used as they are and are never rendered as
242
+ templates, so they are safe to take from user input. Spurl does not
243
+ check the resulting URL, though: if ``base`` or ``scheme`` comes from
244
+ user input, the link can point anywhere, including ``javascript:`` URLs.
245
+ Pass only trusted values there.
246
+
247
+ Coming from django-spurl
248
+ ------------------------
249
+
250
+ The arguments and their meaning are the same. The differences:
251
+
252
+ - ``{% spurl a=1 b=2 %}`` becomes ``{{ spurl(a=1, b=2) }}``, and
253
+ ``{% spurl ... as var %}`` becomes ``{% set var = spurl(...) %}``.
254
+ - A keyword repeated in the tag becomes a list:
255
+ ``add_query="a=1" add_query="b=2"`` becomes ``add_query=["a=1", "b=2"]``.
256
+ - Nested tags such as ``path="{\% url 'home' %\}"`` and inner variables
257
+ such as ``query="foo={{ bar }}"`` are gone: use Jinja expressions
258
+ instead, ``path=url_for("home")`` and ``query="foo=" ~ bar`` (or
259
+ ``set_query={"foo": bar}``). django-spurl rendered every string
260
+ argument as a template, so data passed to it could run template code;
261
+ flask-spurl never does this.
262
+ - The ``autoescape`` argument is gone; escaping follows the Jinja
263
+ environment.
264
+ - Unknown arguments raise ``TypeError`` instead of being ignored.
265
+
266
+ Development
267
+ -----------
268
+
269
+ To contribute, fork the `repository <https://github.com/bashu/flask-spurl/>`__,
270
+ make your changes, add tests, and open a pull request. Run the tests with
271
+ `uv <https://docs.astral.sh/uv/>`__:
272
+
273
+ .. code:: shell
274
+
275
+ uv run pytest
276
+
277
+ To run them for every supported Python version, use
278
+ `tox <https://tox.wiki>`__:
279
+
280
+ .. code:: shell
281
+
282
+ uvx --with tox-uv --with tox-gh tox
283
+
284
+ (Un)license
285
+ -----------
286
+
287
+ This is free and unencumbered software released into the public domain.
288
+
289
+ Anyone is free to copy, modify, publish, use, compile, sell, or
290
+ distribute this software, either in source code form or as a compiled
291
+ binary, for any purpose, commercial or non-commercial, and by any means.
292
+
293
+ In jurisdictions that recognize copyright laws, the author or authors of
294
+ this software dedicate any and all copyright interest in the software to
295
+ the public domain. We make this dedication for the benefit of the public
296
+ at large and to the detriment of our heirs and successors. We intend
297
+ this dedication to be an overt act of relinquishment in perpetuity of
298
+ all present and future rights to this software under copyright law.
299
+
300
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
301
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
302
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
303
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
304
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
305
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
306
+ DEALINGS IN THE SOFTWARE.
307
+
308
+ For more information, please refer to http://unlicense.org/
309
+
310
+ Artwork credit
311
+ --------------
312
+
313
+ Superman ASCII art comes from http://ascii.co.uk/art/superman
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <http://unlicense.org/>
@@ -0,0 +1,136 @@
1
+ [build-system]
2
+ build-backend = "hatchling.build"
3
+ requires = [ "hatch-fancy-pypi-readme>=24.1", "hatchling>=1.27" ]
4
+
5
+ [project]
6
+ name = "flask-spurl"
7
+ version = "0.1.0"
8
+ description = "A Flask extension for building and changing URLs in Jinja templates."
9
+ license = "Unlicense"
10
+ license-files = [ "UNLICENSE" ]
11
+ maintainers = [ { name = "Basil Shubin", email = "basil.shubin@gmail.com" } ]
12
+ authors = [
13
+ { name = "Jamie Matthews", email = "jamie.matthews@jamesturk.net" },
14
+ ]
15
+ requires-python = ">=3.12"
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Environment :: Web Environment",
19
+ "Framework :: Flask",
20
+ "Intended Audience :: Developers",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python",
23
+ "Programming Language :: Python :: 3 :: Only",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Programming Language :: Python :: 3.14",
27
+ "Programming Language :: Python :: 3.15",
28
+ "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
29
+ "Topic :: Software Development :: Libraries :: Python Modules",
30
+ ]
31
+ dynamic = [ "readme" ]
32
+ dependencies = [
33
+ "flask>=3.1",
34
+ "urlobject>=3.0",
35
+ ]
36
+ urls.download = "https://github.com/bashu/flask-spurl/zipball/master"
37
+ urls.homepage = "https://github.com/bashu/flask-spurl/"
38
+
39
+ [dependency-groups]
40
+ dev = [
41
+ "coverage==7.17.2",
42
+ "mypy==2.4.1",
43
+ "pre-commit==4.7.0",
44
+ "pytest==9.2.0",
45
+ "pytest-sugar==1.1.1",
46
+ "ruff==0.17.4",
47
+ ]
48
+
49
+ [tool.hatch]
50
+ metadata.hooks.fancy-pypi-readme.content-type = "text/x-rst"
51
+ metadata.hooks.fancy-pypi-readme.fragments = [ { path = "README.rst" }, { text = "\n" }, { path = "CHANGES.rst" } ]
52
+ build.targets.wheel.packages = [ "src/flask_spurl" ]
53
+ build.targets.sdist.only-include = [ "src", "AUTHORS", "CHANGES.rst", "README.rst" ]
54
+
55
+ # ==== ruff ====
56
+ [tool.ruff]
57
+ lint.select = [
58
+ "A",
59
+ "ASYNC",
60
+ "B",
61
+ "BLE",
62
+ "C4",
63
+ "C90",
64
+ "COM",
65
+ "DTZ",
66
+ "E",
67
+ "EM",
68
+ "ERA",
69
+ "EXE",
70
+ "F",
71
+ "FA",
72
+ "FBT",
73
+ "FLY",
74
+ "G",
75
+ "I",
76
+ "ICN",
77
+ "INP",
78
+ "INT",
79
+ "ISC",
80
+ "N",
81
+ "PD",
82
+ "PERF",
83
+ "PGH",
84
+ "PIE",
85
+ "PL",
86
+ "PT",
87
+ "PTH",
88
+ "PYI",
89
+ "Q",
90
+ "RET",
91
+ "RSE",
92
+ "RUF",
93
+ "S",
94
+ "SIM",
95
+ "SLF",
96
+ "SLOT",
97
+ "T10",
98
+ "T20",
99
+ "TC",
100
+ "TID",
101
+ "TRY",
102
+ "UP",
103
+ "W",
104
+ "YTT",
105
+ ]
106
+ lint.ignore = [
107
+ "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar`
108
+ "S101", # Use of assert detected https://docs.astral.sh/ruff/rules/assert/
109
+ "SIM102", # sometimes it's better to nest
110
+ # of types for comparison.
111
+ # Deactivated because it can make the code slow:
112
+ # https://github.com/astral-sh/ruff/issues/7871
113
+ ]
114
+ lint.isort.default-section = "third-party"
115
+ lint.isort.force-single-line = true
116
+ lint.isort.known-first-party = [ "flask_spurl" ]
117
+ lint.isort.section-order = [ "future", "standard-library", "flask", "third-party", "first-party", "local-folder" ]
118
+ lint.isort.sections.flask = [ "flask" ]
119
+
120
+ # ==== pyproject-fmt ====
121
+ [tool.pyproject-fmt]
122
+ keep_full_version = true
123
+
124
+ # ==== mypy ====
125
+ [tool.mypy]
126
+ ignore_missing_imports = true
127
+ python_version = "3.15"
128
+ check_untyped_defs = true
129
+ warn_redundant_casts = true
130
+ warn_unused_ignores = true
131
+ warn_unused_configs = true
132
+
133
+ # ==== coverage ====
134
+ [tool.coverage]
135
+ run.source = [ "flask_spurl" ]
136
+ run.relative_files = true
@@ -0,0 +1,6 @@
1
+ from .builder import build_url
2
+ from .extension import Spurl
3
+
4
+ __all__ = ["Spurl", "build_url"]
5
+
6
+ __version__ = "0.1.0"
@@ -0,0 +1,182 @@
1
+ """Build URLs from ordered keyword arguments, independently of any web framework."""
2
+
3
+ import re
4
+ from collections.abc import Mapping
5
+ from typing import Any
6
+
7
+ from urlobject import URLObject
8
+ from urlobject.query_string import QueryString
9
+
10
+ TRUE_RE = re.compile(r"^(true|on)$", flags=re.IGNORECASE)
11
+
12
+
13
+ def convert_to_boolean(value: object) -> bool | None:
14
+ """Return ``value`` if it is a boolean, or whether a string is ``true`` or ``on``.
15
+
16
+ Any other value gives ``None``.
17
+ """
18
+ if isinstance(value, bool):
19
+ return value
20
+
21
+ if isinstance(value, str):
22
+ return bool(TRUE_RE.match(value))
23
+
24
+ return None
25
+
26
+
27
+ def parse_query(query: str | Mapping[str, Any]) -> Mapping[str, Any]:
28
+ """Return a query given as a string as a dict; return a mapping unchanged."""
29
+ if isinstance(query, str):
30
+ return QueryString(query).dict
31
+
32
+ return query
33
+
34
+
35
+ class URLBuilder:
36
+ """Builds a URL by applying spurl arguments one by one, in the order given.
37
+
38
+ Each supported argument ``name`` has a ``handle_<name>`` method.
39
+ """
40
+
41
+ def __init__(self) -> None:
42
+ self.url = URLObject()
43
+
44
+ def build(self, arguments: Mapping[str, Any]) -> str:
45
+ """Apply ``arguments`` in order and return the resulting URL.
46
+
47
+ A list or tuple value applies its argument once per item.
48
+ Raises ``TypeError`` when there are no arguments or some are not supported.
49
+ """
50
+ if not arguments:
51
+ msg = "spurl takes at least one argument"
52
+ raise TypeError(msg)
53
+
54
+ if unknown := [name for name in arguments if name not in SUPPORTED_ARGUMENTS]:
55
+ msg = f"Unsupported spurl arguments: {', '.join(unknown)}"
56
+ raise TypeError(msg)
57
+
58
+ for name, value in arguments.items():
59
+ handler = getattr(self, f"handle_{name}")
60
+ items = value if isinstance(value, list | tuple) else (value,)
61
+
62
+ for item in items:
63
+ handler(item)
64
+
65
+ self.set_sensible_defaults()
66
+
67
+ return str(self.url)
68
+
69
+ def handle_base(self, value: str) -> None:
70
+ self.url = URLObject(value)
71
+
72
+ def handle_auth(self, value: str) -> None:
73
+ self.url = self.url.with_auth(*value.split(":", 1))
74
+
75
+ def handle_secure(self, value: bool | str) -> None: # noqa: FBT001
76
+ scheme = "https" if convert_to_boolean(value) else "http"
77
+ self.url = self.url.with_scheme(scheme)
78
+
79
+ def handle_query(self, value: str | Mapping[str, Any]) -> None:
80
+ query = (
81
+ QueryString().set_params(**value) if isinstance(value, Mapping) else value
82
+ )
83
+ self.url = self.url.with_query(QueryString(query))
84
+
85
+ def handle_query_from(self, value: str) -> None:
86
+ self.url = self.url.with_query(URLObject(value).query)
87
+
88
+ def handle_add_query(self, value: str | Mapping[str, Any]) -> None:
89
+ self.url = self.url.add_query_params(**parse_query(value))
90
+
91
+ def handle_add_query_from(self, value: str) -> None:
92
+ self.url = self.url.add_query_params(**URLObject(value).query.dict)
93
+
94
+ def handle_set_query(self, value: str | Mapping[str, Any]) -> None:
95
+ self.url = self.url.set_query_params(**parse_query(value))
96
+
97
+ def handle_set_query_from(self, value: str) -> None:
98
+ self.url = self.url.set_query_params(**URLObject(value).query.dict)
99
+
100
+ def handle_remove_query_param(self, value: str) -> None:
101
+ if "=" in value:
102
+ name, param_value = value.split("=", 1)
103
+ self.url = self.url.del_query_param_value(name, param_value)
104
+
105
+ else:
106
+ self.url = self.url.del_query_param(value)
107
+
108
+ def handle_remove_query_params_except(self, value: str) -> None:
109
+ params_to_keep = value.split(" ")
110
+ params_to_remove = [
111
+ name for name, _ in self.url.query_list if name not in params_to_keep
112
+ ]
113
+ self.url = self.url.with_query(self.url.query.del_params(params_to_remove))
114
+
115
+ def handle_toggle_query(self, value: str | Mapping[str, Any]) -> None:
116
+ current_query = self.url.query.dict
117
+
118
+ for name, values in parse_query(value).items():
119
+ first, second = values.split(",") if isinstance(values, str) else values
120
+
121
+ if name in current_query and current_query[name] == first:
122
+ self.url = self.url.set_query_param(name, second)
123
+
124
+ else:
125
+ self.url = self.url.set_query_param(name, first)
126
+
127
+ def handle_scheme(self, value: str) -> None:
128
+ self.url = self.url.with_scheme(value)
129
+
130
+ def handle_scheme_from(self, value: str) -> None:
131
+ self.url = self.url.with_scheme(URLObject(value).scheme)
132
+
133
+ def handle_host(self, value: str) -> None:
134
+ self.url = self.url.with_hostname(value)
135
+
136
+ def handle_host_from(self, value: str) -> None:
137
+ self.url = self.url.with_hostname(URLObject(value).hostname)
138
+
139
+ def handle_path(self, value: str) -> None:
140
+ self.url = self.url.with_path(value)
141
+
142
+ def handle_path_from(self, value: str) -> None:
143
+ self.url = self.url.with_path(URLObject(value).path)
144
+
145
+ def handle_add_path(self, value: str) -> None:
146
+ self.url = self.url.add_path(value)
147
+
148
+ def handle_add_path_from(self, value: str) -> None:
149
+ self.url = self.url.add_path(URLObject(value).path.removeprefix("/"))
150
+
151
+ def handle_fragment(self, value: str) -> None:
152
+ self.url = self.url.with_fragment(value)
153
+
154
+ def handle_fragment_from(self, value: str) -> None:
155
+ self.url = self.url.with_fragment(URLObject(value).fragment)
156
+
157
+ def handle_port(self, value: int | str) -> None:
158
+ self.url = self.url.with_port(int(value))
159
+
160
+ def handle_port_from(self, value: str) -> None:
161
+ self.url = self.url.with_port(URLObject(value).port)
162
+
163
+ def set_sensible_defaults(self) -> None:
164
+ """Use ``http`` when the URL has a host but no scheme."""
165
+ if self.url.hostname and not self.url.scheme:
166
+ self.url = self.url.with_scheme("http")
167
+
168
+
169
+ SUPPORTED_ARGUMENTS = frozenset(
170
+ name.removeprefix("handle_")
171
+ for name in vars(URLBuilder)
172
+ if name.startswith("handle_")
173
+ )
174
+
175
+
176
+ def build_url(**arguments: Any) -> str:
177
+ """Build a URL from spurl arguments, applied in the order they are passed.
178
+
179
+ For example, ``build_url(base="http://example.com/?page=1", set_query="page=2")``
180
+ returns ``"http://example.com/?page=2"``.
181
+ """
182
+ return URLBuilder().build(arguments)
@@ -0,0 +1,22 @@
1
+ """Flask extension that adds ``spurl`` to Jinja templates."""
2
+
3
+ from flask import Flask
4
+
5
+ from .builder import build_url
6
+
7
+
8
+ class Spurl:
9
+ """Makes ``spurl(...)`` available in the Jinja templates of a Flask app.
10
+
11
+ Pass the app to the constructor, or call :meth:`init_app` later.
12
+ One instance can be set up for several apps.
13
+ """
14
+
15
+ def __init__(self, app: Flask | None = None) -> None:
16
+ if app is not None:
17
+ self.init_app(app)
18
+
19
+ def init_app(self, app: Flask) -> None:
20
+ """Register ``spurl`` as a template global of ``app``."""
21
+ app.add_template_global(build_url, name="spurl")
22
+ app.extensions["spurl"] = self