├── .flake8
├── .github
└── workflows
│ └── ci.yml
├── .gitignore
├── .readthedocs.yml
├── CHANGELOG.md
├── COPYING
├── MANIFEST.in
├── Makefile
├── README.rst
├── VERSION
├── docs
├── _static
│ └── .gitignore
├── caches.rst
├── common_patterns.rst
├── compression_and_serialisation.rst
├── conf.py
├── index.rst
├── keys.rst
└── rationale.rst
├── make.bat
├── mypy.ini
├── pyappcache
├── __init__.py
├── cache.py
├── compression.py
├── fs.py
├── keys.py
├── memcache.py
├── py.typed
├── redis.py
├── serialisation
│ ├── __init__.py
│ ├── core.py
│ └── pandas.py
├── sqlite_lru.py
└── util
│ ├── __init__.py
│ └── requests.py
├── pytest.ini
├── setup.py
├── tests
├── __init__.py
├── conftest.py
├── test-data
│ └── stock-exchanges.parquet
├── test_caches.py
├── test_compression.py
├── test_keys.py
├── test_memcache.py
├── test_namespacing.py
├── test_redis.py
├── test_requests.py
├── test_serialisation.py
├── test_sqlite_lru.py
└── utils.py
└── tox.ini
/.flake8:
--------------------------------------------------------------------------------
1 | [flake8]
2 | max-line-length = 88
3 | exclude=.mypy_cache,__pycache__,pyappcache.egg-info,build,dist,.tox,.coverage,htmlcov
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 | runs-on: ubuntu-latest
8 | strategy:
9 | max-parallel: 4
10 | matrix:
11 | python-version: [3.8, 3.9, "3.10", "3.11", "3.12"]
12 |
13 | services:
14 | redis:
15 | image: redis
16 | ports:
17 | - 6379:6379
18 | options: --entrypoint redis-server
19 |
20 | memcached:
21 | image: memcached
22 | ports:
23 | - 11211:11211
24 | options: --entrypoint memcached
25 |
26 | steps:
27 | - uses: actions/checkout@v1
28 | - name: Set up Python ${{ matrix.python-version }}
29 | uses: actions/setup-python@v2
30 | with:
31 | python-version: ${{ matrix.python-version }}
32 | # pylibmc needs to build itself
33 | - name: Install dependencies
34 | run: |
35 | python -m pip install --upgrade pip
36 | pip install tox tox-gh-actions~=2.11.0
37 | sudo apt-get install libmemcached-dev
38 | - name: Test with tox
39 | run: tox
40 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .mypy_cache
2 | __pycache__
3 | pyappcache.egg-info
4 | build
5 | dist
6 | .tox
7 | .coverage
8 | htmlcov
--------------------------------------------------------------------------------
/.readthedocs.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | version: 2
4 |
5 | python:
6 | version: 3.7
7 | install:
8 | - method: pip
9 | path: .
10 | extra_requirements:
11 | - tests
12 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## 0.10.0
4 | ### Added
5 |
6 | - A new FilesystemCache
7 | - Added a new serialiser which uses Parquet instead of pickle for Pandas
8 | dataframes: `pyappcache.serialisation.pandas.DataFrameAwareSerialiser`.
9 | - Support for Python 3.12
10 | - A new `BinaryFileSerialiser`
11 |
12 | ### Changed
13 |
14 | - Caches now work on buffers internally, rather than strs
15 | - This is a breaking change for compressors and serialisers
16 | - This seems to work much better for larger values (eg dataframes, csv files,
17 | etc)
18 | - SqliteCache will now use [incremental blob
19 | I/O](https://www.sqlite.org/c3ref/blob.html) where possible (eg Python 3.11+)
20 | - Fixed an issue with the default prefix being "pyappache"
21 | - Sort out CacheControlProxy
22 |
23 | ### Removed
24 |
25 | - Support for Python 3.7
26 |
27 | ## 0.9.1 - 2022-12-08
28 |
29 | ### Added
30 |
31 | - `prefix` can be passed as an arg to `Cache.__init__`
32 | - Support up to Python 3.11
33 |
34 | ### Changed
35 |
36 | - Added a better repr for `SimpleStringKey`
37 | - Fixed two issues in sqlite where expiry and eviction were not correct
38 |
39 | ### Removed
40 |
41 | - Support for Python 3.6
42 |
43 | ## 0.9 - 2021-03-01
44 |
45 | ### Added
46 |
47 | - Improved documentation greatly (and put it on RTD)
48 | - GPLv3 license
49 |
50 | ### Changed
51 |
52 | - Change the Key classes, a breaking change
53 |
54 | ### Removed
55 |
56 | ## 0.2 - 2021-01-14
57 |
58 | ### Added
59 | - Support for operating as a read-through/write-through cache
60 | - `get_via` (update-on-read)
61 | - `set_via` (update-on-write)
62 | - Key "namespacing" (documentation to follow)
63 |
64 | ### Changed
65 | - pylibmc and redis are now optional dependencies
66 | - eg install `pyappcache[memcache]` or `pyappcache[redis]` to require them
67 | - Default cache prefix is now just "pyappcache" and slashes are added when building raw keys
68 | - The required API surface of caches has been reduced further
69 | - MemcacheCache will retry exactly once when pylibmc raises a ConnectionError
70 | - in order to be robust against memcache restarts
71 |
72 | ### Removed
73 | - repr no longer defined on GenericStringKey
74 |
75 | ## 0.1 - 2020-07-15
76 |
77 | - First version
78 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include COPYING
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line, and also
5 | # from the environment for the first two.
6 | SPHINXOPTS ?=
7 | SPHINXBUILD ?= sphinx-build
8 | SOURCEDIR = source
9 | BUILDDIR = build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
21 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | pyappcache
2 | ==========
3 |
4 | Pyappcache is a library to make it easier to use application-level
5 | caching in Python.
6 |
7 | - Allows putting arbitrary Python objects into the cache
8 | - Uses PEP484 type hints to help you typecheck cache return values
9 | - Supports Memcache, Redis and SQLite
10 | - Supports working as a "read-through" and "write-through" cache
11 | - Native support for key `"namespacing" `__
12 | - Provides a few handy extras
13 |
14 | - A plugin for the
15 | `cachecontrol `__ library
16 | so you can also use it as an HTTP cache with
17 | `requests `__
18 |
19 | A simple example
20 | ----------------
21 |
22 | .. code:: python
23 |
24 | from datetime import date
25 |
26 | from pyappcache.redis import RedisCache
27 | from pyappcache.keys import Key, SimpleStringKey
28 |
29 | cache = RedisCache()
30 |
31 | # Annotate the type here to let mypy know this key is used for dates
32 | key: Key[date] = SimpleStringKey("mifid start date")
33 | cache.set(key, date(2018, 1, 3), ttl_seconds=3600)
34 |
35 | ... # later...
36 |
37 | # This variable's type will be inferred as datetime.date
38 | special_date = cache.get(key)
39 |
40 |
41 | How it compares to alternatives
42 | -------------------------------
43 |
44 | Using the redis/memcache/sqlite client directly
45 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
46 |
47 | - Explicit key objects allow for type inference and encapsulation of keying
48 | - Keys are prefix to help prevent collisions
49 | - Optional, pluggable, compression
50 | - Hopefully the overhead is small (not yet tested!)
51 | - Portable between redis/memcache/sqlite, etc
52 |
53 | dogpile.cache
54 | ~~~~~~~~~~~~~
55 |
56 | - Explicit key objects allow for type inference and encapsulation of keying
57 | - dogpile.cache provides locking, pyappcache does not
58 | - Reduced temptation to use the problematic decorator pattern
59 | - This often causes import order problems as you need to have your cache at import time
60 | - Pyappache doesn't provide DBM/file backends, SQLite instead
61 |
--------------------------------------------------------------------------------
/VERSION:
--------------------------------------------------------------------------------
1 | 0.10.0
--------------------------------------------------------------------------------
/docs/_static/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/calpaterson/pyappcache/f4bff4f8d522c6103e378be32b97e35bff116f36/docs/_static/.gitignore
--------------------------------------------------------------------------------
/docs/caches.rst:
--------------------------------------------------------------------------------
1 | Caches
2 | ======
3 |
4 | The standard interface
5 | ----------------------
6 |
7 | Pyappcache supports multiple different cache backends, all with the same
8 | interface. No matter whether you're using Redis, Memcache or the SQLiteCache
9 | you will use the same interface:
10 |
11 | .. autoclass:: pyappcache.cache.Cache
12 | :members: get, set, invalidate, clear, set_by_str, get_by_str,
13 | invalidate_by_str, prefix, compressor, serialiser
14 |
15 |
16 |
17 | Redis
18 | ~~~~~
19 |
20 | .. autoclass:: pyappcache.redis.RedisCache
21 | :members: __init__
22 |
23 | Memcache
24 | ~~~~~~~~
25 |
26 | .. autoclass:: pyappcache.memcache.MemcacheCache
27 | :members: __init__
28 |
29 | SqliteCache
30 | ~~~~~~~~~~~
31 |
32 | Pyappcache also includes a Sqlite-based implementation of an LRU cache. This
33 | can be handy for scripts.
34 |
35 | .. autoclass:: pyappcache.sqlite_lru.SqliteCache
36 | :members: __init__
37 |
38 | .. autofunction:: pyappcache.sqlite_lru.get_in_memory_conn
39 |
40 | See :ref:`local sqlite file as cache` for the common pattern of storing the
41 | cache in a file alongside a script.
42 |
43 | Implementing support for a custom cache backend
44 | -----------------------------------------------
45 |
46 | If you use something else as a cache (a filesystem, some SQL database, dbm)
47 | implementing a custom driver is not too hard.
48 |
49 | You need only subclass :class:`~pyappcache.cache.Cache` and implement four
50 | abstract methods:
51 |
52 | .. automethod:: pyappcache.cache.Cache.get_raw
53 |
54 | .. automethod:: pyappcache.cache.Cache.set_raw
55 |
56 | .. automethod:: pyappcache.cache.Cache.invalidate_raw
57 |
58 | .. automethod:: pyappcache.cache.Cache.clear
59 | :noindex:
60 |
61 | :class:`~pyappcache.cache.Cache` is implemented entirely in terms of these four
62 | methods so once you implement these, you get everything else "for free".
63 |
--------------------------------------------------------------------------------
/docs/common_patterns.rst:
--------------------------------------------------------------------------------
1 | Common patterns
2 | ===============
3 |
4 | Using pyappcache to provide caching for ``requests``
5 | ----------------------------------------------------
6 |
7 | Pyappcache provides some added extras to allow it to be used as a cache for the
8 | popular `requests `_ library when
9 | used in conjunction with the `CacheControl
10 | `_ library.
11 |
12 | CacheControl provides the HTTP caching logic and Pyappcache provides the cache
13 | backends.
14 |
15 | .. autoclass:: pyappcache.util.requests.CacheControlProxy
16 |
17 | .. code:: python
18 |
19 | import requests
20 | import cachecontrol
21 | from pyappcache.redis import RedisCache
22 | from pyappcache.util.requests import CacheControlProxy
23 |
24 | # Create a Cache instance around Redis
25 | cache = RedisCache()
26 |
27 | # Create the proxy, which implements CacheControl's desired API
28 | cc_proxy = CacheControlProxy(cache)
29 |
30 | # Create the session
31 | cached_session = cachecontrol.CacheControl(
32 | requests.Session(),
33 | cache=cc_proxy
34 | )
35 |
36 | # Make the request - first time not cached
37 | cached_session.get("http://calpaterson.com")
38 |
39 | # Make the request - seen it before so reads from cache
40 | cached_session.get("http://calpaterson.com")
41 |
42 |
43 | Storing your cache in a local sqlite file
44 | -----------------------------------------
45 |
46 | .. _local sqlite file as cache:
47 |
48 | Sometimes it's handy to have the cache stored on disk. This is not as fast as
49 | in-memory but can be handy if you need a way to persist cache entries but
50 | aren't able to run a "proper" cache server like memcache or redis.
51 |
52 | .. code:: python
53 |
54 | import sqlite3
55 | from pyappcache.sqlite_lru import SqliteCache
56 |
57 | sqlite_db = sqlite3.connect("my_cache.sqlite3")
58 | cache = SqliteCache(connection=sqlite_db)
59 |
--------------------------------------------------------------------------------
/docs/compression_and_serialisation.rst:
--------------------------------------------------------------------------------
1 | Compression and serialisation
2 | ==============================
3 |
4 | Pyappcache offers pluggable compression and serialisation so you can choose
5 | what is used to compress your cache values and how they are serialised. The
6 | defaults are gzip and pickle.
7 |
8 | Compression
9 | -----------
10 |
11 | .. autoclass:: pyappcache.compression.Compressor
12 | :members: is_compressed, compress, decompress
13 |
14 | .. autoclass:: pyappcache.compression.GZIPCompressor
15 | :members: level
16 |
17 |
18 | Serialisation
19 | -------------
20 |
21 | .. autoclass:: pyappcache.serialisation.Serialiser
22 | :members: dumps, loads
23 |
24 | .. autoclass:: pyappcache.serialisation.PickleSerialiser
25 | :members: pickle_protocol
26 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # Configuration file for the Sphinx documentation builder.
2 | #
3 | # This file only contains a selection of the most common options. For a full
4 | # list see the documentation:
5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html
6 |
7 | # -- Path setup --------------------------------------------------------------
8 |
9 | # If extensions (or modules to document with autodoc) are in another directory,
10 | # add these directories to sys.path here. If the directory is relative to the
11 | # documentation root, use os.path.abspath to make it absolute, like shown here.
12 | #
13 | # import os
14 | # import sys
15 | # sys.path.insert(0, os.path.abspath('.'))
16 |
17 |
18 | # -- Project information -----------------------------------------------------
19 |
20 | project = "pyappcache"
21 | copyright = "2020, Cal Paterson"
22 | author = "Cal Paterson"
23 |
24 |
25 | # -- General configuration ---------------------------------------------------
26 |
27 | # Add any Sphinx extension module names here, as strings. They can be
28 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
29 | # ones.
30 | extensions = [
31 | "sphinx.ext.autodoc",
32 | "sphinx_autodoc_typehints",
33 | ]
34 |
35 | # Add any paths that contain templates here, relative to this directory.
36 | templates_path = ["_templates"]
37 |
38 | # List of patterns, relative to source directory, that match files and
39 | # directories to ignore when looking for source files.
40 | # This pattern also affects html_static_path and html_extra_path.
41 | exclude_patterns = [] # type: ignore
42 |
43 |
44 | # -- Options for HTML output -------------------------------------------------
45 |
46 | # The theme to use for HTML and HTML Help pages. See the documentation for
47 | # a list of builtin themes.
48 | #
49 | html_theme = "alabaster"
50 |
51 | # Add any paths that contain custom static files (such as style sheets) here,
52 | # relative to this directory. They are copied after the builtin static files,
53 | # so a file named "default.css" will overwrite the builtin "default.css".
54 | html_static_path = ["_static"]
55 |
56 | master_doc = "index"
57 |
58 | autodoc_member_order = "bysource"
59 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | pyappcache documentation
2 | ========================
3 |
4 | pyappcache is a Python library for using volatile caches such as memcache or
5 | redis.
6 |
7 | A minimal example using Redis
8 | -----------------------------
9 |
10 | .. code:: python
11 |
12 | from datetime import date
13 |
14 | from pyappcache.redis import RedisCache
15 | from pyappcache.keys import Key, SimpleStringKey
16 |
17 | cache = RedisCache()
18 |
19 | # Annotate the type here to let mypy know this key is used for dates
20 | key: Key[date] = SimpleStringKey("mifid start date")
21 | cache.set(key, date(2018, 1, 3), ttl_seconds=3600)
22 |
23 | ... # later...
24 |
25 | # This variable's type will be inferred as datetime.date
26 | special_date = cache.get(key)
27 |
28 | The above code:
29 |
30 | - creates a new instance of pyappcache's `RedisCache` class
31 | - creates a new key object
32 | - sets that key's value to `date(2018, 1, 3)`
33 | - and then (later) that value can be retrieved *with the right type inference*
34 |
35 |
36 | Reference documentation
37 | -----------------------
38 |
39 | .. toctree::
40 | :maxdepth: 3
41 |
42 | caches
43 | keys
44 | compression_and_serialisation
45 | common_patterns
46 | rationale
47 |
48 |
49 | Indices and tables
50 | ==================
51 |
52 | * :ref:`genindex`
53 | * :ref:`modindex`
54 | * :ref:`search`
55 |
--------------------------------------------------------------------------------
/docs/keys.rst:
--------------------------------------------------------------------------------
1 | Keys
2 | ====
3 |
4 | Why Key classes?
5 | ----------------
6 |
7 | The advantage of making cache keys first class objects:
8 |
9 | #. Encapsulate all the logic for calculating the key in one place
10 | #. Allow for typechecking return values from the cache
11 | #. Make it possible to control compression, namespacing, etc in one place
12 |
13 | A note on "key paths"
14 | ^^^^^^^^^^^^^^^^^^^^^
15 |
16 | Pyappcache is designed around the idea of "key paths" that are predictable and
17 | similar to unix paths, such as `users/54/likes`, which might store user number
18 | 54's likes. Predictable key paths aid debugging - you can always guess where
19 | to look when using the cache separately from pyappcache.
20 |
21 | Pyappcache caches will also *prefix* key paths with some custom key path, to
22 | allow multiple different uses of the same cache without each clobbering the
23 | other's namespace.
24 |
25 | How to create your own key classes
26 | ----------------------------------
27 |
28 | Three different ways, from most straightforward to most complex.
29 |
30 | Option 1: Simple string keys
31 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
32 |
33 | If you just want to use a string as your key, you can use
34 | :class:`~pyappcache.keys.SimpleStringKey` directly.
35 |
36 | .. autoclass:: pyappcache.keys.SimpleStringKey
37 | :members: __init__
38 |
39 | .. code:: python
40 |
41 | from pyappcache.keys import SimpleStringKey
42 |
43 | death_star_location = SimpleStringKey("death-star-location")
44 | cache.set(death_star_location, "near alderaan")
45 |
46 | ... # later...
47 | where_is_it_now = cache.get(death_star_location)
48 |
49 | Option 2: Subclasses of BaseKey
50 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
51 |
52 | If you want to have something more complicated, you can often get started by
53 | subclassing :class:`~pyappcache.keys.BaseKey`.
54 |
55 | .. autoclass:: pyappcache.keys.BaseKey
56 | :members: cache_key_segments
57 |
58 | This abstract base class is designed to make it quick as possible to create a
59 | new key class - just override `cache_key_segments` and you're ready to go.
60 |
61 | .. code:: python
62 |
63 | from pyappcache.keys import BaseKey
64 | from some_orm_layer import BigORMObj
65 |
66 | class BigORMObjKey(BaseKey):
67 | def __init__(self, big_orm_obj):
68 | self.big_orm_obj = big_orm_obj
69 |
70 | def cache_key_segments(self):
71 | return str(big_orm_obj.id)
72 |
73 | Option 3: Create your own Keys from scratch
74 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
75 |
76 | If you want full flexibilty you need only define three special methods to allow
77 | any object to act as a `Key`.
78 |
79 | .. autoclass:: pyappcache.keys.Key
80 | :members: namespace_key, should_compress, cache_key_segments
81 |
--------------------------------------------------------------------------------
/docs/rationale.rst:
--------------------------------------------------------------------------------
1 | Rationale
2 | =========
3 |
4 | Pyappcache takes a slightly different approach to other cache libraries.
5 |
6 | First class key objects
7 | -----------------------
8 |
9 | In pyappcache, keys are first class objects - though you can use strings too if
10 | you prefer.
11 |
12 | Make keys a first class object to make it easier to centralise logic around
13 | keying and avoid typos and other common mistakes that arise when using strings
14 | as keys.
15 |
16 | Support multiple caches
17 | -----------------------
18 |
19 | Redis and Memcache are both popular volatile caches. Pyappcache also includes
20 | an implementation using Sqlite can be useful in some scenarios.
21 |
22 | It's also easy(ish) to implement support for a new cache.
23 |
24 | Support type hints
25 | ------------------
26 |
27 | Pyappcache has type hinting to help catch bugs - particularly the common
28 | mistake of forgetting that the cache might return nothing!
29 |
30 | Pluggable serialisation and compression
31 | ---------------------------------------
32 |
33 | The specifics of how Python objects are turned into bytestrings is explicit and
34 | pluggable - you can provide your own compression and serialisation methods.
35 |
36 | Inspectable
37 | -----------
38 |
39 | Pyappcache generates predictable cache keys to make debugging easier - you'll
40 | be able to predict what key is generated (and if you don't know, you can ask a
41 | key object in a REPL).
42 |
--------------------------------------------------------------------------------
/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | pushd %~dp0
4 |
5 | REM Command file for Sphinx documentation
6 |
7 | if "%SPHINXBUILD%" == "" (
8 | set SPHINXBUILD=sphinx-build
9 | )
10 | set SOURCEDIR=source
11 | set BUILDDIR=build
12 |
13 | if "%1" == "" goto help
14 |
15 | %SPHINXBUILD% >NUL 2>NUL
16 | if errorlevel 9009 (
17 | echo.
18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
19 | echo.installed, then set the SPHINXBUILD environment variable to point
20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you
21 | echo.may add the Sphinx directory to PATH.
22 | echo.
23 | echo.If you don't have Sphinx installed, grab it from
24 | echo.http://sphinx-doc.org/
25 | exit /b 1
26 | )
27 |
28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
29 | goto end
30 |
31 | :help
32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
33 |
34 | :end
35 | popd
36 |
--------------------------------------------------------------------------------
/mypy.ini:
--------------------------------------------------------------------------------
1 | [mypy]
2 | python_version = 3.8
3 | exclude = ["build"]
4 |
5 | check_untyped_defs = True
6 | no_implicit_optional = True
7 | warn_unused_configs = True
8 | # currently there is a discrepency between types for requests between python
9 | # versions
10 | # warn_unused_ignores = True
11 | disallow_incomplete_defs = True
12 | warn_return_any = True
13 | strict_equality = True
14 | [mypy-setuptools]
15 | ignore_missing_imports = True
16 | [mypy-pylibmc.*]
17 | ignore_missing_imports = True
18 | [mypy-pytest.*]
19 | ignore_missing_imports = True
20 | [mypy-responses.*]
21 | ignore_missing_imports = True
22 | [mypy-cachecontrol.*]
23 | ignore_missing_imports = True
24 | [mypy-pluggy]
25 | ignore_missing_imports = True
26 | [mypy-exceptiongroup]
27 | ignore_missing_imports = True
28 | [mypy-tomli]
29 | ignore_missing_imports = True
--------------------------------------------------------------------------------
/pyappcache/__init__.py:
--------------------------------------------------------------------------------
1 | #
2 |
--------------------------------------------------------------------------------
/pyappcache/cache.py:
--------------------------------------------------------------------------------
1 | from abc import ABCMeta, abstractmethod
2 | from logging import getLogger
3 | from typing import Optional, TypeVar, Any, cast, Callable, Sequence, Mapping, IO
4 |
5 | from .compression import Compressor, GZIPCompressor
6 | from .serialisation import Serialiser, PickleSerialiser
7 | from .keys import Key, build_raw_key
8 |
9 | V = TypeVar("V")
10 |
11 |
12 | logger = getLogger(__name__)
13 |
14 |
15 | class Cache(metaclass=ABCMeta):
16 | """The standard, cross backend, interface to a cache."""
17 |
18 | DEFAULT_PREFIX = "pyappcache"
19 |
20 | def __init__(self, prefix=DEFAULT_PREFIX):
21 | #: A prefix that will be applied to cache keys to allow for multiple
22 | #: instances of this class to co-exist. Exact use varies by particular
23 | #: cache. Default is `'pyappcache'`.
24 | self.prefix = prefix
25 | #: The compressor that will be used when a key asks for compression.
26 | #: Default is gzip via :class:`.compression.GZIPCompressor`
27 | self.compressor: Compressor = GZIPCompressor()
28 | #: The serialiers that will be used to turn Python objects back and
29 | #: forth into bytes. The default serialiser is pickle, via
30 | #: :class:`.serialisation.PickleSerialiser`
31 | self.serialiser: Serialiser = PickleSerialiser()
32 |
33 | def get(self, key: Key[V]) -> Optional[V]:
34 | """Look up the value stored under a :class:`~pyappcache.keys.Key` instance"""
35 | namespace_key = key.namespace_key()
36 | if namespace_key is not None:
37 | namespace = self.lookup_namespace(namespace_key)
38 | if namespace is None:
39 | return None
40 | else:
41 | namespace = None
42 |
43 | cache_contents = self.get_raw(
44 | build_raw_key(self.prefix, key, namespace=namespace)
45 | )
46 | if cache_contents is not None:
47 | if self.compressor.is_compressed(cache_contents):
48 | cache_contents = self.compressor.decompress(cache_contents)
49 | return cast(V, self.serialiser.load(cache_contents))
50 | else:
51 | return None
52 |
53 | def get_by_str(self, key_str: str) -> Optional[Any]:
54 | """Look up the value stored under a :class:`str`.
55 |
56 | Users of this method will have to construct string keys for themselves."""
57 | cache_contents = self.get_raw(build_raw_key(self.prefix, key_str))
58 | if cache_contents is not None:
59 | if self.compressor.is_compressed(cache_contents):
60 | cache_contents = self.compressor.decompress(cache_contents)
61 | return self.serialiser.load(cache_contents)
62 | else:
63 | return None
64 |
65 | def get_via(self, key: Key[V], getter: Callable[[], V]) -> V:
66 | cache_contents = self.get(key)
67 | if cache_contents is None:
68 | new_cache_contents = getter()
69 | self.set(key, new_cache_contents)
70 | return new_cache_contents
71 | else:
72 | return cache_contents
73 |
74 | def lookup_namespace(self, key: Key) -> Optional[str]:
75 | # FIXME: is this required?
76 | namespace = self.get(key)
77 | if namespace is not None:
78 | return str(namespace)
79 | else:
80 | return None
81 |
82 | def set(self, key: Key[V], value: V, ttl_seconds: int = 0) -> None:
83 | """Set a value by :class:`~pyappcache.keys.Key`"""
84 | namespace_key = key.namespace_key() # FIXME: move this inside lookup_namespace
85 | if namespace_key is not None:
86 | namespace = self.lookup_namespace(namespace_key)
87 | if namespace is None:
88 | logger.warning("unable to set key as namespace does not exist")
89 | return None
90 | else:
91 | namespace = None
92 | as_pickle = self.serialiser.dump(value)
93 | if key.should_compress(value, as_pickle):
94 | as_bytes = self.compressor.compress(as_pickle)
95 | else:
96 | as_bytes = as_pickle
97 | self.set_raw(
98 | build_raw_key(self.prefix, key, namespace=namespace), as_bytes, ttl_seconds
99 | )
100 |
101 | def set_via(
102 | self,
103 | key: Key[V],
104 | value: V,
105 | setter: Callable[..., Any],
106 | setter_args: Sequence = (),
107 | setter_kwargs: Optional[Mapping] = None,
108 | ) -> None:
109 | if setter_kwargs is None:
110 | setter_kwargs = {}
111 | setter(*setter_args, **setter_kwargs)
112 | self.set(key, value)
113 |
114 | def set_by_str(
115 | self, key_str: str, value: V, ttl_seconds: int = 0, compress: bool = False
116 | ) -> None:
117 | """Set a value by a :class:`str`."""
118 | as_pickle = self.serialiser.dump(value)
119 | if compress:
120 | as_bytes = self.compressor.compress(as_pickle)
121 | else:
122 | as_bytes = as_pickle
123 | raw_key = build_raw_key(self.prefix, key_str)
124 | self.set_raw(
125 | raw_key,
126 | as_bytes,
127 | ttl_seconds,
128 | )
129 |
130 | def invalidate(self, key: Key[V]) -> None:
131 | """Invalidate by :class:`~pyappcache.keys.Key`.
132 |
133 | Depending on the particular implementation of invalidation this may or
134 | may not immediately free memory in the underlying cache (usually not)."""
135 | namespace_key = key.namespace_key() # FIXME: move this inside lookup_namespace
136 | if namespace_key is not None:
137 | namespace = self.lookup_namespace(namespace_key)
138 | if namespace is None:
139 | logger.warning("unable to invalidate key as namespace does not exist")
140 | return None
141 | else:
142 | namespace = None
143 | self.invalidate_raw(build_raw_key(self.prefix, key, namespace=namespace))
144 |
145 | def invalidate_by_str(self, key_str: str) -> None:
146 | self.invalidate_raw(build_raw_key(self.prefix, key_str))
147 |
148 | @abstractmethod
149 | def get_raw(self, key_str: str) -> Optional[IO[bytes]]:
150 | """Look up a value (as bytes) from a concrete key string.
151 |
152 | :param key_str: the (fully prefixed) key string to look up
153 |
154 | """
155 | pass # pragma: no cover
156 |
157 | @abstractmethod
158 | def set_raw(self, key_str: str, value_bytes: IO[bytes], ttl_seconds: int) -> None:
159 | """Set a value (as bytes) by a concrete key string.
160 |
161 | :param key_str: the (fully prefixed) key string to set.
162 | """
163 | pass # pragma: no cover
164 |
165 | @abstractmethod
166 | def invalidate_raw(self, key_str: str) -> None:
167 | """Invalidate a key by a concrete key string.
168 |
169 | :param key_str: the (fully prefixed) key string to invalidate
170 | """
171 | pass # pragma: no cover
172 |
173 | @abstractmethod
174 | def clear(self) -> None:
175 | """Remove all keys from the cache.
176 |
177 | For most caches this will remove absolutely everything from the
178 | server, so use with care.
179 |
180 | """
181 | pass # pragma: no cover
182 |
--------------------------------------------------------------------------------
/pyappcache/compression.py:
--------------------------------------------------------------------------------
1 | from io import BytesIO
2 | import shutil
3 | from typing import IO, cast
4 | import gzip
5 |
6 | from typing_extensions import Protocol
7 |
8 |
9 | class Compressor(Protocol):
10 | """The protocol for compressors to follow"""
11 |
12 | def is_compressed(self, data: IO[bytes]) -> bool:
13 | """Takes some, possibly compressed data as an argument and returns True
14 | if is has been compressed with this compressor, False otherwise."""
15 | pass # pragma: no cover
16 |
17 | def compress(self, data: IO[bytes]) -> IO[bytes]:
18 | """Compress the given bytes with this compressor"""
19 | pass # pragma: no cover
20 |
21 | def decompress(self, data: IO[bytes]) -> IO[bytes]:
22 | """Decompress the given bytes with this compressor"""
23 | pass # pragma: no cover
24 |
25 |
26 | class GZIPCompressor:
27 | """A default compressor that is gzip at level 5."""
28 |
29 | def __init__(self, level: int = 5):
30 | """
31 |
32 | :param level: The gzip compression level (default 5)"""
33 | #: Gzip compression level
34 | self.level = level
35 |
36 | def is_compressed(self, data: IO[bytes]) -> bool:
37 | head = data.read(2)
38 | data.seek(0)
39 | return head == b"\x1f\x8b"
40 |
41 | def compress(self, data: IO[bytes]) -> IO[bytes]:
42 | inner_buf = BytesIO()
43 | with gzip.GzipFile(
44 | fileobj=inner_buf, mode="w", compresslevel=self.level
45 | ) as gzip_f:
46 | shutil.copyfileobj(data, gzip_f)
47 | inner_buf.seek(0)
48 | return inner_buf
49 |
50 | def decompress(self, data: IO[bytes]) -> IO[bytes]:
51 | return cast(IO[bytes], gzip.open(data))
52 |
--------------------------------------------------------------------------------
/pyappcache/fs.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sqlite3
3 | from typing import Optional, IO, List
4 | from logging import getLogger
5 | from pathlib import Path
6 | import shutil
7 | from contextlib import closing
8 | from datetime import datetime, timedelta
9 |
10 | from dateutil.parser import parse as parse_dt
11 |
12 | from .cache import Cache
13 |
14 | logger = getLogger(__name__)
15 |
16 | CREATE_DDL = """
17 | CREATE TABLE IF NOT EXISTS pyappcache (
18 | key PRIMARY KEY,
19 | expiry NOT NULL,
20 | last_read NOT NULL,
21 | size NOT NULL
22 | );
23 | """
24 |
25 | INDEX_DDL: List[str] = [
26 | "CREATE INDEX IF NOT EXISTS idx_pyappcache_expiry ON pyappcache(expiry);",
27 | "CREATE INDEX IF NOT EXISTS idx_pyappcache_last_read ON pyappcache(last_read);",
28 | "CREATE INDEX IF NOT EXISTS idx_pyappcache_size ON pyappcache(size);",
29 | ]
30 |
31 |
32 | TOUCH_DML = """
33 | UPDATE pyappcache
34 | SET last_read = ?
35 | WHERE key = ?
36 | AND (expiry >= ? OR expiry = '-1');
37 | """
38 |
39 | SET_DML = """
40 | INSERT OR REPLACE INTO pyappcache
41 | (key, expiry, last_read, size)
42 | VALUES
43 | (?, ?, ?, ?);
44 | """
45 |
46 | GET_TTL_DQL = """
47 | SELECT expiry
48 | FROM pyappcache
49 | WHERE key = ?;
50 | """
51 |
52 | # The below SQL should be done in one step using the RETURNING clause of the
53 | # DELETE statement, but RETURNING was only added to sqlite in 3.35.0
54 | # (2021-03-12) and not everyone has it yet (including me)
55 |
56 | GET_EVICTION_COHORT_DQL = """
57 | SELECT
58 | KEY
59 | FROM (
60 | SELECT
61 | KEY,
62 | last_read,
63 | SUM(size) OVER (ORDER BY last_read DESC) AS total_size
64 | FROM pyappcache) AS t
65 | WHERE
66 | total_size > ?;
67 | """
68 |
69 | EVICT_COHORT_DML = """
70 | DELETE FROM pyappcache
71 | WHERE KEY IN (
72 | SELECT
73 | KEY
74 | FROM (
75 | SELECT
76 | KEY,
77 | last_read,
78 | SUM(size) OVER (ORDER BY last_read DESC) AS total_size
79 | FROM pyappcache) AS t
80 | WHERE
81 | total_size > ?
82 | )
83 | """
84 |
85 | CLEAR_DML = """
86 | UPDATE pyappcache SET expiry = ?;
87 | """
88 |
89 |
90 | class FilesystemCache(Cache):
91 | METADATA_DB_FILENAME = "metadata.sqlite3"
92 |
93 | # 100mb default limit
94 | DEFAULT_MAX_SIZE = 1000 * 1000 * 100
95 |
96 | def __init__(self, directory: Path, max_size_bytes: int = DEFAULT_MAX_SIZE):
97 | super().__init__()
98 | self.directory = directory
99 | self.directory.mkdir(parents=True, exist_ok=True)
100 | self.max_size_bytes = max_size_bytes
101 | self.metadata_conn = sqlite3.connect(
102 | str(self.directory / self.METADATA_DB_FILENAME)
103 | )
104 | with closing(self.metadata_conn.cursor()) as cursor:
105 | cursor.execute(CREATE_DDL)
106 | for index_ddl in INDEX_DDL:
107 | cursor.execute(index_ddl)
108 | self.metadata_conn.commit()
109 |
110 | def _make_path(self, raw_key: str) -> Path:
111 | path = self.directory / raw_key.replace("/", "_")
112 | path.parent.mkdir(parents=True, exist_ok=True)
113 | return path
114 |
115 | def get_raw(self, raw_key: str) -> Optional[IO[bytes]]:
116 | now = datetime.utcnow()
117 | with closing(self.metadata_conn.cursor()) as cursor:
118 | cursor.execute(TOUCH_DML, (now.isoformat(), raw_key, now.isoformat()))
119 | if cursor.rowcount == 0:
120 | return None
121 | self.metadata_conn.commit()
122 |
123 | path = self._make_path(raw_key)
124 | try:
125 | return path.open("rb")
126 | except FileNotFoundError:
127 | # FIXME: should handle this by expiring the key
128 | return None
129 |
130 | def set_raw(self, raw_key: str, value_bytes: IO[bytes], ttl_seconds: int) -> None:
131 | path = self._make_path(raw_key)
132 | with path.open("w+b") as fh:
133 | shutil.copyfileobj(value_bytes, fh)
134 | size = _get_fh_size(value_bytes)
135 | if ttl_seconds != 0:
136 | expiry = (datetime.utcnow() + timedelta(seconds=ttl_seconds)).isoformat()
137 | else:
138 | expiry = "-1"
139 | with closing(self.metadata_conn.cursor()) as cursor:
140 | cursor.execute(SET_DML, (raw_key, expiry, datetime.utcnow(), size))
141 | self.metadata_conn.commit()
142 | self._evict()
143 |
144 | def invalidate_raw(self, raw_key: str) -> None:
145 | # FIXME: this should be updating the metadata
146 | path = self._make_path(raw_key)
147 | path.unlink(missing_ok=True)
148 |
149 | def _evict(self) -> None:
150 | """Evict data to maintain the maximum size."""
151 | with closing(self.metadata_conn.cursor()) as cursor:
152 | cursor.execute("BEGIN;")
153 | cursor.execute(GET_EVICTION_COHORT_DQL, (self.max_size_bytes,))
154 | rs = cursor.fetchall()
155 | cursor.execute(EVICT_COHORT_DML, (self.max_size_bytes,))
156 | self.metadata_conn.commit()
157 |
158 | for row in rs:
159 | raw_key = row[0]
160 | path = self._make_path(raw_key)
161 | path.unlink(missing_ok=True)
162 |
163 | def ttl(self, key_bytes: str) -> Optional[int]:
164 | """Returns the (remaining) TTL of the given key."""
165 | now = datetime.utcnow()
166 | with closing(self.metadata_conn.cursor()) as cursor:
167 | cursor.execute(GET_TTL_DQL, (key_bytes,))
168 | row = cursor.fetchone()
169 | if row is not None:
170 | expiry = row[0]
171 | expiry_dt = parse_dt(expiry)
172 | ttl_td = expiry_dt - now
173 | return int(ttl_td.total_seconds())
174 | else:
175 | return None
176 |
177 | def clear(self) -> None:
178 | now = datetime.utcnow()
179 | past = now - timedelta(seconds=1)
180 | with closing(self.metadata_conn.cursor()) as cursor:
181 | cursor.execute(CLEAR_DML, (past.isoformat(),))
182 | self.metadata_conn.commit()
183 |
184 |
185 | def _get_fh_size(fh: IO[bytes]) -> int:
186 | """Return the size of a seekable binary filehandle."""
187 | pos = fh.tell()
188 | fh.seek(0, os.SEEK_END)
189 | size = fh.tell()
190 | fh.seek(pos)
191 | return size
192 |
--------------------------------------------------------------------------------
/pyappcache/keys.py:
--------------------------------------------------------------------------------
1 | from abc import abstractmethod, ABCMeta
2 | from typing import IO
3 |
4 | from typing import TypeVar, Sequence, Union, Optional, Any
5 | from typing_extensions import Protocol
6 |
7 | #: Key value
8 | V = TypeVar("V", contravariant=True)
9 |
10 |
11 | class Key(Protocol[V]):
12 | """The "protocol" for keys. Define the same methods as this class, and you
13 | have created a key which will work with pyappcache.
14 |
15 | """
16 |
17 | def namespace_key(self) -> "Optional[Key[Any]]":
18 | """If this is a namespaced key, this method returns the key to the
19 | namespace that should be used - otherwise None.
20 |
21 | """
22 | pass # pragma: no cover
23 |
24 | def should_compress(self, python_obj: V, as_bytes: IO[bytes]) -> bool:
25 | """This method passes the original Python object and the serialised
26 | `bytes` version of it in order to allow this method to decide whether
27 | compression should be used.
28 |
29 | This allows for this method to take Python level attributes/methods and
30 | the size of the bytestring into account when making a decision.
31 |
32 | Returns True if compression should be applied, False if not.
33 | """
34 | pass # pragma: no cover
35 |
36 | def cache_key_segments(self) -> Sequence[str]:
37 | """Return segments of the whole key path. For example `["a", "b",
38 | "c"]` - the key segments will be prepended with the Cache's own
39 | :attr:`~pyappcache.cache.Cache.prefix` and then joined with slashes,
40 | similar to unix paths."""
41 | pass # pragma: no cover
42 |
43 |
44 | class BaseKey(Key[V], metaclass=ABCMeta):
45 | """An abstract baseclass suitable (but not required) for subclassing to
46 | create many class:`~Key` instances.
47 |
48 | To use, subclass and override :meth:`~cache_key_segments`. To get
49 | progressively more functionality, you can also override
50 | :meth:`~namespace_key` and :meth:`should_compress`.
51 |
52 | """
53 |
54 | def namespace_key(self) -> Optional[Key[Any]]:
55 | return None
56 |
57 | def should_compress(self, python_obj: V, as_bytes: IO[bytes]) -> bool:
58 | return False
59 |
60 | @abstractmethod
61 | def cache_key_segments(self) -> Sequence[str]:
62 | ... # pragma: no cover
63 |
64 |
65 | class SimpleStringKey(Key[V]):
66 | """A simple, string-based Key."""
67 |
68 | def __init__(self, key_str: str):
69 | """Create a key based on a string"""
70 | self.key_str = key_str
71 |
72 | def namespace_key(self) -> Optional[Key[Any]]:
73 | return None
74 |
75 | def should_compress(self, python_obj: V, as_bytes: IO[bytes]) -> bool:
76 | return False
77 |
78 | def cache_key_segments(self) -> Sequence[str]:
79 | return [self.key_str]
80 |
81 | def __repr__(self) -> str:
82 | return f""
83 |
84 |
85 | def build_raw_key(
86 | prefix: str, key: Union[Key, str], namespace: Optional[str] = None
87 | ) -> str:
88 | """Creates a string key from a cache prefix and a key, and optionally a
89 | resolved namespace.
90 | """
91 | key_segments = [prefix]
92 | if namespace is not None:
93 | key_segments.append(namespace)
94 | if isinstance(key, str):
95 | key_segments.append(key)
96 | else:
97 | key_segments.extend(key.cache_key_segments())
98 | key_str = "/".join(key_segments)
99 | return key_str
100 |
--------------------------------------------------------------------------------
/pyappcache/memcache.py:
--------------------------------------------------------------------------------
1 | import pylibmc
2 | import io
3 |
4 | from typing import Optional, Any, IO
5 | from logging import getLogger
6 |
7 | from .cache import Cache
8 |
9 | logger = getLogger(__name__)
10 |
11 |
12 | class MemcacheCache(Cache):
13 | """An implementation of Cache for memcache.
14 |
15 | All methods in this class will retry exactly once when the underlying
16 | pylibmc client returns a ConnectionError (to be robust against memcache
17 | restarts.
18 | """
19 |
20 | def __init__(self, client: Optional[Any] = None):
21 | """
22 |
23 | :param client: A optional (pylibmc-compatible) memcache client to use."""
24 | super().__init__()
25 | if client is not None:
26 | self._mc = client
27 | else:
28 | self._mc = pylibmc.Client(["127.0.0.1"], binary=True)
29 |
30 | def get_raw(self, raw_key: str) -> Optional[IO[bytes]]:
31 | try:
32 | value = self._mc.get(raw_key)
33 | except pylibmc.ConnectionError:
34 | logger.warning("got a connection error from pylibmc, retrying once")
35 | value = self._mc.get(raw_key)
36 | if value is not None:
37 | return io.BytesIO(value)
38 | else:
39 | return None
40 |
41 | def set_raw(self, raw_key: str, value_bytes: IO[bytes], ttl: int) -> None:
42 | # FIXME: check that keys don't include control characters or whitespace
43 | # Or add a note?
44 | try:
45 | self._mc.set(raw_key, value_bytes.read(), time=ttl)
46 | return
47 | except pylibmc.ConnectionError:
48 | logger.warning("got a connection error from pylibmc, retrying once")
49 | value_bytes.seek(0)
50 | self._mc.set(raw_key, value_bytes.read(), time=ttl)
51 |
52 | def invalidate_raw(self, raw_key: str) -> None:
53 | try:
54 | self._mc.delete(raw_key)
55 | except pylibmc.ConnectionError:
56 | logger.warning("got a connection error from pylibmc, retrying once")
57 | self._mc.delete(raw_key)
58 |
59 | def clear(self) -> None:
60 | """Clear the cache.
61 |
62 | Warning: memcache doesn't have a way to list keys so this clears
63 | everything!"""
64 | logger.warning("flushing memcache!")
65 | try:
66 | self._mc.flush_all()
67 | except pylibmc.ConnectionError:
68 | logger.warning("got a connection error from pylibmc, retrying once")
69 | self._mc.flush_all()
70 |
--------------------------------------------------------------------------------
/pyappcache/py.typed:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/calpaterson/pyappcache/f4bff4f8d522c6103e378be32b97e35bff116f36/pyappcache/py.typed
--------------------------------------------------------------------------------
/pyappcache/redis.py:
--------------------------------------------------------------------------------
1 | import io
2 | from typing import Optional, cast, IO
3 | from logging import getLogger
4 |
5 | import redis as redis_py
6 |
7 | from .cache import Cache
8 |
9 | logger = getLogger(__name__)
10 |
11 |
12 | class RedisCache(Cache):
13 | """A redis :class:`~pyappcache.cache.Cache` instance.
14 |
15 | This uses ``GET``/``SET``/``DELETE``.
16 |
17 | .. admonition:: :meth:`~Cache.clear` uses ``FLUSHDB``
18 |
19 | The clear method for this implementation will call ``FLUSHDB`` - and so
20 | remove *everything* in the database.
21 |
22 | """
23 |
24 | def __init__(self, client: Optional[redis_py.Redis] = None):
25 | """
26 |
27 | :param client: A optional redis client to use. If one isn't provided
28 | database 0 on localhost is used."""
29 | super().__init__()
30 | if client is not None:
31 | self._redis = client
32 | else:
33 | self._redis = redis_py.Redis()
34 |
35 | def get_raw(self, raw_key: str) -> Optional[IO[bytes]]:
36 | value = self._redis.get(raw_key)
37 | if value is not None:
38 | return io.BytesIO(cast(bytes, value))
39 | else:
40 | return None
41 |
42 | def set_raw(self, raw_key: str, value_bytes: IO[bytes], ttl_seconds: int) -> None:
43 | self._redis.set(
44 | raw_key, value_bytes.read(), ex=ttl_seconds if ttl_seconds != 0 else None
45 | )
46 |
47 | def invalidate_raw(self, raw_key: str) -> None:
48 | self._redis.delete(raw_key)
49 |
50 | def clear(self) -> None:
51 | self._redis.flushdb()
52 |
--------------------------------------------------------------------------------
/pyappcache/serialisation/__init__.py:
--------------------------------------------------------------------------------
1 | from .core import PickleSerialiser, BinaryFileSerialiser, Serialiser # noqa
2 |
3 | __all__ = ["PickleSerialiser", "Serialiser", "BinaryFileSerialiser"]
4 |
--------------------------------------------------------------------------------
/pyappcache/serialisation/core.py:
--------------------------------------------------------------------------------
1 | from typing import Any, IO
2 | from io import BytesIO
3 | import pickle
4 | from logging import getLogger
5 |
6 | from typing_extensions import Protocol
7 |
8 | logger = getLogger(__name__)
9 |
10 |
11 | class Serialiser(Protocol):
12 | """The protocol for serialisers to follow"""
13 |
14 | def dump(self, obj: Any) -> IO[bytes]:
15 | """Dumps an arbitrary Python object to a buffer"""
16 | pass # pragma: no cover
17 |
18 | def load(self, data: IO[bytes]) -> Any:
19 | """Restores an arbitrary Python object from bytes, *or `None` if the
20 | bytes don't make sense*."""
21 | pass # pragma: no cover
22 |
23 |
24 | class PickleSerialiser:
25 | """A wrapper for pickling.
26 |
27 | The difference between this and pickle.load/pickle.dump is that
28 | ``PickleSerialiser`` returns None when it can't unpickle - to defend
29 | against unreadable cache values."""
30 |
31 | #: The pickle protocol level (default 4). Changing this default value
32 | #: will be considered a breaking API change.
33 | pickle_protocol = 4
34 |
35 | def dump(self, obj: Any) -> IO[bytes]:
36 | buf = BytesIO()
37 | pickle.dump(obj, buf, protocol=self.pickle_protocol)
38 | buf.seek(0)
39 | return buf
40 |
41 | def load(self, data: IO[bytes]) -> Any:
42 | try:
43 | value = pickle.load(data)
44 | except pickle.UnpicklingError:
45 | logger.warning("unable to unpickle value")
46 | value = None
47 | return value
48 |
49 |
50 | class BinaryFileSerialiser:
51 | def dump(self, obj: Any) -> IO[bytes]:
52 | try:
53 | pos = obj.tell()
54 | s = obj.read(10)
55 | obj.seek(pos)
56 | if type(s) is not bytes:
57 | raise RuntimeError(
58 | "BinaryFileSerializer can only serialise binary files (got a string file)"
59 | )
60 | else:
61 | return obj
62 | except AttributeError:
63 | raise RuntimeError(
64 | f"BinaryFileSerializer can only serialise files, but got a {type(obj)}"
65 | )
66 |
67 | def load(self, data: IO[bytes]) -> IO[bytes]:
68 | return data
69 |
--------------------------------------------------------------------------------
/pyappcache/serialisation/pandas.py:
--------------------------------------------------------------------------------
1 | from logging import getLogger
2 |
3 | logger = getLogger(__name__)
4 |
5 | from typing import Any, IO
6 | from io import BytesIO
7 |
8 | import pandas as pd
9 |
10 | from .core import PickleSerialiser
11 |
12 |
13 | class DataFrameAwareSerialiser(PickleSerialiser):
14 | """A serialiser that is aware of dataframes and, instead of pickling them,
15 | outputs them to parquet.
16 |
17 | """
18 |
19 | def __init__(self):
20 | super().__init__()
21 |
22 | def dump(self, obj: Any) -> IO[bytes]:
23 | if isinstance(obj, pd.DataFrame):
24 | buf = BytesIO()
25 | obj.to_parquet(buf)
26 | buf.seek(0)
27 | return buf
28 | else:
29 | return super().dump(obj)
30 |
31 | def load(self, data: IO[bytes]) -> Any:
32 | if _is_parquet(data):
33 | return pd.read_parquet(data)
34 | else:
35 | return super().load(data)
36 |
37 |
38 | def _is_parquet(data: IO[bytes]) -> bool:
39 | head = data.read(3)
40 | data.seek(0)
41 | return head == b"PAR"
42 |
--------------------------------------------------------------------------------
/pyappcache/sqlite_lru.py:
--------------------------------------------------------------------------------
1 | from typing import Optional, Union, IO
2 | import shutil
3 | import io
4 | from datetime import datetime, timedelta
5 | from contextlib import closing
6 | import sqlite3
7 |
8 | from dateutil.parser import parse as parse_dt
9 |
10 | from .cache import Cache
11 |
12 | CREATE_DDL = """
13 | CREATE TABLE IF NOT EXISTS pyappcache
14 | (key PRIMARY KEY, value NOT NULL, expiry NOT NULL, last_read NOT NULL);
15 | """
16 |
17 | INDEX_DDL = [
18 | """
19 | CREATE INDEX IF NOT EXISTS pyappcache_expiry
20 | ON pyappcache (expiry);
21 | """,
22 | """
23 | CREATE INDEX IF NOT EXISTS pyappcache_last_read
24 | ON pyappcache (last_read);
25 | """,
26 | ]
27 |
28 | SET_DML = """
29 | INSERT OR REPLACE INTO pyappcache
30 | (key, value, expiry, last_read)
31 | VALUES
32 | (?, ?, ?, ?);
33 | """
34 |
35 | SET_DML_FOR_BLOBOPEN = """
36 | INSERT OR REPLACE INTO pyappcache
37 | (key, value, expiry, last_read)
38 | VALUES
39 | (?, zeroblob(?), ?, ?);
40 | """
41 |
42 | EVICT_DML = """
43 | DELETE FROM pyappcache
44 | WHERE key IN (
45 | SELECT key
46 | FROM pyappcache
47 | ORDER BY last_read DESC
48 | LIMIT -1 OFFSET ?
49 | );
50 | """
51 |
52 | TOUCH_DML = """
53 | UPDATE pyappcache
54 | SET last_read = ?
55 | WHERE key = ?
56 | AND (expiry >= ? OR expiry = '-1');
57 | """
58 |
59 | GET_DQL = """
60 | SELECT value
61 | FROM pyappcache
62 | WHERE key = ?
63 | AND (expiry >= ? OR expiry = '-1');
64 | """
65 |
66 | GET_DQL_FOR_BLOBOPEN = """
67 | SELECT rowid
68 | FROM pyappcache
69 | WHERE key = ?
70 | AND (expiry >= ? OR expiry = '-1');
71 | """
72 |
73 | GET_TTL_DQL = """
74 | SELECT expiry
75 | FROM pyappcache
76 | WHERE key = ?;
77 | """
78 |
79 | INVALIDATE_DML = """
80 | DELETE FROM pyappcache
81 | WHERE key = ?;
82 | """
83 |
84 | CLEAR_DML = """
85 | DELETE FROM pyappcache;
86 | """
87 |
88 | # This is present as a basic safety feature - to prevent people blowing up
89 | # their processes by accident
90 | MAX_SIZE = 10_000
91 |
92 |
93 | _in_memory_conn = None
94 |
95 |
96 | def get_in_memory_conn():
97 | """Get a shared in-memory connection.
98 |
99 | This is used by :class:`~pyappcache.sqlite_lru.SqliteCache` to get a named
100 | in-memory sqlite connection (`pyappcache_memory` - to avoid clobbering
101 | other users of in-memory sqlite databases) and multi-thread support.
102 |
103 | """
104 | global _in_memory_conn
105 | if _in_memory_conn is None:
106 | # This avoids clobbering other in memory sqlite databases (but allows
107 | # us to use them from different threads)
108 | _in_memory_conn = sqlite3.connect(
109 | "file:pyappcache_memory?mode=memory&cache=shared"
110 | )
111 | return _in_memory_conn
112 |
113 |
114 | class SqliteCache(Cache):
115 | """Implementation of an LRU cache using sqlite3.
116 |
117 | Note that as this is an LRU cache data accesses require write access (in
118 | order to update the last-used time).
119 | """
120 |
121 | def __init__(
122 | self, max_size: int = MAX_SIZE, connection: Optional[sqlite3.Connection] = None
123 | ):
124 | """
125 |
126 | :parameter max_size: Maximum size of the LRU cache. Defaults to 10,000
127 | :parameter connection: Optionally, you can pass a sqlite3 connection. By
128 | default an in-memory database will be used (this will be is shared between all
129 | instances).
130 |
131 | """
132 | super().__init__()
133 | if connection is None:
134 | self.conn = get_in_memory_conn()
135 | else:
136 | self.conn = connection
137 |
138 | # the blobopen API is newish, 3.11+
139 | self._has_blobopen = hasattr(self.conn, "blobopen")
140 |
141 | self.max_size = max_size
142 | with closing(self.conn.cursor()) as cursor:
143 | cursor.execute(CREATE_DDL)
144 | for index_ddl in INDEX_DDL:
145 | cursor.execute(index_ddl)
146 | self.conn.commit()
147 |
148 | def get_raw(self, raw_key: str) -> Optional[IO[bytes]]: # pragma: no cover
149 | now = datetime.utcnow()
150 | with closing(self.conn.cursor()) as cursor:
151 | cursor.execute(TOUCH_DML, (now, raw_key, now))
152 | if self._has_blobopen:
153 | cursor.execute(GET_DQL_FOR_BLOBOPEN, (raw_key, now))
154 | else:
155 | cursor.execute(GET_DQL, (raw_key, now))
156 | v = cursor.fetchone()
157 | if v is not None:
158 | if self._has_blobopen:
159 | rowid = v[0]
160 | blob = self.conn.blobopen("pyappcache", "value", rowid, readonly=True)
161 | # we need readline above in the stack, for pickle.
162 | # frustratingly sqlite3.Blob does not have that and none of the
163 | # wrappers in io seem able to polyfill it
164 | rv = io.BytesIO()
165 | shutil.copyfileobj(blob, rv)
166 | rv.seek(0)
167 | else:
168 | (cache_contents,) = v
169 | rv = io.BytesIO(cache_contents)
170 | else:
171 | rv = None
172 | self.conn.commit()
173 | return rv
174 |
175 | def set_raw(
176 | self, key_bytes: str, value_bytes: IO[bytes], ttl: int
177 | ) -> None: # pragma: no cover
178 | last_read = datetime.utcnow()
179 | expiry: Union[str, datetime]
180 | if ttl != 0:
181 | expiry = last_read + timedelta(seconds=ttl)
182 | else:
183 | expiry = "-1"
184 | with closing(self.conn.cursor()) as cursor:
185 | if self._has_blobopen:
186 | value_bytes.seek(0, io.SEEK_END)
187 | value_length = value_bytes.tell()
188 | value_bytes.seek(0)
189 | cursor.execute(
190 | SET_DML_FOR_BLOBOPEN, (key_bytes, value_length, expiry, last_read)
191 | )
192 | rowid = cursor.lastrowid
193 | with closing(self.conn.blobopen("pyappcache", "value", rowid)) as blob:
194 | shutil.copyfileobj(value_bytes, blob)
195 | else:
196 | cursor.execute(
197 | SET_DML, (key_bytes, value_bytes.read(), expiry, last_read)
198 | )
199 | cursor.execute(EVICT_DML, (self.max_size,))
200 |
201 | self.conn.commit()
202 |
203 | def ttl(self, key_bytes: str) -> Optional[int]:
204 | """Returns the (remaining) TTL of the given key."""
205 | now = datetime.utcnow()
206 | with closing(self.conn.cursor()) as cursor:
207 | cursor.execute(GET_TTL_DQL, (key_bytes,))
208 | row = cursor.fetchone()
209 | if row is not None:
210 | expiry = row[0]
211 | expiry_dt = parse_dt(expiry)
212 | ttl_td = expiry_dt - now
213 | return int(ttl_td.total_seconds())
214 | else:
215 | return None
216 |
217 | def invalidate_raw(self, raw_key: str) -> None:
218 | with closing(self.conn.cursor()) as cursor:
219 | cursor.execute(INVALIDATE_DML, (raw_key,))
220 | self.conn.commit()
221 |
222 | def clear(self) -> None:
223 | with closing(self.conn.cursor()) as cursor:
224 | cursor.execute(CLEAR_DML)
225 | self.conn.commit()
226 |
--------------------------------------------------------------------------------
/pyappcache/util/__init__.py:
--------------------------------------------------------------------------------
1 | #
2 |
--------------------------------------------------------------------------------
/pyappcache/util/requests.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 |
3 | from ..cache import Cache
4 | from ..keys import SimpleStringKey
5 |
6 | CacheControlKey = SimpleStringKey[bytes]
7 |
8 |
9 | class CacheControlProxy:
10 | """A proxy to allow :class:`~pyappcache.cache.Cache` instances to be
11 | converted for the cachecontrol library's desired API.
12 |
13 | """
14 |
15 | def __init__(self, cache: Cache):
16 | """
17 |
18 | :parameter cache: An instances of :class:`~pyappcache.Cache` to proxy."""
19 | self.cache = cache
20 |
21 | def get(self, key_str: str) -> Optional[bytes]:
22 | key = CacheControlKey(key_str)
23 | return self.cache.get(key)
24 |
25 | def set(self, key_str: str, value: bytes, expires: Optional[int] = None) -> None:
26 | key = CacheControlKey(key_str)
27 | self.cache.set(key, value, ttl_seconds=expires or 0)
28 |
29 | def delete(self, key_str: str) -> None:
30 | key = CacheControlKey(key_str)
31 | self.cache.invalidate(key)
32 |
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | log_level = DEBUG
3 | filterwarnings =
4 | ignore:.*imp.*:DeprecationWarning
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup, find_packages
2 |
3 | VERSION = open("VERSION").read().strip()
4 | README = open("README.rst").read()
5 |
6 | redis_requirements = ["redis>=3"]
7 | memcache_requirements = ["pylibmc"]
8 | test_requirements = [
9 | "black~=22.10.0",
10 | "cachecontrol",
11 | "flask",
12 | "mypy==0.991",
13 | "pandas",
14 | "pandas-stubs",
15 | "pyarrow",
16 | "pyflakes",
17 | "pytest-cov",
18 | "pytest~=7.2.0",
19 | "requests",
20 | "sphinx-autodoc-typehints~=1.19.5",
21 | "sphinx==5.3.0",
22 | "time-machine~=2.13.0",
23 | "types-python-dateutil",
24 | "types-redis",
25 | "types-requests",
26 | "wheel",
27 | ]
28 |
29 | setup(
30 | name="pyappcache",
31 | version=VERSION,
32 | packages=find_packages(exclude=["tests.*", "tests"]),
33 | package_data={"pyappcache": ["py.typed"]},
34 | include_package_data=True,
35 | long_description=README,
36 | long_description_content_type="text/markdown",
37 | python_requires=">=3.8",
38 | install_requires=["typing_extensions", "python-dateutil"],
39 | extras_require={
40 | "redis": redis_requirements,
41 | "memcache": memcache_requirements,
42 | "tests": test_requirements + memcache_requirements + redis_requirements,
43 | "dev": ["bpython~=0.18"],
44 | },
45 | project_urls={
46 | "Documentation": "https://pyappcache.readthedocs.io/en/latest/",
47 | "Code": "https://github.com/calpaterson/pyappcache",
48 | "Issue tracker": "https://github.com/calpaterson/pyappcache/issues",
49 | },
50 | url="https://github.com/calpaterson/pyappcache",
51 | author="Cal Paterson",
52 | author_email="cal@calpaterson.com",
53 | classifiers=[
54 | "Intended Audience :: Developers",
55 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
56 | "Programming Language :: Python :: 3",
57 | "Programming Language :: Python :: 3.10",
58 | "Programming Language :: Python :: 3.11",
59 | "Programming Language :: Python :: 3.12",
60 | "Programming Language :: Python :: 3.8",
61 | "Programming Language :: Python :: 3.9",
62 | ],
63 | )
64 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/calpaterson/pyappcache/f4bff4f8d522c6103e378be32b97e35bff116f36/tests/__init__.py
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 |
3 | import redis as redis_py
4 | import pylibmc
5 |
6 | from pyappcache.cache import Cache
7 | from pyappcache.memcache import MemcacheCache
8 | from pyappcache.redis import RedisCache
9 | from pyappcache.sqlite_lru import SqliteCache
10 | from pyappcache.fs import FilesystemCache
11 |
12 | import pytest
13 | from .utils import random_string, StringToStringKey, StringToStringKeyWithCompression
14 |
15 |
16 | @pytest.fixture(scope="session")
17 | def memcache_client():
18 | return pylibmc.Client(["127.0.0.1"], binary=True)
19 |
20 |
21 | @pytest.fixture(scope="session")
22 | def redis_client():
23 | return redis_py.Redis()
24 |
25 |
26 | @pytest.fixture(scope="function", params=["redis", "memcache", "sqlite", "fs"])
27 | def cache(request, redis_client, memcache_client, tmpdir):
28 | """Cache object"""
29 | cache: Cache
30 | if request.param == "redis":
31 | cache = RedisCache(redis_client)
32 | elif request.param == "sqlite":
33 | cache = SqliteCache()
34 | elif request.param == "fs":
35 | cache = FilesystemCache(Path(str(tmpdir)))
36 | else:
37 | cache = MemcacheCache(memcache_client)
38 |
39 | # Randomise the prefix
40 | cache.prefix = random_string()
41 |
42 | return cache
43 |
44 |
45 | @pytest.fixture(params=[StringToStringKey, StringToStringKeyWithCompression])
46 | def KeyCls(request):
47 | return request.param
48 |
49 |
50 | test_data = Path(__file__).parent.resolve() / "test-data"
51 |
--------------------------------------------------------------------------------
/tests/test-data/stock-exchanges.parquet:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/calpaterson/pyappcache/f4bff4f8d522c6103e378be32b97e35bff116f36/tests/test-data/stock-exchanges.parquet
--------------------------------------------------------------------------------
/tests/test_caches.py:
--------------------------------------------------------------------------------
1 | from io import BytesIO
2 |
3 | from pyappcache.cache import Cache
4 | from pyappcache.keys import build_raw_key
5 | from pyappcache.memcache import MemcacheCache
6 | from pyappcache.sqlite_lru import SqliteCache
7 | from pyappcache.redis import RedisCache
8 | from pyappcache.fs import FilesystemCache
9 |
10 | import pytest
11 | from .utils import random_string, StringToStringKeyWithCompression, random_bytes
12 |
13 |
14 | def test_get_and_set_no_ttl(cache, KeyCls):
15 | v = "a"
16 | key = KeyCls(random_string())
17 | cache.set(key, v)
18 | got = cache.get(key)
19 | assert got == v
20 |
21 |
22 | def test_ttl_when_key_not_set(cache):
23 | if not hasattr(cache, "ttl"):
24 | pytest.skip("ttl is not implemented")
25 | key = random_string().encode("utf-8")
26 | assert cache.ttl(key) is None
27 |
28 |
29 | def test_get_and_set_10k_sec_ttl(cache, KeyCls):
30 | key = KeyCls(random_string())
31 | cache.set(key, "a", ttl_seconds=10_000)
32 |
33 | key_str = build_raw_key(cache.prefix, key)
34 | if isinstance(cache, MemcacheCache):
35 | # Is there any way to do this?
36 | pytest.skip("memcache ttl checker is too flaky")
37 | # ttl = get_memcache_ttl(key_str)
38 | elif isinstance(cache, SqliteCache):
39 | ttl = cache.ttl(key_str)
40 | elif isinstance(cache, FilesystemCache):
41 | ttl = cache.ttl(key_str)
42 | elif isinstance(cache, RedisCache):
43 | ttl = cache._redis.ttl(key_str)
44 | assert cache.get(key) == "a"
45 | assert ttl is not None
46 | assert ttl > 9_000
47 |
48 |
49 | def test_overwrite(cache, KeyCls):
50 | key = KeyCls(random_string())
51 | cache.set(key, "a")
52 | cache.set(key, "b")
53 | assert cache.get(key) == "b"
54 |
55 |
56 | def test_get_and_set_absent(cache, KeyCls):
57 | key = KeyCls(random_string())
58 | assert cache.get(key) is None
59 |
60 |
61 | def test_invalidate(cache, KeyCls):
62 | key = KeyCls(random_string())
63 | cache.set(key, "a")
64 | cache.invalidate(key)
65 | assert cache.get(key) is None
66 |
67 |
68 | def test_clear(cache, KeyCls):
69 | key = KeyCls(random_string())
70 | cache.set(key, "a")
71 | cache.clear()
72 | assert cache.get(key) is None
73 |
74 |
75 | def test_unreadable_pickle(cache, KeyCls):
76 | key = KeyCls(random_string())
77 | key_segments = [cache.prefix]
78 | key_segments.extend(key.cache_key_segments())
79 | key_bytes = "/".join(key_segments)
80 | cache.set_raw(key_bytes, BytesIO(b"good luck unpickling this"), 0)
81 |
82 | assert cache.get(key) is None
83 |
84 |
85 | def test_prefixing(cache, KeyCls):
86 | key = KeyCls(random_string())
87 | cache.set(key, "a")
88 | cache.prefix = random_string()
89 | assert cache.get(key) is None
90 |
91 |
92 | def test_by_str(cache, KeyCls):
93 | key_subj = random_string()
94 | key = KeyCls(key_subj)
95 | str_key = key_subj
96 |
97 | cache.set(key, "a")
98 | assert cache.get_by_str(str_key) == "a"
99 |
100 | cache.invalidate_by_str(str_key)
101 | assert cache.get_by_str(key) is None
102 |
103 | cache.set_by_str(str_key, "b")
104 | assert cache.get(key) == "b"
105 |
106 | cache.invalidate_by_str(str_key)
107 | assert cache.get(key) is None
108 |
109 |
110 | def test_compression_via_key(cache):
111 | key = StringToStringKeyWithCompression(random_string())
112 | cache.set(key, "b")
113 |
114 | raw_value = cache.get_raw(build_raw_key(cache.prefix, key)).read()
115 | assert raw_value.startswith(b"\x1f\x8b")
116 |
117 |
118 | def test_compression_via_str(cache):
119 | cache.set_by_str("a", "b", compress=True)
120 | raw_value = cache.get_raw(build_raw_key(cache.prefix, "a")).read()
121 | assert raw_value.startswith(b"\x1f\x8b")
122 |
123 |
124 | def test_get_via(cache, KeyCls):
125 | key = KeyCls(random_string())
126 |
127 | getter_called = False
128 |
129 | def fake_getter():
130 | nonlocal getter_called
131 | getter_called = True
132 | return "ok"
133 |
134 | cache.get_via(key, fake_getter)
135 | assert getter_called is True
136 |
137 | getter_called = False
138 | cache.get_via(key, fake_getter)
139 | assert getter_called is False
140 |
141 |
142 | def test_set_via(cache, KeyCls):
143 | key = KeyCls(random_string())
144 |
145 | db = {}
146 |
147 | def fake_setter(id_, value):
148 | db[id_] = value
149 |
150 | value = random_string()
151 | cache.set_via(key, value, fake_setter, setter_args=("a", value))
152 |
153 | assert cache.get(key) == value
154 | assert db["a"] == value
155 |
156 |
157 | def test_set_via_setter_fails(cache, KeyCls):
158 | key = KeyCls(random_string())
159 |
160 | def fake_setter(id_, value):
161 | raise RuntimeError("bad bytes!")
162 |
163 | value = random_string()
164 | with pytest.raises(RuntimeError):
165 | cache.set_via(key, value, fake_setter, setter_args=("a", value))
166 |
167 | assert cache.get(key) is None
168 |
169 |
170 | def test_default_prefix(cache):
171 | cache.prefix = Cache.DEFAULT_PREFIX
172 | key = random_string()
173 | value = random_string()
174 | cache.set_by_str(key, value)
175 |
176 | assert cache.get_raw("/".join(["pyappcache", key])) is not None
177 |
178 |
179 | def test_eviction__max_size_is_maintained(cache):
180 | """Test that eviction happens on set_raw."""
181 | if not hasattr(cache, "max_size_bytes"):
182 | pytest.skip(reason="cache doesn't have a max_size_bytes param")
183 |
184 | cache.max_size_bytes = 100
185 |
186 | a_val = random_bytes(49)
187 | b_val = random_bytes(49)
188 | c_val = random_bytes(49)
189 |
190 | cache.set_raw("a", BytesIO(a_val), 100)
191 | cache.set_raw("b", BytesIO(b_val), 100)
192 | cache.set_raw("c", BytesIO(c_val), 100)
193 |
194 | assert cache.get_raw("a") is None
195 | assert cache.get_raw("b").read() == b_val
196 | assert cache.get_raw("c").read() == c_val
197 |
198 |
199 | def test_eviction__reading_is_a_touch(cache):
200 | if not hasattr(cache, "max_size_bytes"):
201 | pytest.skip(reason="cache doesn't have a max_size_bytes param")
202 |
203 | cache.max_size_bytes = 100
204 |
205 | a_val = random_bytes(49)
206 | b_val = random_bytes(49)
207 | c_val = random_bytes(49)
208 |
209 | cache.set_raw("a", BytesIO(a_val), 100)
210 | cache.set_raw("b", BytesIO(b_val), 100)
211 | cache.get_raw("a")
212 | cache.set_raw("c", BytesIO(c_val), 100)
213 |
214 | assert cache.get_raw("a").read() == a_val
215 | assert cache.get_raw("b") is None
216 | assert cache.get_raw("c").read() == c_val
217 |
--------------------------------------------------------------------------------
/tests/test_compression.py:
--------------------------------------------------------------------------------
1 | from io import BytesIO
2 |
3 | from pyappcache.compression import GZIPCompressor
4 |
5 | import pytest
6 |
7 |
8 | @pytest.fixture(scope="session")
9 | def compressor():
10 | return GZIPCompressor()
11 |
12 |
13 | def test_compress_and_decompress(compressor):
14 | buf = BytesIO(b"hello, world")
15 | decompressed = compressor.decompress(compressor.compress(buf)).read()
16 | buf.seek(0)
17 | expected = buf.read()
18 | assert expected == decompressed
19 |
--------------------------------------------------------------------------------
/tests/test_keys.py:
--------------------------------------------------------------------------------
1 | from pyappcache.serialisation import PickleSerialiser
2 | from pyappcache.keys import SimpleStringKey, Key
3 | from .utils import StringToIntKey
4 |
5 |
6 | def test_simple_key_to_segments():
7 | key = StringToIntKey("freddie")
8 | assert key.cache_key_segments() == ["freddie"]
9 |
10 |
11 | def test_should_compress():
12 | key = StringToIntKey("freddie")
13 | obj = 1
14 | as_bytes = PickleSerialiser().dump(obj)
15 | assert key.should_compress(obj, as_bytes) is False
16 |
17 |
18 | def test_simple_string_key_repr():
19 | key: Key[str] = SimpleStringKey("foo")
20 | assert repr(key) == ""
21 |
--------------------------------------------------------------------------------
/tests/test_memcache.py:
--------------------------------------------------------------------------------
1 | import pickle
2 | import pylibmc
3 |
4 | import pytest
5 |
6 | from pyappcache.memcache import MemcacheCache
7 | from .utils import random_string
8 |
9 |
10 | class FlakeyClient:
11 | def __init__(self, flakes):
12 | self.count = 0
13 | self.flakes = flakes
14 |
15 | def get(self, key):
16 | if self.count >= self.flakes:
17 | return pickle.dumps("good bytes")
18 | else:
19 | self.count += 1
20 | raise pylibmc.ConnectionError("nope")
21 |
22 | def set(self, key, value, time):
23 | if self.count >= self.flakes:
24 | return None
25 | else:
26 | self.count += 1
27 | raise pylibmc.ConnectionError("nope")
28 |
29 | def delete(self, key):
30 | if self.count >= self.flakes:
31 | return None
32 | else:
33 | self.count += 1
34 | raise pylibmc.ConnectionError("nope")
35 |
36 | def flush_all(self):
37 | if self.count >= self.flakes:
38 | return None
39 | else:
40 | self.count += 1
41 | raise pylibmc.ConnectionError("nope")
42 |
43 |
44 | @pytest.mark.parametrize(
45 | "method_name, args, expected",
46 | [
47 | ("get_by_str", ("a",), "good bytes"),
48 | ("set_by_str", ("a", "b"), None),
49 | ("invalidate_by_str", ("a"), None),
50 | ("clear", (), None),
51 | ],
52 | )
53 | def test_retry_on_disconnect(method_name, args, expected):
54 | """Check we try to reconnect (exactly once) to the memcache server if we get disconnected."""
55 |
56 | cache = MemcacheCache(FlakeyClient(1))
57 | assert getattr(cache, method_name)(*args) == expected
58 |
59 |
60 | def test_retry_gives_up_on_down():
61 | """Check we don't retry forever"""
62 |
63 | cache = MemcacheCache(FlakeyClient(2))
64 | with pytest.raises(pylibmc.ConnectionError):
65 | cache.get_by_str("foo")
66 |
67 |
68 | def test_default_client():
69 | cache = MemcacheCache()
70 | cache.get_by_str(random_string()) is None
71 |
--------------------------------------------------------------------------------
/tests/test_namespacing.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | import logging
3 |
4 | from pyappcache.keys import BaseKey
5 |
6 |
7 | class UserToLastChangedKey(BaseKey[datetime]):
8 | def __init__(self, username: str):
9 | self._username = username
10 |
11 | def cache_key_segments(self):
12 | return [self._username, "last_changed"]
13 |
14 |
15 | class UserFavouritePokemon(BaseKey[str]):
16 | def __init__(self, username: str):
17 | self._username = username
18 |
19 | def namespace_key(self):
20 | return UserToLastChangedKey(self._username)
21 |
22 | def cache_key_segments(self):
23 | return ["favourite_pokemon"]
24 |
25 |
26 | def test_namespace_get_when_no_namespace(cache):
27 | key = UserFavouritePokemon("john")
28 |
29 | cache.set(key.namespace_key(), datetime(2018, 1, 3))
30 | cache.set(key, "pikachu")
31 | cache.invalidate(key.namespace_key())
32 | assert cache.get(key) is None
33 |
34 |
35 | def test_namespace_set_when_no_namespace(cache):
36 | key = UserFavouritePokemon("john")
37 |
38 | cache.set(key, "pikachu")
39 | assert cache.get(key) is None
40 |
41 |
42 | def test_namespace_get_and_set_when_namespace_present(cache):
43 | key = UserFavouritePokemon("john")
44 |
45 | cache.set(key.namespace_key(), datetime(2018, 1, 3))
46 | cache.set(key, "pikachu")
47 |
48 | assert cache.get(key) == "pikachu"
49 |
50 |
51 | def test_get_and_set_when_namespace_outdated(cache):
52 | key = UserFavouritePokemon("john")
53 |
54 | cache.set(key.namespace_key(), datetime(2018, 1, 3))
55 | cache.set(key, "pikachu")
56 | cache.set(key.namespace_key(), datetime(2018, 1, 4))
57 |
58 | assert cache.get(key) is None
59 |
60 |
61 | def test_get_and_set_when_namespace_updated(cache):
62 | key = UserFavouritePokemon("john")
63 |
64 | cache.set(key.namespace_key(), datetime(2018, 1, 3))
65 | cache.set(key, "pikachu")
66 | cache.set(key.namespace_key(), datetime(2018, 1, 4))
67 | cache.set(key, "bulbasaur")
68 |
69 | assert cache.get(key) == "bulbasaur"
70 |
71 |
72 | def test_invalidation_when_no_namespace(cache, caplog):
73 | key = UserFavouritePokemon("john")
74 |
75 | with caplog.at_level(logging.WARNING, logger="pyappcache.cache"):
76 | cache.invalidate(key)
77 | assert caplog.record_tuples == [
78 | (
79 | "pyappcache.cache",
80 | 30,
81 | "unable to invalidate key as namespace does not exist",
82 | )
83 | ]
84 |
85 |
86 | def test_invalidation_when_namespace_present(cache):
87 | key = UserFavouritePokemon("john")
88 |
89 | cache.set(key.namespace_key(), datetime(2018, 1, 3))
90 | cache.set(key, "pikachu")
91 |
92 | cache.invalidate(key)
93 | assert cache.get(key) is None
94 |
--------------------------------------------------------------------------------
/tests/test_redis.py:
--------------------------------------------------------------------------------
1 | from pyappcache.redis import RedisCache
2 | from .utils import random_string
3 |
4 |
5 | def test_default_client():
6 | cache = RedisCache()
7 | cache.get_by_str(random_string()) is None
8 |
--------------------------------------------------------------------------------
/tests/test_requests.py:
--------------------------------------------------------------------------------
1 | import threading
2 | from datetime import datetime, timedelta
3 | from contextlib import closing
4 | import socket
5 | import time
6 |
7 | import requests
8 | import cachecontrol
9 | import flask
10 |
11 | import requests.models
12 | import requests.adapters
13 | import pytest
14 |
15 | from pyappcache.util.requests import CacheControlProxy
16 |
17 |
18 | def get_free_port():
19 | with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
20 | s.bind(("", 0))
21 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
22 | return s.getsockname()[1]
23 |
24 |
25 | @pytest.fixture(scope="session")
26 | def local_server():
27 | app = flask.Flask("local-server")
28 | app.config["calls"] = 0
29 |
30 | @app.route("/", methods=["GET"])
31 | def get_route():
32 | response = flask.make_response(b"hello")
33 | response.headers["Cache-Control"] = "max-age=200"
34 | app.config["calls"] += 1
35 | return response
36 |
37 | @app.route("/ok", methods=["GET"])
38 | def ok():
39 | return "ok"
40 |
41 | @app.route("/", methods=["DELETE"])
42 | def delete_route():
43 | response = flask.make_response(b"goodbye")
44 | app.config["calls"] += 1
45 | return response
46 |
47 | port = get_free_port()
48 |
49 | thread = threading.Thread(
50 | target=app.run, kwargs={"port": port, "debug": False}, daemon=True
51 | )
52 | thread.start()
53 |
54 | # Wait until the server has started up (check by polling)
55 | give_up_time = datetime.utcnow() + timedelta(seconds=5)
56 | sesh = requests.Session()
57 | while give_up_time > datetime.utcnow():
58 | try:
59 | sesh.get(f"http://localhost:{port}/ok", timeout=0.001)
60 | break
61 | except requests.exceptions.RequestException:
62 | pass
63 | time.sleep(0) # aka thread.yield
64 |
65 | return app, port
66 |
67 |
68 | def test_request_with_cache_control(cache, local_server):
69 | """Check that requests are cached properly"""
70 | app, port = local_server
71 | initial_calls = app.config["calls"]
72 |
73 | url = f"http://localhost:{port}/"
74 |
75 | proxy = CacheControlProxy(cache)
76 |
77 | sesh = requests.Session()
78 | cached_sesh = cachecontrol.CacheControl(sesh, cache=proxy) # type: ignore
79 |
80 | response1 = cached_sesh.get(url)
81 | assert response1.status_code == 200
82 | assert response1.content == b"hello"
83 |
84 | response2 = cached_sesh.get(url)
85 | assert response2.status_code == 200
86 | assert response2.content == b"hello"
87 |
88 | assert app.config["calls"] == (initial_calls + 1)
89 |
90 |
91 | def test_deletion_with_cache_control(cache, local_server):
92 | """Check that issuing a delete clears the entry from the cache"""
93 | app, port = local_server
94 |
95 | url = f"http://localhost:{port}/"
96 |
97 | proxy = CacheControlProxy(cache)
98 |
99 | sesh = requests.Session()
100 | cached_sesh = cachecontrol.CacheControl(sesh, cache=proxy) # type: ignore
101 |
102 | response1 = cached_sesh.get(url)
103 | assert response1.status_code == 200
104 | assert response1.content == b"hello"
105 |
106 | response2 = cached_sesh.delete(url)
107 | assert response2.status_code == 200
108 | assert response2.content == b"goodbye"
109 |
110 | assert proxy.get(url) is None
111 |
--------------------------------------------------------------------------------
/tests/test_serialisation.py:
--------------------------------------------------------------------------------
1 | from io import BytesIO, StringIO
2 |
3 | import pandas as pd
4 | from pandas.testing import assert_frame_equal
5 | import pytest
6 |
7 | from .conftest import test_data
8 |
9 | from pyappcache.serialisation import PickleSerialiser, BinaryFileSerialiser
10 | from pyappcache.serialisation.pandas import DataFrameAwareSerialiser
11 |
12 | stock_exchanges = pd.read_parquet(test_data / "stock-exchanges.parquet")
13 |
14 |
15 | def test_pickle_serialiser():
16 | serialiser = PickleSerialiser()
17 | loaded = serialiser.load(serialiser.dump(BytesIO(b"a"))).read()
18 | assert loaded == b"a"
19 |
20 |
21 | def test_dataframe_serialiser__doesnt_change_df():
22 | serialiser = DataFrameAwareSerialiser()
23 | loaded = serialiser.load(serialiser.dump(stock_exchanges))
24 | assert_frame_equal(loaded, stock_exchanges)
25 |
26 |
27 | def test_dataframe_serialiser__handles_junk():
28 | serialiser = DataFrameAwareSerialiser()
29 | assert serialiser.load(BytesIO(b"junk")) is None
30 |
31 |
32 | def test_dataframe_serialised__handles_normal_objects():
33 | serialiser = DataFrameAwareSerialiser()
34 | loaded = serialiser.load(serialiser.dump(BytesIO(b"a"))).read()
35 | assert loaded == b"a"
36 |
37 |
38 | def test_binary_file_serialiser__works_on_files():
39 | serialiser = BinaryFileSerialiser()
40 | buf = BytesIO(b"hello")
41 | assert serialiser.dump(buf).getvalue() == b"hello"
42 |
43 | assert serialiser.load(buf).getvalue() == b"hello"
44 |
45 |
46 | def test_binary_file_serialiser__explodes_on_objects():
47 | serialiser = BinaryFileSerialiser()
48 | with pytest.raises(RuntimeError):
49 | serialiser.dump({})
50 |
51 |
52 | def test_binary_file_serialiser__explodes_on_text_file():
53 | serialiser = BinaryFileSerialiser()
54 | buf = StringIO("hello")
55 | with pytest.raises(RuntimeError):
56 | serialiser.dump(buf)
57 |
--------------------------------------------------------------------------------
/tests/test_sqlite_lru.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | import contextlib
3 | import sqlite3
4 |
5 | import pytest
6 | import time_machine
7 | from pyappcache.sqlite_lru import SqliteCache
8 | from .utils import StringToStringKey, random_string
9 |
10 |
11 | @pytest.fixture(scope="function")
12 | def random_conn():
13 | """A random sqlite3 conn, to prevent clashes between tests"""
14 | return sqlite3.connect(f"file:{random_string()}?mode=memory&cache=shared")
15 |
16 |
17 | def test_sqlite3_lru(random_conn):
18 | """Test that the LRU functionality for SQLite3Cache works right by causing
19 | an eviction."""
20 | cache = SqliteCache(max_size=5, connection=random_conn)
21 |
22 | for i in range(6):
23 | cache.set(StringToStringKey(str(i)), "something")
24 |
25 | assert cache.get(StringToStringKey("0")) is None
26 |
27 |
28 | def test_sqlite_lru_with_backing_file(tmp_path):
29 | """Test that it works with a backing file (as opposed to the default, in
30 | memory option)"""
31 | path = tmp_path / "cache.sqlite3"
32 |
33 | with contextlib.closing(sqlite3.connect(str(path))) as connection:
34 | cache = SqliteCache(max_size=5, connection=connection)
35 |
36 | cache.set(StringToStringKey("a"), "b")
37 |
38 | assert path.exists()
39 |
40 |
41 | def test_in_memory_db_naming():
42 | """Test that our in memory sqlite db does not clash with ordinary
43 | ':memory:' sqlite databases."""
44 | cache = SqliteCache()
45 |
46 | cache.set(StringToStringKey("a"), "b")
47 |
48 | table_dql = """
49 | SELECT name FROM sqlite_master WHERE type = 'table';
50 | """
51 | in_memory_conn = sqlite3.connect(":memory:")
52 | tables = in_memory_conn.execute(table_dql).fetchall()
53 |
54 | assert len(tables) == 0
55 |
56 |
57 | def test_sqlite3_ttls_cause_expiry(random_conn):
58 | """Test that TTLs do cause keys to expire"""
59 | cache = SqliteCache(connection=random_conn)
60 |
61 | key = StringToStringKey("a")
62 | with time_machine.travel(datetime(2018, 1, 3)):
63 | cache.set(key, "b", ttl_seconds=1)
64 |
65 | with time_machine.travel(datetime(2018, 1, 4)):
66 | assert cache.get(key) is None
67 |
68 |
69 | def test_sqlite3_no_ttls_never_expire(random_conn):
70 | """Test that keys set with a 0 ttl never expire"""
71 | cache = SqliteCache(connection=random_conn)
72 |
73 | key = StringToStringKey("a")
74 | with time_machine.travel(datetime(2018, 1, 3)):
75 | cache.set(key, "1")
76 |
77 | with time_machine.travel(datetime(2019, 1, 3)):
78 | assert cache.get(key) == "1"
79 |
80 |
81 | def test_sqlite3_eviction_with_ttls(random_conn):
82 | """Test that evictions happen in order of last_read, not ttl"""
83 | cache = SqliteCache(max_size=1, connection=random_conn)
84 |
85 | key_a = StringToStringKey("a")
86 | with time_machine.travel(datetime(2018, 1, 3, 0)):
87 | cache.set(key_a, "1", ttl_seconds=36000)
88 |
89 | key_b = StringToStringKey("b")
90 | with time_machine.travel(datetime(2018, 1, 3, 1)):
91 | cache.set(key_b, "2", ttl_seconds=10)
92 |
93 | assert cache.get(key_a) is None
94 | assert cache.get(key_b) == "2"
95 |
96 |
97 | def test_sqlite3_eviction_without_ttls(random_conn):
98 | cache = SqliteCache(max_size=1, connection=random_conn)
99 |
100 | key_a = StringToStringKey("a")
101 | with time_machine.travel(datetime(2018, 1, 3, 0)):
102 | cache.set(key_a, "1")
103 |
104 | key_b = StringToStringKey("b")
105 | with time_machine.travel(datetime(2018, 1, 3, 1)):
106 | cache.set(key_b, "2")
107 |
108 | assert cache.get(key_a) is None
109 | assert cache.get(key_b) == "2"
110 |
111 |
112 | def test_sqlite3_eviction_via_last_read(random_conn):
113 | cache = SqliteCache(max_size=2, connection=random_conn)
114 |
115 | with time_machine.travel(datetime(2018, 1, 3, 0)):
116 | key_a = StringToStringKey("a")
117 | cache.set(key_a, "1", ttl_seconds=36000)
118 |
119 | with time_machine.travel(datetime(2018, 1, 3, 1)):
120 | key_b = StringToStringKey("b")
121 | cache.set(key_b, "2", ttl_seconds=36000)
122 |
123 | with time_machine.travel(datetime(2018, 1, 3, 2)):
124 | cache.get(key_a)
125 |
126 | with time_machine.travel(datetime(2018, 1, 3, 3)):
127 | key_c = StringToStringKey("c")
128 | cache.set(key_c, "3", ttl_seconds=36000)
129 |
130 | assert cache.get(key_b) is None
131 | assert cache.get(key_a) == "1"
132 |
--------------------------------------------------------------------------------
/tests/utils.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 | import re
3 | import random
4 | import string
5 | import socket
6 | from datetime import datetime, timedelta
7 | from logging import getLogger
8 |
9 | from pyappcache.keys import SimpleStringKey
10 |
11 | logger = getLogger(__name__)
12 |
13 | StringToIntKey = SimpleStringKey[int]
14 | StringToStringKey = SimpleStringKey[str]
15 |
16 |
17 | class StringToStringKeyWithCompression(StringToStringKey):
18 | def should_compress(self, python_obj, as_bytes):
19 | return True
20 |
21 |
22 | def random_string(n: int = 32) -> str:
23 | return "".join(random.choice(string.ascii_lowercase) for _ in range(n))
24 |
25 |
26 | def random_bytes(n) -> bytes:
27 | return bytes(random_string(n), "utf-8")
28 |
29 |
30 | ONE_MEG = 1024 * 1024 * 1024
31 |
32 | SLAB_REGEX = re.compile(rb":(\d+):")
33 |
34 |
35 | def get_memcache_ttl(key: str) -> Optional[int]:
36 | """There is no way to get the ttl of a key from pylibmc so we do it out of
37 | band with a socket via the text API."""
38 | logger.info("looking up the ttl of: %s", key)
39 | timelimit = datetime.utcnow() + timedelta(seconds=1)
40 | ttl_regex = re.compile(
41 | rb"ITEM %s \[[0-9]+ b; ([0-9]+) s]" % bytes(key, "utf-8"), re.MULTILINE
42 | )
43 |
44 | attempt = 1
45 | # Looks like something is causing the IO to happen async so try for a second
46 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
47 | sock.connect(("localhost", 11211))
48 | while datetime.utcnow() < timelimit:
49 | # 1. Get a list of slabs
50 | sock.send(b"stats items\r\n")
51 | response = sock.recv(ONE_MEG)
52 | logger.debug("memcached stats items response: \n%s", response)
53 | slabs = set(int(slab) for slab in SLAB_REGEX.findall(response))
54 |
55 | # 2. Check every slab for our item
56 | for slab in slabs:
57 | command = bytes(f"stats cachedump {slab} 10\r\n", "utf-8")
58 | sock.send(command)
59 | response = sock.recv(ONE_MEG)
60 | logger.debug("memcached stats cachedump response: \n%s", response)
61 | match_obj = ttl_regex.search(response)
62 | if match_obj:
63 | ttl = int(match_obj.group(1))
64 | logger.info("found ttl for %s: %d (on attempt %d)", key, ttl, attempt)
65 | return ttl
66 | attempt += 1
67 | return None
68 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | skipsdist = True
3 | envlist = py38, py39, py310, py311, 312
4 |
5 | [gh-actions]
6 | python =
7 | 3.8: py38
8 | 3.9: py39
9 | 3.10: py310
10 | 3.11: py311
11 | 3.11: py311
12 | 3.12: py312
13 |
14 | [testenv]
15 | commands =
16 | pip install --upgrade setuptools pip wheel
17 | pip install -e .[tests]
18 | mypy .
19 | pytest --cov=pyappcache --cov-fail-under 100
20 | black --check .
21 | pyflakes pyappcache
22 | # FIXME: Add -W -n --keep-going
23 | sphinx-build -M html docs build
24 | python setup.py bdist_wheel
25 | [flake8]
26 | max-line-length = 88
--------------------------------------------------------------------------------