小能豆

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

python

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.


阅读 74

收藏
2023-11-28

共1个答案

小能豆

It looks like there are issues with your project’s directory structure and how you’re trying to import modules. Here are some suggestions to resolve the problems:

  1. Update sys.path: Add the root directory of your project to sys.path in your scripts. You can do this in your main.py files.

```
# src/main.py
import sys
sys.path.append(‘/path/to/your/python-functions’)
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)
```

python # src/api/main.py def status(req: https_fn.Request): return https_fn.Response("Hello", status=200)

  1. Use Relative Imports: In your src/api/main.py, use relative imports instead of absolute imports.

```python
# src/api/main.py
from .. import https_fn

def status(req: https_fn.Request):
return https_fn.Response(“Hello”, status=200)
```

  1. Ensure Correct Module Names: Make sure that the module names in your imports match the actual file names and folder structure. Ensure there are no typos.

  2. Check Working Directory: Ensure that the working directory when running your script is set to the root of your project.

python cd /path/to/your/python-functions python src/main.py

  1. Firebase Configuration: The Firebase error you are encountering might be a separate issue. Ensure that your Firebase configuration files are correctly set up and that your functions.yaml specifies a version number.

By addressing these points, you should be able to resolve the import issues and deploy your functions successfully.

2023-11-28