summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTheron Luhn <theron@luhn.com>2025-08-24 16:28:04 -0700
committerTheron Luhn <theron@luhn.com>2025-08-24 16:32:02 -0700
commit97319b2d2239974b04cbef2b82d5405758095b7c (patch)
tree45d587527c4d4d4b61933a1be14b93677026fa35
parentd157158564cff627e73d2942a9b929ff041b98ef (diff)
downloadpyramid-97319b2d2239974b04cbef2b82d5405758095b7c.tar.gz
pyramid-97319b2d2239974b04cbef2b82d5405758095b7c.tar.bz2
pyramid-97319b2d2239974b04cbef2b82d5405758095b7c.zip
Implement our own version of `resource_filename`.
-rw-r--r--src/pyramid/path.py28
-rw-r--r--tests/test_path.py14
2 files changed, 42 insertions, 0 deletions
diff --git a/src/pyramid/path.py b/src/pyramid/path.py
index d4909d412..5138344c7 100644
--- a/src/pyramid/path.py
+++ b/src/pyramid/path.py
@@ -1,4 +1,8 @@
+import atexit
+from contextlib import ExitStack
+import functools
from importlib.machinery import SOURCE_SUFFIXES
+import importlib.resources
import os
import pkg_resources
import sys
@@ -9,6 +13,30 @@ from pyramid.interfaces import IAssetDescriptor
init_names = ['__init__%s' % x for x in SOURCE_SUFFIXES]
+@functools.lru_cache(maxsize=None)
+def resource_filename(package, name):
+ """
+ Return a filename on the filesystem for the given resource. If the
+ resource does not exist in the filesystem (e.g. in a zipped egg), it will
+ be extracted to a temporary directory and cleaned up when the application
+ exits.
+
+ This function is equivalent to the now-deprecated
+ ``pkg_resources.resource_filename``.
+
+ This function is only included in order to provide legacy functionality;
+ use should be avoided. Instead prefer to use ``importlib.resource`` APIs
+ directly.
+
+ """
+ ref = importlib.resources.files(package) / name
+
+ manager = ExitStack()
+ atexit.register(manager.close)
+ path = manager.enter_context(importlib.resources.as_file(ref))
+ return str(path)
+
+
def caller_path(path, level=2):
if not os.path.isabs(path):
module = caller_module(level + 1)
diff --git a/tests/test_path.py b/tests/test_path.py
index af3dfb500..968739af4 100644
--- a/tests/test_path.py
+++ b/tests/test_path.py
@@ -4,6 +4,20 @@ import unittest
here = os.path.abspath(os.path.dirname(__file__))
+class TestResourceFilename(unittest.TestCase):
+ def _callFUT(self, package, name):
+ from pyramid.path import resource_filename
+
+ return resource_filename(package, name)
+
+ def test_returns_path(self):
+ path = self._callFUT('tests', 'test_path.py')
+ self.assertIsInstance(path, str)
+ # If it's a real path, we should be able to open and read from it.
+ with open(path) as fh:
+ assert fh.read(1)
+
+
class TestCallerPath(unittest.TestCase):
def tearDown(self):
from . import test_path