Skip to content

Commit f5583bd

Browse files
author
Joel Collins
committed
Easy function to get URL of static files
1 parent 4488ee0 commit f5583bd

File tree

1 file changed

+23
-13
lines changed

1 file changed

+23
-13
lines changed

labthings/server/extensions.py

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22
import traceback
3+
from flask import url_for
34

45
from importlib import util
56
import sys
@@ -52,18 +53,16 @@ def __init__(
5253

5354
self.methods = {}
5455

55-
if static_folder:
56-
print(f"Adding route for {static_folder}")
57-
self.static_view_class = static_from(static_folder)
58-
self.add_view(self.static_view_class, f"{static_url_path}/<path:path>")
59-
else:
60-
self.static_view_class = None
56+
self.static_view_class = static_from(static_folder)
57+
self.add_view(
58+
self.static_view_class, f"{static_url_path}/<path:path>", view_id="static",
59+
)
6160

6261
@property
6362
def views(self):
6463
return self._views
6564

66-
def add_view(self, view_class, rule, **kwargs):
65+
def add_view(self, view_class, rule, view_id=None, **kwargs):
6766
# Remove all leading slashes from view route
6867
cleaned_rule = rule
6968
while cleaned_rule[0] == "/":
@@ -72,12 +71,13 @@ def add_view(self, view_class, rule, **kwargs):
7271
# Expand the rule to include extension name
7372
full_rule = "/{}/{}".format(self._name_uri_safe, cleaned_rule)
7473

75-
view_id = (
76-
cleaned_rule.replace("/", "_")
77-
.replace("<", "")
78-
.replace(">", "")
79-
.replace(":", "_")
80-
)
74+
if not view_id:
75+
view_id = (
76+
cleaned_rule.replace("/", "_")
77+
.replace("<", "")
78+
.replace(">", "")
79+
.replace(":", "_")
80+
)
8181

8282
# Store route information in a dictionary
8383
d = {"rule": full_rule, "view": view_class, "kwargs": kwargs}
@@ -145,6 +145,16 @@ def add_method(self, method, method_name):
145145
"Unable to bind method to extension. Method name already exists."
146146
)
147147

148+
def static_file_url(self, filename: str):
149+
static_repr = self.views.get("static")
150+
static_view = static_repr.get("view")
151+
static_endpoint = getattr(static_view, "endpoint", None)
152+
153+
if not static_endpoint:
154+
return None
155+
156+
return url_for(static_endpoint, path=filename, _external=True)
157+
148158

149159
def find_instances_in_module(module, class_to_find):
150160
"""Find instances of a particular class within a module

0 commit comments

Comments
 (0)