【问题标题】:Google App Engine Python - Using same base handler in different modulesGoogle App Engine Python - 在不同模块中使用相同的基本处理程序
【发布时间】:2014-10-27 18:56:42
【问题描述】:

我正在转换 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?

【问题讨论】:

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


    【解决方案1】:

    您可以尝试here,例如:

    from ..common import BaseHandler

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多