Skip to content

Commit

Permalink
Forgot to format these files (#294)
Browse files Browse the repository at this point in the history
  • Loading branch information
aviraljain99 committed Jun 17, 2022
1 parent 71faff3 commit 7d6dcfb
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 58 deletions.
75 changes: 39 additions & 36 deletions elpis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import psutil
from werkzeug.serving import is_running_from_reloader


def create_app(test_config=None):
# Called by the flask run command in the cli.
GUI_BUILD_DIR = "/elpis/elpis/gui/build"
Expand All @@ -21,22 +22,20 @@ def create_app(test_config=None):
# Variable to control the use of a proxy to support webpackdevserver
WEBPACK_DEV_SERVER_PROXY = os.environ.get("WEBPACK_DEV_SERVER_PROXY", None)

log = logging.getLogger('werkzeug')
log = logging.getLogger("werkzeug")
log.setLevel(logging.DEBUG)
# Prevent the HTTP request logs polluting more important train logs
log.disabled = True

if WEBPACK_DEV_SERVER_PROXY:
app = Flask(__name__,
instance_relative_config=True,
static_folder=GUI_PUBLIC_DIR)
app = Flask(__name__, instance_relative_config=True, static_folder=GUI_PUBLIC_DIR)
else:
# Setup static resources
# create and configure the app
# auto detect for yarn watch or yarn build
static_dir_watch = '/js'
static_dir_build = '/static'
if 'js' in os.listdir(GUI_BUILD_DIR):
static_dir_watch = "/js"
static_dir_build = "/static"
if "js" in os.listdir(GUI_BUILD_DIR):
# using yarn watch
static_dir = static_dir_watch
else:
Expand All @@ -46,35 +45,35 @@ def create_app(test_config=None):
# static_dir = static_dir_build
# else:
# static_dir = static_dir_watch
logger.info(f'using static_dir: {static_dir}')
logger.info(f"using static_dir: {static_dir}")
# Create a custom Flask instance defined in the app.py file. Same as a
# normal Flask class but with a specialised blueprint function.
app = Flask(__name__,
instance_relative_config=True,
static_folder=GUI_BUILD_DIR + static_dir,
static_url_path=static_dir)
app = Flask(
__name__,
instance_relative_config=True,
static_folder=GUI_BUILD_DIR + static_dir,
static_url_path=static_dir,
)

# When making this multi-user, the secret key would require to be a secure hash.
app.config.from_mapping(
SECRET_KEY='dev'
)
app.config.from_mapping(SECRET_KEY="dev")

elpis_path = Path(os.getcwd())
app.config['ELPIS_PATH'] = elpis_path
app.config["ELPIS_PATH"] = elpis_path

# For a single user, storing the interface object is okay to do in
# the app.config, however, this would need to change for multi-user.
# Each user would require a unique Interface. One Interface
# stores all the artifacts that user has generated.
interface_path = Path(os.path.join(elpis_path, '/state/of_origin'))
interface_path = Path(os.path.join(elpis_path, "/state/of_origin"))
if not interface_path.exists():
app.config['INTERFACE'] = Interface(interface_path)
app.config["INTERFACE"] = Interface(interface_path)
else:
app.config['INTERFACE'] = Interface(interface_path, use_existing=True)
app.config["INTERFACE"] = Interface(interface_path, use_existing=True)

# Developer-friendly mode has convenient interface widgets for setting engine etc
load_dotenv()
app.config['DEV_MODE'] = os.environ.get('DEV_MODE')
app.config["DEV_MODE"] = os.environ.get("DEV_MODE")

# add the endpoints routes
app.register_blueprint(endpoints.bp)
Expand All @@ -84,47 +83,51 @@ def create_app(test_config=None):
# Start Tensorboard if not already running (because Flask init happens twice)
tensorboard_running = False
for proc in psutil.process_iter():
for conns in proc.connections(kind='inet'):
for conns in proc.connections(kind="inet"):
if conns.laddr.port == 6006:
tensorboard_running = True
print('Tensorboard is running on', proc.pid)
print("Tensorboard is running on", proc.pid)
if not tensorboard_running:
print('Tensorboard is not running, start it')
print("Tensorboard is not running, start it")
tensorboard = program.TensorBoard()
tensorboard.configure(argv=['tensorboard',
'--logdir=/state/of_origin/models',
'--port=6006',
'--host=0.0.0.0'])
tensorboard.configure(
argv=[
"tensorboard",
"--logdir=/state/of_origin/models",
"--port=6006",
"--host=0.0.0.0",
]
)
url = tensorboard.launch()
print(f"Tensorflow listening on {url}")

# the rest of the routes below are for the single file react app.
@app.route('/index.html')
@app.route("/index.html")
def index_file():
"""Redirects to '/' for React."""
return redirect('/')
return redirect("/")

@app.route('/', defaults={'path': ''})
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def index(path):
logger.info(f'in index with: {path}')
if (WEBPACK_DEV_SERVER_PROXY):
# If we are running the webpack dev server,
logger.info(f"in index with: {path}")
if WEBPACK_DEV_SERVER_PROXY:
# If we are running the webpack dev server,
# We proxy webpack requests through to the dev server
return proxy('http://localhost:3000/', path)
return proxy("http://localhost:3000/", path)
else:
with open(f"{GUI_BUILD_DIR}/index.html", "r") as fin:
content = fin.read()
return content

@app.route('/favicon.ico')
@app.route("/favicon.ico")
def favicon():
with open(f"{GUI_PUBLIC_DIR}/favicon.ico", "rb") as fin:
return fin.read()

return app


# Proxy Wrapper
def proxy(host, path):
response = get(f"{host}{path}")
Expand Down
7 changes: 2 additions & 5 deletions elpis/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

class Flask(FlaskBase):
"""Custom app to allow multi-level blueprints."""

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

Expand All @@ -20,7 +20,4 @@ def register_blueprint(self, blueprint, **options):
# Deal with custom Blueprint objects
blueprint.app = self
blueprint.prepare_routes()
blueprint.register_app(
lambda bp: super(Flask, self).register_blueprint(bp),
self
)
blueprint.register_app(lambda bp: super(Flask, self).register_blueprint(bp), self)
39 changes: 22 additions & 17 deletions elpis/blueprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,17 @@ class BlueprintSetupState(FlaskBlueprintSetupState):
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
if self.url_prefix is not None:
if rule:
rule = f'{self.blueprint.get_full_url_prefix()}{rule}'
rule = f"{self.blueprint.get_full_url_prefix()}{rule}"
else:
rule = self.url_prefix
options.setdefault('subdomain', self.subdomain)
options.setdefault("subdomain", self.subdomain)
if endpoint is None:
endpoint = _endpoint_from_view_func(view_func)
else:
endpoint = f'{self.blueprint.get_full_endpoint()}.{endpoint}'
endpoint = f"{self.blueprint.get_full_endpoint()}.{endpoint}"
defaults = self.url_defaults
if 'defaults' in options:
defaults = dict(defaults, **options.pop('defaults'))
if "defaults" in options:
defaults = dict(defaults, **options.pop("defaults"))
self.app.add_url_rule(rule, endpoint, view_func, defaults=defaults, **options)


Expand All @@ -66,7 +66,7 @@ def register_blueprint(self, blueprint):
appended to their paths and endpoints.
"""
# Setting the parent of a blueprint makes that a child (non-base/root)
# blueprint.
# blueprint.
blueprint.parent = self
self.blueprints.append(blueprint)

Expand All @@ -92,8 +92,9 @@ def register(self, app, options, first_registration=False):

if self.has_static_folder:
state.add_url_rule(
self.static_url_path + '/<path:filename>',
view_func=self.send_static_file, endpoint='static'
self.static_url_path + "/<path:filename>",
view_func=self.send_static_file,
endpoint="static",
)

for deferred in self.deferred_functions:
Expand Down Expand Up @@ -136,17 +137,17 @@ def get_full_endpoint(self) -> str:
# Normally having a dot('.') in the name is naughty and isn't
# allowed because they can be accessed like attributes, but
# for this modularity we are breaking this rule.
return f'{self.parent.get_full_endpoint()}.{self.name}'
return f"{self.parent.get_full_endpoint()}.{self.name}"
else:
return self.name

def get_full_url_prefix(self) -> str:
"""
Recursively build the URL prefix for this blueprint.
"""
url_prefix = '' if self.url_prefix is None else self.url_prefix
url_prefix = "" if self.url_prefix is None else self.url_prefix
if self.parent:
return f'{self.parent.get_full_url_prefix()}{url_prefix}'
return f"{self.parent.get_full_url_prefix()}{url_prefix}"
else:
return url_prefix

Expand All @@ -159,16 +160,20 @@ def prepare_routes(self):

def export(new_rule, end_point, view_function, route_options):
if self.is_base_blueprint():
if view_function and hasattr(view_function, '__name__'):
assert '.' not in view_function.__name__, "Blueprint view function name should not contain dots"
self.record(lambda s:
s.add_url_rule(new_rule, end_point, view_function, **route_options))
if view_function and hasattr(view_function, "__name__"):
assert (
"." not in view_function.__name__
), "Blueprint view function name should not contain dots"
self.record(
lambda s: s.add_url_rule(new_rule, end_point, view_function, **route_options)
)
else:
# Remove the ability to access the vie_function like a an
# attribute because we want a dot('.') in the endpoint name
# for syntax sugar.
self.record(lambda s:
s.add_url_rule(new_rule, end_point, view_function, **route_options))
self.record(
lambda s: s.add_url_rule(new_rule, end_point, view_function, **route_options)
)

# prepare child routes now
for blueprint in self.blueprints:
Expand Down

0 comments on commit 7d6dcfb

Please sign in to comment.