refactor(__init__): reset context manager for flask app

with proper bdist setup, it shouldn't be necessary to wrap path
of importlib, since the context manager will handle egg extraction
itself. Hopefully...
This commit is contained in:
Tiara Rodney 2022-04-08 21:01:33 +02:00
parent a4116832e7
commit c8dffbbdf8
2 changed files with 2 additions and 27 deletions

View file

@ -144,6 +144,7 @@ from configparser import ConfigParser
from ast import literal_eval from ast import literal_eval
from io import StringIO from io import StringIO
from os import environ from os import environ
from importlib.resources import path as resource_path
from connexion import FlaskApp from connexion import FlaskApp
from connexion.resolver import RestyResolver from connexion.resolver import RestyResolver
@ -302,7 +303,7 @@ def get_flask_app(
options = {"swagger_ui": server_config.swagger_ui} options = {"swagger_ui": server_config.swagger_ui}
#context manager returns a pathlib.Path object #context manager returns a pathlib.Path object
with tmp_pkg_resource_text_path('httpaste.schema', 'httpaste.openapi.json') as path: with resource_path('httpaste.schema', 'httpaste.openapi.json') as path:
application = FlaskApp(__name__, specification_dir=path.parent) application = FlaskApp(__name__, specification_dir=path.parent)

View file

@ -1,7 +1,6 @@
from random import choice from random import choice
from base64 import b64decode from base64 import b64decode
from urllib.parse import urljoin from urllib.parse import urljoin
from importlib.resources import read_text
from tempfile import mkdtemp from tempfile import mkdtemp
from pathlib import Path from pathlib import Path
from contextlib import contextmanager from contextlib import contextmanager
@ -35,28 +34,3 @@ def decode(data: str, encoding: str) -> bytes:
def join_url(base:str, url: str) -> str: def join_url(base:str, url: str) -> str:
return urljoin(base, url, True) return urljoin(base, url, True)
@contextmanager
def tmp_pkg_resource_text_path(package:str, resource:str) -> Path:
"""context manager for accessing package resources from a real path
this applies to the circumstance of the package living inside of an
egg and therefore is unable to provide real existing paths to any
module that may require it.
:param package: dot seperated package name
:param resource: basename of resource inside package
:returns: a Path-like object
"""
data = read_text(package, resource)
tmp_dirname = mkdtemp()
tmp_dirpath = Path(tmp_dirname)
tmp_file = tmp_dirpath.joinpath(resource)
tmp_file.write_text(data)
try:
yield tmp_file
finally:
tmp_file.unlink()
tmp_dirpath.rmdir()