星期四, 10月 06, 2016

Google App Engine 使用 requests 時遇到 "no module named requests" 錯誤

開發 Google App Engine 應用,使用 requests 來發 RESTFul API 時,遇到了 "no module named requests" 錯誤。網路上一堆文章都是教你如何利用 pip 或 easy_install 來安裝 requests 模組。但是我還是持續看到同樣的錯誤訊息。

後來看到這篇 Stackoverflow 的回文指出:

Adding Third Party Python Libraries

You can include third party Python libraries with your application by putting the code in your application directory. If you make a symbolic link to a module's directory in your application directory, appcfg.py will follow the link and include the module in your app.

The Python module include path includes your application's root directory (the directory containing the app.yaml file). Modules you create in your application's root directory are available using a path from the root. Don't forget to create__init__.py files in sub-directories, so Python will recognize the sub-directories as packages.

大致上是說任何第三方模組,都必須放在應用的根目錄(跟 app.yaml 相同目錄)裡,但這樣一來,整個目錄就都是第三方模組的檔案夾,會非常雜亂。所以這時候可以參考 GAE 文件的建議
  1. 建立一個資料夾「lib」,把第三方模組都放在這裡面。
  2. 新增一個檔案 appengine_config.py,裡頭寫入:
from google.appengine.ext import vendor
# Add any libraries installed in the "lib" folder.
vendor.add('lib')

這樣子就能夠把 requests 這個模組放到這個資料夾裡。如果懶得新增模組,也可以建立一個 symbolic link 指向 python 的 package 目錄就可以了。