silver-nitrate 1.0.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,201 @@
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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright 2023 The Flickr Foundation.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.1
2
+ Name: silver-nitrate
3
+ Version: 1.0.0
4
+ Summary: Python utilities used by the Flickr Foundation
5
+ Author-email: Flickr Foundation <hello@flickr.org>
6
+ Maintainer-email: Alex Chan <alex@flickr.org>
7
+ Project-URL: Homepage, https://github.com/Flickr-Foundation/silver-nitrate
8
+ Project-URL: Changelog, https://github.com/Flickr-Foundation/silver-nitrate/blob/main/CHANGELOG.md
9
+ Keywords: flickr
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.12
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE-APACHE
17
+ License-File: LICENSE-MIT
18
+
19
+ # silver-nitrate
20
+
21
+ This is a collection of Python utilities used by [the Flickr Foundation](https://www.flickr.org/).
22
+ It allows us to share certain functions and common code across all our projects.
23
+
24
+ Think of it as a souped-up version of `utils.py`.
25
+
26
+ This library is primarily for our use, but the code is fairly generic and may well be useful in other projects.
27
+ If you want to use it, copy/paste the code (and the associated tests!) into your own project rather than adding a dependency on this library.
28
+
29
+ <figure>
30
+ <a href="https://www.flickr.com/photos/podsville/3912488857">
31
+ <img src="https://live.staticflickr.com/3438/3912488857_78a5103b69_c_d.jpg">
32
+ </a>
33
+ <figcaption>
34
+ <em>Builder's Photo of 2-8-0 Locomotive No 1402 "James Archbald," built in 1930 by the Delaware & Hudson Railroad.</em>
35
+ Scan of a silver-halide photo print.
36
+ Photo from Bill Harrison <a href="https://www.flickr.com/photos/podsville/3912488857">on Flickr</a>.
37
+ </figcaption>
38
+ </figure>
39
+
40
+ ## What's in a name?
41
+
42
+ I wanted to pick a name that was:
43
+
44
+ 1. More interesting than "utils"
45
+ 2. Had a connection to photography
46
+ 3. Wasn't taken on PyPI
47
+
48
+ Silver nitrate was a key chemical in the early days of photography, especially in the 19th and early 20th centuries.
49
+
50
+ Photographers would coat glass plates with a mixture of chemicals, including silver nitrate.
51
+ Because silver nitrate reacts when exposed to light, when you put the plate in a camera and open the shutter, different areas would react differently to create an image on the plate.
52
+ You could then develop this plate into a photograph.
53
+
54
+ This code is key to our work at the Flickr Foundation, so I thought it was a fitting name.
55
+
56
+ ## Development
57
+
58
+ If you want to make changes to the library, there are instructions in [CONTRIBUTING.md](./CONTRIBUTING.md).
59
+
60
+ ## License
61
+
62
+ This project is dual-licensed as Apache-2.0 and MIT.
@@ -0,0 +1,44 @@
1
+ # silver-nitrate
2
+
3
+ This is a collection of Python utilities used by [the Flickr Foundation](https://www.flickr.org/).
4
+ It allows us to share certain functions and common code across all our projects.
5
+
6
+ Think of it as a souped-up version of `utils.py`.
7
+
8
+ This library is primarily for our use, but the code is fairly generic and may well be useful in other projects.
9
+ If you want to use it, copy/paste the code (and the associated tests!) into your own project rather than adding a dependency on this library.
10
+
11
+ <figure>
12
+ <a href="https://www.flickr.com/photos/podsville/3912488857">
13
+ <img src="https://live.staticflickr.com/3438/3912488857_78a5103b69_c_d.jpg">
14
+ </a>
15
+ <figcaption>
16
+ <em>Builder's Photo of 2-8-0 Locomotive No 1402 "James Archbald," built in 1930 by the Delaware & Hudson Railroad.</em>
17
+ Scan of a silver-halide photo print.
18
+ Photo from Bill Harrison <a href="https://www.flickr.com/photos/podsville/3912488857">on Flickr</a>.
19
+ </figcaption>
20
+ </figure>
21
+
22
+ ## What's in a name?
23
+
24
+ I wanted to pick a name that was:
25
+
26
+ 1. More interesting than "utils"
27
+ 2. Had a connection to photography
28
+ 3. Wasn't taken on PyPI
29
+
30
+ Silver nitrate was a key chemical in the early days of photography, especially in the 19th and early 20th centuries.
31
+
32
+ Photographers would coat glass plates with a mixture of chemicals, including silver nitrate.
33
+ Because silver nitrate reacts when exposed to light, when you put the plate in a camera and open the shutter, different areas would react differently to create an image on the plate.
34
+ You could then develop this plate into a photograph.
35
+
36
+ This code is key to our work at the Flickr Foundation, so I thought it was a fitting name.
37
+
38
+ ## Development
39
+
40
+ If you want to make changes to the library, there are instructions in [CONTRIBUTING.md](./CONTRIBUTING.md).
41
+
42
+ ## License
43
+
44
+ This project is dual-licensed as Apache-2.0 and MIT.
@@ -0,0 +1,74 @@
1
+ [build-system]
2
+ requires = [
3
+ "setuptools >= 65",
4
+ ]
5
+ build-backend = "setuptools.build_meta"
6
+
7
+ [project]
8
+ name = "silver-nitrate"
9
+ description = "Python utilities used by the Flickr Foundation"
10
+ readme = "README.md"
11
+ keywords = ["flickr"]
12
+ authors = [
13
+ {name = "Flickr Foundation", email = "hello@flickr.org"},
14
+ ]
15
+ maintainers = [
16
+ {name = "Alex Chan", email="alex@flickr.org"},
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 5 - Production/Stable",
20
+ "License :: OSI Approved :: Apache Software License",
21
+ "License :: OSI Approved :: MIT License",
22
+ "Programming Language :: Python :: 3.12",
23
+ ]
24
+ requires-python = ">=3.12"
25
+ dependencies = []
26
+ dynamic = ["version"]
27
+
28
+ [project.urls]
29
+ "Homepage" = "https://github.com/Flickr-Foundation/silver-nitrate"
30
+ "Changelog" = "https://github.com/Flickr-Foundation/silver-nitrate/blob/main/CHANGELOG.md"
31
+
32
+ [tool.setuptools.dynamic]
33
+ version = {attr = "nitrate.__version__"}
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+
38
+ [tool.setuptools.package-data]
39
+ nitrate = ["py.typed"]
40
+
41
+ [tool.coverage.run]
42
+ branch = true
43
+ source = [
44
+ "nitrate",
45
+ "tests",
46
+ ]
47
+
48
+ [tool.coverage.report]
49
+ show_missing = true
50
+ skip_covered = true
51
+ fail_under = 100
52
+
53
+ [tool.pytest.ini_options]
54
+ filterwarnings = [
55
+ "error",
56
+ ]
57
+
58
+ [tool.mypy]
59
+ mypy_path = "src"
60
+ check_untyped_defs = true
61
+ disallow_any_generics = true
62
+ disallow_incomplete_defs = true
63
+ disallow_subclassing_any = true
64
+ disallow_untyped_calls = true
65
+ disallow_untyped_decorators = true
66
+ disallow_untyped_defs = true
67
+ no_implicit_optional = true
68
+ no_implicit_reexport = true
69
+ show_error_codes = true
70
+ strict_equality = true
71
+ warn_redundant_casts = true
72
+ warn_return_any = true
73
+ warn_unused_configs = true
74
+ warn_unused_ignores = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
@@ -0,0 +1,66 @@
1
+ """
2
+ Use cassettes for testing HTTP APIs with VCR.py [1]
3
+
4
+ This establishes a couple of conventions for where cassettes are stored
5
+ and how they're named.
6
+
7
+ [1]: https://vcrpy.readthedocs.io/
8
+ """
9
+
10
+ from collections.abc import Generator
11
+
12
+ import pytest
13
+ import vcr
14
+ from vcr.cassette import Cassette
15
+
16
+
17
+ def get_cassette_name(request: pytest.FixtureRequest) -> str:
18
+ """
19
+ Returns the name of a cassette for vcr.py.
20
+
21
+ The name can be made up of (up to) three parts:
22
+
23
+ - the name of the test class
24
+ - the name of the test function
25
+ - the ID of the test case in @pytest.mark.parametrize
26
+
27
+ """
28
+ name = request.node.name
29
+
30
+ # This is to catch cases where e.g. we try to include a complete
31
+ # HTTP URL in a cassette name, which creates very messy folders in
32
+ # the fixtures directory.
33
+ if any(char in name for char in ":/."):
34
+ raise ValueError(
35
+ "Illegal characters in VCR cassette name - "
36
+ "please set a test ID with @pytest.param(…, id='…')"
37
+ )
38
+
39
+ if request.cls is not None:
40
+ return f"{request.cls.__name__}.{name}.yml"
41
+ else:
42
+ return f"{name}.yml"
43
+
44
+
45
+ @pytest.fixture(scope="function")
46
+ def cassette_name(request: pytest.FixtureRequest) -> str:
47
+ return get_cassette_name(request)
48
+
49
+
50
+ @pytest.fixture(scope="function")
51
+ def vcr_cassette(cassette_name: str) -> Generator[Cassette, None, None]:
52
+ """
53
+ Creates a VCR cassette for use in tests.
54
+
55
+ Anything using httpx in this test will record its HTTP interactions
56
+ as "cassettes" using vcr.py, which can be replayed offline
57
+ (e.g. in CI tests).
58
+ """
59
+ with vcr.use_cassette(
60
+ cassette_name,
61
+ cassette_library_dir="tests/fixtures/cassettes",
62
+ ) as cassette:
63
+ yield cassette
64
+
65
+
66
+ __all__ = ["cassette_name", "vcr_cassette"]
@@ -0,0 +1,63 @@
1
+ """
2
+ Allow encoding/decoding JSON in a type-preserving way.
3
+
4
+ In particular, these classes allow us to store ``datetime.datetime``
5
+ values in JSON and retrieve them as proper datetime objects, rather
6
+ than e.g. strings.
7
+ """
8
+
9
+ import datetime
10
+ import json
11
+ from typing import Any, Literal, TypedDict, TypeVar
12
+
13
+
14
+ T = TypeVar("T")
15
+
16
+ EncodedDate = TypedDict(
17
+ "EncodedDate", {"type": Literal["datetime.datetime"], "value": str}
18
+ )
19
+
20
+
21
+ class DatetimeEncoder(json.JSONEncoder):
22
+ """
23
+ A custom JSON encoder that supports datetimes.
24
+
25
+ >>> t = datetime.datetime(2001, 2, 3, 4, 5, 6)
26
+ >>> json.dumps({"t": t}, cls=DatetimeEncoder)
27
+ '{"t": {"type": "datetime.datetime", "value": "2001-02-03T04:05:06"}}'
28
+
29
+ This is meant to be used with ``DatetimeDecoder`` -- together, they
30
+ allow you to serialise a datetime value via JSON and preserve its type.
31
+
32
+ """
33
+
34
+ def default(self, t: T) -> T | EncodedDate:
35
+ if isinstance(t, datetime.datetime):
36
+ return {"type": "datetime.datetime", "value": t.isoformat()}
37
+ else: # pragma: no cover
38
+ return t
39
+
40
+
41
+ class DatetimeDecoder(json.JSONDecoder):
42
+ """
43
+ A custom JSON decoder that supports the datetimes encoded
44
+ by DatetimeEncoder.
45
+
46
+ >>> json.loads(
47
+ ... '{"t": {"type": "datetime.datetime", "value": "2001-02-03T04:05:06"}}',
48
+ ... cls=DatetimeDecoder)
49
+ {'t': datetime.datetime(2001, 2, 3, 4, 5, 6)}
50
+
51
+ """
52
+
53
+ def __init__(self) -> None:
54
+ super().__init__(object_hook=self.dict_to_object)
55
+
56
+ def dict_to_object(self, d: dict[str, Any]) -> dict[str, Any] | datetime.datetime:
57
+ if d.get("type") == "datetime.datetime":
58
+ return datetime.datetime.fromisoformat(d["value"])
59
+ else:
60
+ return d
61
+
62
+
63
+ __all__ = ["DatetimeEncoder", "DatetimeDecoder"]
@@ -0,0 +1,64 @@
1
+ """
2
+ Retrieve passwords from the system keychain.
3
+
4
+ This provides a thin wrapper around the ``keyring`` module.
5
+ """
6
+
7
+ import keyring
8
+
9
+
10
+ def get_required_password(service_name: str, username: str) -> str:
11
+ """
12
+ Retrieve a password from the keychain, or throw if it's missing.
13
+ """
14
+ # We wrap this API because keyring will return ``None`` rather
15
+ # than tell you a password is missing, e.g.
16
+ #
17
+ # >>> import keyring
18
+ # >>> pw = keyring.get_password("doesnotexist", "doesnotexist")
19
+ # >>> print(pw)
20
+ # None
21
+ #
22
+ # It's better to throw an error early than let this empty value
23
+ # propagate into our code and bubble up elsewhere.
24
+ #
25
+ # e.g. if we're calling the Flickr API using an API key retrieved
26
+ # using keyring, we'd rather know immediately that it's empty than
27
+ # get a cryptic "invalid API key" error from the Flickr API.
28
+ #
29
+ password = keyring.get_password(service_name, username)
30
+
31
+ if password is None:
32
+ raise RuntimeError(f"Could not retrieve password {(service_name, username)}")
33
+
34
+ return password
35
+
36
+
37
+ class InMemoryKeyring(keyring.backend.KeyringBackend):
38
+ """
39
+ A keyring implementation which stores passwords in a dictionary.
40
+
41
+ This is for testing only.
42
+ """
43
+
44
+ def __init__(self) -> None:
45
+ self.passwords: dict[tuple[str, str], str] = {}
46
+
47
+ def priority(self) -> int: # pragma: no cover
48
+ return 1
49
+
50
+ def set_password(self, service_name: str, username: str, password: str) -> None:
51
+ self.passwords[(service_name, username)] = password
52
+
53
+ def get_password(self, service_name: str, username: str) -> str | None:
54
+ return self.passwords.get((service_name, username))
55
+
56
+ # This function isn't currently used as part of the tests, but we
57
+ # need it to construct an instance of KeyringBackend.
58
+ def delete_password(
59
+ self, service_name: str, username: str
60
+ ) -> None: # pragma: no cover
61
+ del self.passwords[(service_name, username)]
62
+
63
+
64
+ __all__ = ["get_required_password"]
File without changes
@@ -0,0 +1,64 @@
1
+ """
2
+ Some helper methods for writing type-safe Python.
3
+ """
4
+
5
+ import functools
6
+ import json
7
+ import pathlib
8
+ from typing import Any, Hashable, TypeVar
9
+
10
+ from pydantic import ConfigDict, TypeAdapter
11
+
12
+
13
+ T = TypeVar("T")
14
+
15
+
16
+ @functools.cache
17
+ def _get_validator(model: type[T]) -> TypeAdapter[T]:
18
+ """
19
+ Get the validator for a given type. This is a moderately expensive
20
+ process, so we cache the result -- we only need to create the
21
+ validator once for each type.
22
+ """
23
+ try:
24
+ model.__pydantic_config__ = ConfigDict(extra="forbid") # type: ignore
25
+ except AttributeError:
26
+ pass
27
+
28
+ return TypeAdapter(model)
29
+
30
+
31
+ def validate_type(t: Any, *, model: type[T]) -> T:
32
+ """
33
+ Check that some data matches a given type.
34
+
35
+ We use this to e.g. check that the structured data we receive from
36
+ Wikimedia matches our definitions, so we can use the data in our
37
+ type-checked Python.
38
+
39
+ See https://stackoverflow.com/a/77386216/1558022
40
+ """
41
+ # This is to fix an issue from the type checker:
42
+ #
43
+ # Argument 1 to "__call__" of "_lru_cache_wrapper"
44
+ # has incompatible type "type[T]"; expected "Hashable"
45
+ #
46
+ assert isinstance(model, Hashable)
47
+
48
+ validator = _get_validator(model)
49
+
50
+ return validator.validate_python(t, strict=True)
51
+
52
+
53
+ def read_typed_json(path: pathlib.Path | str, *, model: type[T]) -> T:
54
+ """
55
+ Read a JSON file and validate that its contents contain the
56
+ correct type.
57
+ """
58
+ with open(path) as in_file:
59
+ t = json.load(in_file)
60
+
61
+ return validate_type(t, model=model)
62
+
63
+
64
+ __all__ = ["validate_type", "read_typed_json"]
@@ -0,0 +1,78 @@
1
+ """
2
+ Some utilities for working with XML in a type-safe way.
3
+ """
4
+
5
+ import xml.etree.ElementTree as ET
6
+
7
+
8
+ def find_required_elem(elem: ET.Element, *, path: str) -> ET.Element:
9
+ """
10
+ Find the first subelement matching ``path``, or throw if absent.
11
+ """
12
+ # We use this when we're parsing responses from the Flickr API, and
13
+ # there are certain elements we know should always be present in responses.
14
+ #
15
+ # e.g. we know that photos always have a <title>, so we could write:
16
+ #
17
+ # photo_elem.find(".//title")
18
+ #
19
+ # But the type checker only knows that ``find()`` returns Optional[Element] --
20
+ # it doesn't know that this path should always be present in the response.
21
+ #
22
+ # If we call it from this function instead:
23
+ #
24
+ # find_required(photo_elem, path=".//title")
25
+ #
26
+ # Then the type checker can see that it returns a well-defined Element,
27
+ # and it's happy for us to use it without checking in the rest of the code.
28
+ matching_elem = elem.find(path=path)
29
+
30
+ if matching_elem is None:
31
+ raise ValueError(f"Could not find required match for {path!r} in {elem!r}")
32
+
33
+ return matching_elem
34
+
35
+
36
+ def find_required_text(elem: ET.Element, *, path: str) -> str:
37
+ """
38
+ Find the text of the first element matching ``path``, or throw if absent.
39
+ """
40
+ # We use this when we're parsing responses from the Flickr API, and
41
+ # there are certain elements we know should always be present and have text.
42
+ #
43
+ # e.g. we know that users always have a <id> with some text, so we could write:
44
+ #
45
+ # user_elem.find(".//id")
46
+ #
47
+ # But the type checker only knows that ``find()`` returns Optional[Element] --
48
+ # it doesn't know that this path should always be present in the response.
49
+ #
50
+ # If we call it from this function instead:
51
+ #
52
+ # find_required_text(user_elem, path=".//id")
53
+ #
54
+ # Then the type checker can see that it returns a well-defined Element,
55
+ # and it's happy for us to use it without checking in the rest of the code.
56
+ matching_elem = find_required_elem(elem, path=path)
57
+ text = matching_elem.text
58
+
59
+ if text is None:
60
+ raise ValueError(f"Could not find required text in {matching_elem}")
61
+
62
+ return text
63
+
64
+
65
+ def find_optional_text(elem: ET.Element, *, path: str) -> str | None:
66
+ """
67
+ Find the text of the first element matching ``path``, or return None
68
+ if the element is missing, has no text, or has empty text.
69
+ """
70
+ matching_elem = elem.find(path=path)
71
+
72
+ if matching_elem is None:
73
+ return None
74
+
75
+ return matching_elem.text or None
76
+
77
+
78
+ __all__ = ["find_required_elem", "find_required_text", "find_optional_text"]
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.1
2
+ Name: silver-nitrate
3
+ Version: 1.0.0
4
+ Summary: Python utilities used by the Flickr Foundation
5
+ Author-email: Flickr Foundation <hello@flickr.org>
6
+ Maintainer-email: Alex Chan <alex@flickr.org>
7
+ Project-URL: Homepage, https://github.com/Flickr-Foundation/silver-nitrate
8
+ Project-URL: Changelog, https://github.com/Flickr-Foundation/silver-nitrate/blob/main/CHANGELOG.md
9
+ Keywords: flickr
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.12
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE-APACHE
17
+ License-File: LICENSE-MIT
18
+
19
+ # silver-nitrate
20
+
21
+ This is a collection of Python utilities used by [the Flickr Foundation](https://www.flickr.org/).
22
+ It allows us to share certain functions and common code across all our projects.
23
+
24
+ Think of it as a souped-up version of `utils.py`.
25
+
26
+ This library is primarily for our use, but the code is fairly generic and may well be useful in other projects.
27
+ If you want to use it, copy/paste the code (and the associated tests!) into your own project rather than adding a dependency on this library.
28
+
29
+ <figure>
30
+ <a href="https://www.flickr.com/photos/podsville/3912488857">
31
+ <img src="https://live.staticflickr.com/3438/3912488857_78a5103b69_c_d.jpg">
32
+ </a>
33
+ <figcaption>
34
+ <em>Builder's Photo of 2-8-0 Locomotive No 1402 "James Archbald," built in 1930 by the Delaware & Hudson Railroad.</em>
35
+ Scan of a silver-halide photo print.
36
+ Photo from Bill Harrison <a href="https://www.flickr.com/photos/podsville/3912488857">on Flickr</a>.
37
+ </figcaption>
38
+ </figure>
39
+
40
+ ## What's in a name?
41
+
42
+ I wanted to pick a name that was:
43
+
44
+ 1. More interesting than "utils"
45
+ 2. Had a connection to photography
46
+ 3. Wasn't taken on PyPI
47
+
48
+ Silver nitrate was a key chemical in the early days of photography, especially in the 19th and early 20th centuries.
49
+
50
+ Photographers would coat glass plates with a mixture of chemicals, including silver nitrate.
51
+ Because silver nitrate reacts when exposed to light, when you put the plate in a camera and open the shutter, different areas would react differently to create an image on the plate.
52
+ You could then develop this plate into a photograph.
53
+
54
+ This code is key to our work at the Flickr Foundation, so I thought it was a fitting name.
55
+
56
+ ## Development
57
+
58
+ If you want to make changes to the library, there are instructions in [CONTRIBUTING.md](./CONTRIBUTING.md).
59
+
60
+ ## License
61
+
62
+ This project is dual-licensed as Apache-2.0 and MIT.
@@ -0,0 +1,20 @@
1
+ LICENSE-APACHE
2
+ LICENSE-MIT
3
+ README.md
4
+ pyproject.toml
5
+ src/nitrate/__init__.py
6
+ src/nitrate/cassettes.py
7
+ src/nitrate/json.py
8
+ src/nitrate/passwords.py
9
+ src/nitrate/py.typed
10
+ src/nitrate/types.py
11
+ src/nitrate/xml.py
12
+ src/silver_nitrate.egg-info/PKG-INFO
13
+ src/silver_nitrate.egg-info/SOURCES.txt
14
+ src/silver_nitrate.egg-info/dependency_links.txt
15
+ src/silver_nitrate.egg-info/top_level.txt
16
+ tests/test_cassettes.py
17
+ tests/test_json.py
18
+ tests/test_passwords.py
19
+ tests/test_types.py
20
+ tests/test_xml.py
@@ -0,0 +1,69 @@
1
+ import httpx
2
+ import pytest
3
+ from vcr.cassette import Cassette
4
+
5
+ from nitrate.cassettes import get_cassette_name
6
+
7
+
8
+ def test_creates_cassette(cassette_name: str) -> None:
9
+ assert cassette_name == "test_creates_cassette.yml"
10
+
11
+
12
+ @pytest.mark.parametrize(
13
+ ["expected_cassette_name"],
14
+ [
15
+ pytest.param("test_creates_parametrized_cassette[test1].yml", id="test1"),
16
+ pytest.param("test_creates_parametrized_cassette[test2].yml", id="test2"),
17
+ pytest.param("test_creates_parametrized_cassette[test3].yml", id="test3"),
18
+ ],
19
+ )
20
+ def test_creates_parametrized_cassette(
21
+ cassette_name: str, expected_cassette_name: str
22
+ ) -> None:
23
+ assert cassette_name == expected_cassette_name
24
+
25
+
26
+ class TestCassetteNameInClass:
27
+ def test_prefixes_class_name_to_cassette(self, cassette_name: str) -> None:
28
+ assert (
29
+ cassette_name
30
+ == "TestCassetteNameInClass.test_prefixes_class_name_to_cassette.yml"
31
+ )
32
+
33
+ @pytest.mark.parametrize(
34
+ ["expected_cassette_name"],
35
+ [
36
+ pytest.param(
37
+ "TestCassetteNameInClass.test_prefixes_name_with_parametrized_cassette[test1].yml",
38
+ id="test1",
39
+ ),
40
+ pytest.param(
41
+ "TestCassetteNameInClass.test_prefixes_name_with_parametrized_cassette[test2].yml",
42
+ id="test2",
43
+ ),
44
+ pytest.param(
45
+ "TestCassetteNameInClass.test_prefixes_name_with_parametrized_cassette[test3].yml",
46
+ id="test3",
47
+ ),
48
+ ],
49
+ )
50
+ def test_prefixes_name_with_parametrized_cassette(
51
+ self, cassette_name: str, expected_cassette_name: str
52
+ ) -> None:
53
+ assert cassette_name == expected_cassette_name
54
+
55
+
56
+ @pytest.mark.parametrize("url", ["https://example.com"])
57
+ def test_throws_if_bad_cassette_name(url: str, request: pytest.FixtureRequest) -> None:
58
+ with pytest.raises(ValueError, match="Illegal characters in VCR cassette name"):
59
+ get_cassette_name(request)
60
+
61
+
62
+ def test_creates_cassette_in_fixture_dir(vcr_cassette: Cassette) -> None:
63
+ resp = httpx.get("https://example.com")
64
+ resp.raise_for_status()
65
+
66
+ assert (
67
+ vcr_cassette._path
68
+ == "tests/fixtures/cassettes/test_creates_cassette_in_fixture_dir.yml"
69
+ )
@@ -0,0 +1,16 @@
1
+ import datetime
2
+ import json
3
+
4
+ from nitrate.json import DatetimeDecoder, DatetimeEncoder
5
+
6
+
7
+ def test_can_json_round_trip() -> None:
8
+ d = {
9
+ "label": "an interesting time",
10
+ "time": datetime.datetime(2001, 2, 3, 4, 5, 6),
11
+ }
12
+
13
+ json_string = json.dumps(d, cls=DatetimeEncoder)
14
+ parsed_json_string = json.loads(json_string, cls=DatetimeDecoder)
15
+
16
+ assert parsed_json_string == d
@@ -0,0 +1,18 @@
1
+ import keyring
2
+ import pytest
3
+
4
+ from nitrate.passwords import InMemoryKeyring, get_required_password
5
+
6
+
7
+ class TestGetRequiredPassword:
8
+ def test_gets_existing_password(self) -> None:
9
+ keyring.set_keyring(InMemoryKeyring())
10
+ keyring.set_password("flickr", "api_key", "12345")
11
+
12
+ assert get_required_password("flickr", "api_key") == "12345"
13
+
14
+ def test_throws_if_password_does_not_exist(self) -> None:
15
+ keyring.set_keyring(InMemoryKeyring())
16
+
17
+ with pytest.raises(RuntimeError, match="Could not retrieve password"):
18
+ get_required_password("flickr", "api_key")
@@ -0,0 +1,54 @@
1
+ import pathlib
2
+ from typing import Any, TypedDict
3
+
4
+ import pytest
5
+ from pydantic import ValidationError
6
+
7
+ from nitrate.types import read_typed_json, validate_type
8
+
9
+
10
+ class Shape(TypedDict):
11
+ color: str
12
+ sides: int
13
+
14
+
15
+ @pytest.mark.parametrize(
16
+ "data",
17
+ [
18
+ {"color": "red"},
19
+ {"sides": 4},
20
+ {"color": "red", "sides": "four"},
21
+ {"color": (255, 0, 0), "sides": 4},
22
+ {"color": "red", "sides": 4, "angle": 36},
23
+ ],
24
+ )
25
+ def test_validate_type_flags_incorrect_data(data: Any) -> None:
26
+ with pytest.raises(ValidationError):
27
+ validate_type(data, model=Shape)
28
+
29
+
30
+ def test_validate_type_allows_valid_data() -> None:
31
+ validate_type({"color": "red", "sides": 4}, model=Shape)
32
+
33
+
34
+ def test_validate_type_supports_builtin_types() -> None:
35
+ validate_type([1, 2, 3], model=list[int])
36
+
37
+
38
+ def test_read_typed_json_allows_valid_data(tmp_path: pathlib.Path) -> None:
39
+ json_path = tmp_path / "data.json"
40
+
41
+ with open(json_path, "w") as out_file:
42
+ out_file.write("[1, 2, 3]")
43
+
44
+ assert read_typed_json(json_path, model=list[int]) == [1, 2, 3]
45
+
46
+
47
+ def test_read_typed_json_flags_invalid_data(tmp_path: pathlib.Path) -> None:
48
+ json_path = tmp_path / "data.json"
49
+
50
+ with open(json_path, "w") as out_file:
51
+ out_file.write("[1, 2, 3]")
52
+
53
+ with pytest.raises(ValidationError):
54
+ read_typed_json(json_path, model=dict[str, str])
@@ -0,0 +1,54 @@
1
+ import xml.etree.ElementTree as ET
2
+
3
+ import pytest
4
+
5
+ from nitrate.xml import find_required_elem, find_required_text, find_optional_text
6
+
7
+
8
+ XML = ET.fromstring(
9
+ """
10
+ <?xml version="1.0" encoding="utf-8" ?>
11
+ <greeting>
12
+ <english>Hello world</english>
13
+ <french/>
14
+ <hungarian></hungarian>
15
+ </greeting>""".strip()
16
+ )
17
+
18
+
19
+ def test_find_required_elem() -> None:
20
+ english = find_required_elem(XML, path=".//english")
21
+ assert english is not None
22
+ assert english.text == "Hello world"
23
+
24
+
25
+ def test_find_required_elem_throws_if_cannot_find_element() -> None:
26
+ with pytest.raises(ValueError, match="Could not find required match"):
27
+ find_required_elem(XML, path=".//german")
28
+
29
+
30
+ def test_find_required_text() -> None:
31
+ assert find_required_text(XML, path=".//english") == "Hello world"
32
+
33
+
34
+ def test_find_required_text_throws_if_finds_element_without_text() -> None:
35
+ with pytest.raises(ValueError, match="Could not find required text"):
36
+ find_required_text(XML, path=".//french")
37
+
38
+
39
+ def test_find_required_text_throws_if_cannot_find_element() -> None:
40
+ with pytest.raises(ValueError, match="Could not find required match"):
41
+ find_required_text(XML, path=".//german")
42
+
43
+
44
+ @pytest.mark.parametrize(
45
+ ["path", "expected"],
46
+ [
47
+ ("english", "Hello world"),
48
+ ("french", None),
49
+ ("german", None),
50
+ ("hungarian", None),
51
+ ],
52
+ )
53
+ def test_find_optional_text(path: str, expected: str | None) -> None:
54
+ assert find_optional_text(XML, path=path) == expected