Skip to content

Commit 9046388

Browse files
authored
fix: Support relative imports for submodules (#169)
1 parent 6f4a360 commit 9046388

File tree

4 files changed

+37
-1
lines changed

4 files changed

+37
-1
lines changed

src/functions_framework/_function_registry.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ def load_function_module(source):
6262
directory, filename = os.path.split(realpath)
6363
name, extension = os.path.splitext(filename)
6464
# 2. Create a new module
65-
spec = importlib.util.spec_from_file_location(name, realpath)
65+
spec = importlib.util.spec_from_file_location(
66+
name, realpath, submodule_search_locations=[directory]
67+
)
6668
source_module = importlib.util.module_from_spec(spec)
6769
# 3. Add the directory of the source to sys.path to allow the function to
6870
# load modules relative to its location

tests/test_functions.py

+11
Original file line numberDiff line numberDiff line change
@@ -604,3 +604,14 @@ def tests_cloud_to_background_event_client_invalid_source(
604604
resp = background_event_client.post("/", headers=headers, json=tempfile_payload)
605605

606606
assert resp.status_code == 500
607+
608+
609+
def test_relative_imports():
610+
source = TEST_FUNCTIONS_DIR / "relative_imports" / "main.py"
611+
target = "function"
612+
613+
client = create_app(target, source).test_client()
614+
615+
resp = client.get("/")
616+
assert resp.status_code == 200
617+
assert resp.data == b"success"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Function used in test for relative imports."""
16+
17+
from .test import foo
18+
19+
20+
def function(request):
21+
"""Test HTTP function who returns a value from a relative import"""
22+
return foo
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
foo = "success"

0 commit comments

Comments
 (0)