2010-03-02 79 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