Generic Proxy and Pool Classes for Python
Project description
Proxy Pattern Pool
Generic Proxy and Pool Classes for Python.
This module provides two classes:
-
Proxyimplements the proxy pattern, i.e. all calls to methods on the proxy are forwarded to an internally wrapped object. This allows to solve the classic chicken-and-egg importation and initialization possibly circular-dependency issue with Python modules:# File "database.py" db = Proxy() def init_app(config): db.set_obj(initialization from config)
# File "app.py" import database from database import db # db is a proxy to nothing … # delayed initialization database.init_app(config) # db is now a proxy to the initialized object
-
Poolimplements a thread-safe pool of things which can be used to store expensive-to-create objects such as database connections. The above proxy object creates a pool automatically depending on its parameters.Call
db._ret_obj()to return the object to the pool when done with it.
Documentation
The Proxy class manages accesses to one or more objects, possibly using
a Pool, depending on the expected scope of said objects.
The Proxy constructors expects the following parameters:
objone single objectSHAREDbetween all threads.funone function called for object creation, each time it is needed, forTHREADandVERSATILEscopes.scopeobject scope as defined byProxy.Scope:SHAREDone shared object (process level)THREADone object per thread (threadingimplementation)WERKZEUGone object per greenlet (werkzeugimplementation)EVENTLETone object per greenlet (eventletimplementation)GEVENTone object per greenlet (geventimplementation)VERSATILEsame asWERKZEUGdefault isSHAREDorTHREADdepending on whether an object of a function was passed for the object.
set_namethe name of a function to set the proxy contents, default isset. This parameter allows to avoid collisions with the proxied methods. It is used as a prefix to haveset_objandset_funfunctions which allow to reset the internalobjorfun.max_sizemaximum pool size for objects kept. None means no pooling, 0 means unlimited pool size (the default).min_sizeminimum pool size. This many is created on startup. Default is 1.max_usehow many times an object should be reused. default is 0 which means unlimited.max_avail_delayafter which unused objects are discarded. default is 0.0 which means unlimited.max_using_delaywarn about objects being used for too long. default is 0.0 which means no warning.max_using_delay_killkill objects being used for too long. default is 0.0 which means no killing.openerfunction to call when creating an object. default is None means nothing is called.getterfunction to call when getting an object. default is None means nothing is called.retterfunction to call when returning an object. default is None means nothing is called.closerfunction to call when discarding an object. default is None means nothing is called.log_levelset logging level, default None means no setting.tracerobject debug helper, default None means less debug.
When max_size is not None, a Pool is created to store the created
objects so as to reuse them. It is the responsability of the user to
return the object when not needed anymore by calling _ret_obj explicitely.
This is useful for code which keeps creating new threads, eg werkzeug.
For a database connection, a good time to do that is just after a commit.
The Pool class manage a pool of objects in a thread-safe way.
Its constructor expects the following parameters:
funhow to create a new object; the function is passed the creation number.max_sizemaximum size of pool, 0 for unlimited.min_sizeminimum size of pool.timeoutmaximum time to wait for something.max_useafter how many usage to discard an object.max_avail_delaywhen to discard an unused object.max_using_delaywhen to warn about object kept for a long time.max_using_delay_killwhen to kill objects kept for a long time.log_levelset logging level, default None means no setting.openerfunction to call when creating an object, default None means no call.getterfunction to call when getting an object, default None means no call.retterfunction to call when returning an object, default None means no call.closerfunction to call when discarding an object, default None means no call.tracerobject debug helper, default None means less debug.
Objects are created on demand by calling fun when needed.
Example
Here is an example of a flask application with blueprints and a shared resource.
First, a shared module holds a proxy to a yet unknown object:
# file "Shared.py"
from ProxyPatternPool import Proxy
stuff = Proxy()
def init_app(stuff):
stuff.set_obj(stuff)
This shared object is used by module with a blueprint:
# file "SubStuff.py"
from Flask import Blueprint
from Shared import stuff
sub = Blueprint(…)
@sub.get("/stuff")
def get_stuff():
return str(stuff), 200
Then the application itself can load and initialize both modules in any order without risk of having some unitialized stuff imported:
# file "App.py"
from flask import Flask
app = Flask("stuff")
from SubStuff import sub
app.register_blueprint(sub, url_prefix="/sub")
import Shared
Shared.init_app("hello world!")
Notes
This module is somehow rhetorical: because of the GIL Python is quite bad as a parallel language, so the point of creating threads which will mostly not really run in parallel is moot, thus the point of having a clever pool of stuff to be shared by these thread is even mooter!
Shared object must be returned to the pool to avoid depleting resources. This may require some active cooperation from the infrastructure which may or may not be reliable. Consider monitoring your resources to detect unexpected status, eg database connections remaining idle in transaction and the like.
See Also:
- Psycopg Pool for pooling Postgres database connexions.
- Eventlet db_pool for pooling MySQL or Postgres database connexions.
- Discussion about database pool sizing.
License
This code is Public Domain.
Versions
Sources, documentation and issues are hosted on GitHub. Install package from PyPI.
8.0 on 2024-02-20
Add opener, getter, retter and closer pool hooks.
7.4 on 2024-02-17
Fix log_level handling.
7.3 on 2024-02-17
Add tracer parameter to help debugging on pool objects.
7.2 on 2024-02-17
Add log_level parameter.
Add pyright (non yet working) check.
7.1 on 2024-02-17
On second thought, allow both warning and killing long running objects.
7.0 on 2024-02-17
Kill long running objects instead of just warning about them.
6.1 on 2023-11-19
Add Python 3.12 tests.
6.0 on 2023-07-17
Add support for more local scopes: WERKZEUG, EVENTLET, GEVENT.
5.0 on 2023-06-16
Use pyproject.toml only.
Require Python 3.10 for simpler code.
4.0 on 2023-02-05
Add max_using_delay for warnings.
Add with support to both Pool and Proxy classes.
Add module-specific exceptions: PoolException, ProxyException.
3.0 on 2022-12-27
Wait for available objects when max_size is reached.
Add min_size parameter to Proxy.
2.1 on 2022-12-27
Ensure that pool always hold min_size objects.
2.0 on 2022-12-26
Add min size and max delay feature to Pool.
1.1 on 2022-11-12
Minor fixes for mypy.
Test with Python 3.12.
Improved documentation.
1.0 on 2022-10-29
Add some documentation.
0.1 on 2022-10-28
Initial release with code extracted from FlaskSimpleAuth.
TODO
- add a method to delete the proxy?
- add an actual timeout feature?
- how to manage a return automatically?
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ProxyPatternPool-8.0.tar.gz.
File metadata
- Download URL: ProxyPatternPool-8.0.tar.gz
- Upload date:
- Size: 13.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.12.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ef0eef8659e6476a1eb633ab6a6554d9179e7d7da7750646156b1fc9d6715143
|
|
| MD5 |
d99b866909eeb3ff5029d35c0917c039
|
|
| BLAKE2b-256 |
7d161e98114bfdcf35a43f1aae097d8394f17dca3c4c360203cebc6fd025d9c5
|
File details
Details for the file ProxyPatternPool-8.0-py3-none-any.whl.
File metadata
- Download URL: ProxyPatternPool-8.0-py3-none-any.whl
- Upload date:
- Size: 10.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.12.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0e0ed48176b916f71c9368ba5e320f4b1c2513f3437dbe70501ecc645d19734c
|
|
| MD5 |
fc53eaead84b19fee7e2bc5f69cd1aeb
|
|
| BLAKE2b-256 |
6a48cdd6f37d887cfb169f65ec07d6f887a24b1f136b8e29eb6dfbefb517b639
|