Google App Engine Python - 在不同模块中使用相同的基本处理程序

时间:2014-10-27 18:56:43

标签: python google-app-engine import module gae-module

我正在将python App Engine应用程序转换为使用本文所述的模块https://cloud.google.com/appengine/docs/python/modules/。我想在我的每个模块中使用自定义处理程序作为基类来添加一些常用功能。我是否需要在每个模块中重复我的自定义处理程序代码,或者有没有办法导入该类?

例如,我希望我的架构看起来像这样:

MyProject
├── common
│   ├── my_handler.py
├── module1
│   │   ├── module1.yaml
│   │   ├── main.py
├── module2
│   │   ├── module2.yaml
│   │   ├── main.py

/common/my_handler.py不是应用引擎模块的一部分,如下所示:

import webapp2
class BaseHandler(webapp2.RequestHandler):
    """
        BaseHandler for all requests
    """
    pass  

然后在/module1/main.py文件中,我想做类似的事情:

import webapp2

from common.my_handler import BaseHandler

class module1Handler(BaseHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('Hello, this is module 1!')

app = webapp2.WSGIApplication(
    [('/', module1Handler),
    ],
    debug=True)

这不起作用,服务器抛出错误,因为它找不到common.my_handler.py:

ImportError: No module named common.my_handler 

模块似乎是沙箱。是否可以从/module1/main.py中导入/common/my_handler.py?

1 个答案:

答案 0 :(得分:2)

您可以尝试here,例如:

from ..common import BaseHandler

或将路径添加到全局路径:

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import common.my_handler as BaseHandler