Search code examples
pythonfirebasegoogle-cloud-platformgoogle-cloud-functionsfirebase-tools

Modules inside firebase cloud functions with python: ModuleNotFoundError: No module named 'src'


I have a directory structure like this:

python-functions/
--src
---- | api/
-------- | __init__.py
-------- | main.py
---- | __init__.py
---- | main.py

I'm trying to define all my functions in src/main.py but have the implementations in its corresponding folder

# src/main.py
import src.api.main as api

@https_fn.on_request(timeout_sec=300)
def status(req: https_fn.Request) -> https_fn.Response:
    return api.status(req)
# src/api/main.py
def status(req: https_fn.Request):
    return https_fn.Response("Hello", status=200)

But when deploying I get this error:

# Importing like: import src
ModuleNotFoundError: No module named 'src'
127.0.0.1 - - [18/May/2023 00:09:43] "GET /\_\_/functions.yaml HTTP/1.1" 500 -
Error: Failed to parse build specification:

- FirebaseError Expect manifest yaml to specify a version number

or this one:

# importing like: from .api.main import main
ImportError: attempted relative import with no known parent package

127.0.0.1 - - [18/May/2023 00:28:19] "GET /__/functions.yaml HTTP/1.1" 500 -

Error: Failed to parse build specification:
- FirebaseError Expect manifest yaml to specify a version number

I've tried other ways of importing like but I still get the same errors.


Solution

  • I was able to solve this by following this comment on a github issue https://github.com/firebase/firebase-functions-python/issues/92#issuecomment-1549153623

    # Adding this to the top of main.py works as a workaround, but it's not ideal:
    
    import sys
    from pathlib import Path
    
    sys.path.insert(0, Path(__file__).parent.as_posix())
    
    from test import base