2010-03-02 44 views
0

我無法創建可從所有類中訪問的全局函數。我在user.py中收到一條錯誤消息:__init__.py中的全局函數無法使用Pylons + Python訪問

NameError: global name 'connectCentral' is not defined 

這是我當前的代碼。

項目/模型/ __初始化__.py:

"""The application's model objects""" 
    import sqlalchemy as sa 
    from sqlalchemy import orm 
    from sqlalchemy import engine_from_config 

    from pylons import config 
    import central 

    #Establish an on-demand connection to the central database 
    def connectCentral(): 
     engine = engine_from_config(config, 'sqlalchemy.central.') 
     central.engine = engine 
     central.Session.configure(bind=engine) 

項目/模型/ user.py

import project.model 

    class User(object): 
     def emailExists(self): 
      try: 
       connectCentral() 
       emails = central.Session.query(User).filter_by(email=self.email).count() 
      if (emails > 0): 
       return False 
      else: 
       return True 

     except NameError: 
      self.errors['email'] = 'E-Mail not set' 
      return False 

我缺少一個導入?有一個更好的方法嗎?

謝謝。

回答

2

您需要用模塊(或包)來限定名稱它在,所以:

 try: 
      project.model.connectCentral() 

+0

當我這樣做,我得到: NameError:名字「項目」是未定義 – ensnare 2010-03-02 04:28:18

+0

奇怪的是,您在開始時使用的'import project.model'應該定義它。嘗試'將project.model導入爲prom',然後使用'prom.connectCentral()' - 然後說什麼? – 2010-03-02 05:22:32

+0

奇怪...從project.model導入*工程,但導入project.model爲proj產生AttributeError:'模塊'對象沒有屬性'模型' – ensnare 2010-03-02 05:58:32

相關問題