无服务器Python本地模块未找到。

3
我想将本地的 Python 模块文件导入到我的服务端项目中的处理程序文件中,但是尽管这个本地文件与我的处理程序文件位于同一父目录中,它似乎无法识别该模块。我对 Python 服务端设置相对较新,想知道是否存在关于服务端文件导入工作的遗漏。
以下是这些文件:
/ (parent directory)
data.py
gather_keys_oauth2.py

错误信息:

Proxy Handler could not detect JSON:   File "/Users/user/.nvm/versions/node/v12.14.0/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/invoke.py", line 72, in <module>
    module = import_module(args.handler_path.replace('/', '.'))
  File "/Users/user/miniconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./data.py", line 4, in <module>
    import gather_keys_oauth2 as Oauth2
ModuleNotFoundError: No module named 'gather_keys_oauth2'

data.py:

import json
from datetime import timedelta, datetime
import math
import gather_keys_oauth2 as Oauth2
import fitbit

def auth(event, context):

    CLIENT_ID = '*client*'
    CLIENT_SECRET = '*secret*'

    server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
    server.browser_authorize()

    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])

    auth2_client = fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

    print(auth2_client)

    body = {
        "message": "Auth",
        "input": event
    }

    response = {
        "statusCode": 200,
        "body": body['message']
    }

    return response

你是在说你部署的 Lambda 函数无法识别模块,还是在你的 IDE 中看到了错误? - AnonymousAlias
我遇到了同样的问题,你能解决吗? - cs4r
我遇到了同样的问题。你找到问题了吗?@cs4r - Arch Desai
@ArchDesai 是的,我已经发布了对我有用的解决方案。请看下面。 - cs4r
2个回答

1
data.py 中以以下方式导入模块 gather_keys_oauth2:
import .gather_keys_oauth2 as Oauth2

请注意模块名前的点号(.)。

-1

您的 Lambda 没有打包您想要导入的模块。您可以使用 serverless-python-requirements 插件来解决此问题。

它可以在本地安装,也可以在管道上安装。

sls plugin install -n serverless-python-requirements 

你可以将这段代码添加到你的serverless.yml文件中,然后尝试部署。
# this part might not be needed depending on size of utils
custom:
  pythonRequirements:
    zip: true

# This plugin allows us import dependencies
plugins:
  - serverless-python-requirements

请查看此插件的指南

https://www.serverless.com/blog/serverless-python-packaging

https://www.npmjs.com/package/serverless-python-requirements(URL更新) 您可以使用


不幸的是,这个不起作用。 - cs4r

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接