Skip to content

Commit 90ae8f5

Browse files
committed
serve up env.js based on environment for frontend applications
1 parent 55b43cc commit 90ae8f5

File tree

3 files changed

+43
-4
lines changed

3 files changed

+43
-4
lines changed

src/pyff/constants.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ class Config(object):
253253
version = DummySetting('version', info="Show pyff version information", short='v', typeconv=as_bool)
254254
module = DummySetting("module", info="load additional plugins from the specified module", short='m')
255255
alias = DummySetting('alias', info="add an alias to the server - argument must be on the form alias=uri", short='A')
256+
env = DummySetting('env', info='add an environment variable to the server', short='E')
256257

257258
# deprecated settings
258259
google_api_key = S("google_api_key", deprecated=True)
@@ -313,6 +314,15 @@ class Config(object):
313314
info="a set of aliases to add to the server",
314315
)
315316

317+
environ = S(
318+
"environ",
319+
default=dict(),
320+
typeconv=as_dict_of_string,
321+
cmdline=['pyffd'],
322+
hidden=True,
323+
info="a set of environement variables to add to the server",
324+
)
325+
316326
base_dir = S("base_dir", info="change to this directory before executing the pipeline")
317327

318328
modules = S("modules", default=[], typeconv=as_list_of_string, hidden=True, info="modules providing plugins")
@@ -513,6 +523,14 @@ def help(prg):
513523
config = Config()
514524

515525

526+
def opt_eq_split(s: str) -> str:
527+
for sep in [':', '=']:
528+
d = tuple(s.rsplit(sep))
529+
if len(d) == 2:
530+
return d
531+
return (None, None)
532+
533+
516534
def parse_options(program, docs):
517535
(short_args, long_args) = config.args(program)
518536
docs += config.help(program)
@@ -529,6 +547,9 @@ def parse_options(program, docs):
529547
if config.aliases is None or len(config.aliases) == 0:
530548
config.aliases = dict(metadata=entities)
531549

550+
if config.environ is None or len(config.environ) == 0:
551+
config.environ = dict()
552+
532553
if config.modules is None:
533554
config.modules = []
534555

@@ -545,6 +566,10 @@ def parse_options(program, docs):
545566
assert colon == ':'
546567
if a and uri:
547568
config.aliases[a] = uri
569+
elif o in ('-E', '--env'):
570+
(k, v) = opt_eq_split(a)
571+
if k and v:
572+
config.environ[k] = v
548573
elif o in ('-m', '--module'):
549574
config.modules.append(a)
550575
else:

src/pyff/mdq.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ def main():
5151
'workers': config.worker_pool_size,
5252
'loglevel': config.loglevel,
5353
'preload_app': True,
54+
'env': config.environ,
5455
'daemon': config.daemonize,
5556
'capture_output': False,
5657
'timeout': config.worker_timeout,

src/pyff/utils.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@
2828
from threading import local
2929
from time import gmtime, strftime
3030
from typing import Any, BinaryIO, Callable, Dict, List, Optional, Sequence, Set, Tuple, Union
31-
31+
from pyramid.request import Request as PyramidRequest
32+
from pyramid.response import Response as PyramidResponse
3233
import pkg_resources
3334
import requests
3435
import xmlsec
@@ -994,10 +995,13 @@ class FrontendApp(BaseModel):
994995
directory: str
995996
dirs: List[str] = []
996997
exts: Set[str] = set()
998+
env: Dict[str, str] = dict()
997999

9981000
@staticmethod
999-
def load(url_path: str, name: str, directory: str) -> FrontendApp:
1000-
fa = FrontendApp(url_path=url_path, name=name, directory=directory)
1001+
def load(url_path: str, name: str, directory: str, env: Optional[Mapping[str, str]] = None) -> FrontendApp:
1002+
if env is None:
1003+
env = config.environ
1004+
fa = FrontendApp(url_path=url_path, name=name, directory=directory, env=env)
10011005
with os.scandir(fa.directory) as it:
10021006
for entry in it:
10031007
if not entry.name.startswith('.'):
@@ -1008,8 +1012,17 @@ def load(url_path: str, name: str, directory: str) -> FrontendApp:
10081012
fa.exts.add(ext)
10091013
return fa
10101014

1015+
def env_js_handler(self, request: PyramidRequest) -> PyramidResponse:
1016+
env_js = "window.env = {" + ",".join([f"{k}: '{v}'" for (k, v) in self.env.items()]) + "};"
1017+
response = PyramidResponse(env_js)
1018+
response.headers['Content-Type'] = 'text/javascript'
1019+
return response
1020+
10111021
def add_route(self, ctx):
1012-
for uri_part in [self.url_path] + [self.url_path + d + "/" for d in self.dirs]:
1022+
env_route = '{}_env_js'.format(self.name)
1023+
ctx.add_route(env_route, '/env.js', request_method='GET')
1024+
ctx.add_view(self.env_js_handler, route_name=env_route)
1025+
for uri_part in [self.url_path] + [self.url_path + d for d in self.dirs]:
10131026
route = '{}_{}'.format(self.name, uri_part)
10141027
path = '{:s}{{sep:/?}}{{path:.*}}'.format(uri_part)
10151028
ctx.add_route(

0 commit comments

Comments
 (0)