如何在Google App Engine中包含第三方Python库?

How to include third party Python libraries in Google App Engine?

如何在Google App Engine中添加Google不提供的第三方python库? 我正在尝试在Google App Engine中使用BeautifulSoup,但无法这样做。 但是我的问题是我想在Google App Engine中使用的任何库。


Google为您的GAE项目中包含的第三方库提供了一种有据可查的方法。

请参阅Python 2.7文档中库的"向应用程序添加第三方程序包"部分。

If you want to include additional pure-python third-party packages, you can do so by setting up vendoring. Vendoring allows you to install packages to a subdirectory of your project and include them in your code. To use vendoring, create (or modify) appengine_config.py in the root of your project.

1
2
3
from google.appengine.ext import vendor
# Add any libraries installed in the"lib" folder.
vendor.add('lib')

然后只需将所有库的源代码放在lib目录中

1
> pip install beautifulsoup4 -t lib

因此,您的项目目录结构如下所示:

1
2
3
4
project
- lib
  - bs4
- your_code.py

这将允许您项目的源文件导入libs的程序包/模块,就像将它们添加到PYTHON_PATH中一样。例如:

1
2
3
# file: your_code.py
import bs4  # no need for 'from lib import bs4'
# do stuff with bs4...

通过执行以下命令,您还可以轻松地从requirements.txt文件安装所有内容

1
> pip install -t lib -r requirements.txt


实际上,我认为这个答案更适合这里。

如果要使用此列表中未包含的第三方库,则必须手动添加它们。

为了手动包括任何其他库,您必须将它们放在app.yaml所在的目录中。因此,例如,如果您具有以下结构:

1
2
3
4
5
hello
├── libs
│   └── bs4
├── hello.py
└── app.yaml

然后在hello.py中,必须将这两行放在文件的开头:

1
2
import sys
sys.path.insert(0, 'libs')

完成此操作后,您将能够使用要放入该libs目录中的任何第三方库。

例如:

1
from bs4 import BeautifulSoup


您只需将包含要使用的库的文件夹复制到App Engine项目中。

然后,在部署时,它会随您的应用程序一起上载并可供使用。

编辑:杰西的答案是我现在如何做到这一点。那就这样吧!


它在这里的工作方式是:

1
2
3
import sys
# sys.path.insert(0, 'libs') #"Old" way, not working for me.
sys.path.append(os.path.join(os.path.dirname(__file__),"libs")) # This works!

然后正常导入:

1
from bs4 import BeautifulSoup

pip install -t lib软件包名称

lib:第三方库的位置

然后,您可以像在ipython或terminal中使用的普通库一样使用此软件包。


只需将Beautifulsoup放在项目的根目录中,然后全部上传