如何在 Serverless v1.0 中导入 Python 依赖 [英] How to import Python dependencies in Serverless v1.0

查看:50
本文介绍了如何在 Serverless v1.0 中导入 Python 依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

语言:Python框架:无服务器 v1.0

Language: Python Framework: Serverless v1.0

通常我会运行 pip freeze >项目根目录下的requirements.txt

如何将这些依赖项打包到每个部署中?

How can I get these dependencies packaged into every deploy?

推荐答案

  1. 创建requirements.txt

pip freeze > requirements.txt

pip freeze > requirements.txt

创建一个包含所有依赖项的文件夹:

create a folder with all the dependencies:

pip install -t vendored -r requirements.txt

pip install -t vendored -r requirements.txt

请注意,为了在代码中使用这些依赖项,您需要添加以下内容:

Note that in order to use these dependencies in the code you'll need to add the following:

import os
import sys
here = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(here, "./vendored")) 

另一个例子见https://stackoverflow.com/a/36944792/1111215.

更新:您现在可以使用 serverless-python-requirements 插件:

UPDATE: Instead of the bullet (2) and the code above, you can now use the serverless-python-requirements plugin:

安装插件

npm install --save serverless-python-requirements

并将插件添加到您的 serverless.yml

plugins:
  - serverless-python-requirements

不要忘记确保您有一个 requirements.txt 文件.

Don't forget to make sure you have a requirements.txt file.

就是这样,一旦 sls deploy 被调用,插件就会将依赖项与代码一起打包.

That's it, once sls deploy is called the plugin will package the dependencies with the code.

有关完整示例,请查看serverless-python-sample.

For a full sample take a look at the serverless-python-sample.

这篇关于如何在 Serverless v1.0 中导入 Python 依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆