Python 循环引用问题:
我得到:
ImportError: cannot import name Image (from image_blob.py)
请帮助我,谢谢:
我的代码:
image.py:
from google.appengine.ext import db
from app.models.item import Item
class Image(Item):
# imports
from app.models.image_blob import ImageBlob
#from app.models.user import User
#from list_user import ListUser # is needed in order to have the references
# references
#uploaded_by_user = db.ReferenceProperty(User, required = True)
large_image = db.ReferenceProperty(ImageBlob, required = True)
small_image = db.ReferenceProperty(ImageBlob, required = True)
# image info
title = db.StringProperty(required = True)
description = db.StringProperty(required = False)
# metadata
# relations
image_blob:
from google.appengine.ext import db
class ImageBlob(db.Model):
from app.models.image import Image
data = db.BlobProperty(required = True)
image = db.ReferenceProperty(Image, required = True)
I get:
ImportError: cannot import name Image (from image_blob.py)
please help me thanks :s
my code:
image.py:
from google.appengine.ext import db
from app.models.item import Item
class Image(Item):
# imports
from app.models.image_blob import ImageBlob
#from app.models.user import User
#from list_user import ListUser # is needed in order to have the references
# references
#uploaded_by_user = db.ReferenceProperty(User, required = True)
large_image = db.ReferenceProperty(ImageBlob, required = True)
small_image = db.ReferenceProperty(ImageBlob, required = True)
# image info
title = db.StringProperty(required = True)
description = db.StringProperty(required = False)
# metadata
# relations
image_blob:
from google.appengine.ext import db
class ImageBlob(db.Model):
from app.models.image import Image
data = db.BlobProperty(required = True)
image = db.ReferenceProperty(Image, required = True)
您尝试在处理整个
image.py
之前从image_blob.py
导入。在发生from app.models.item import Item
时,class Image
尚未定义,因此还无法导入(整个类定义必须在符号被实际定义之前被处理)。有一个简单的解决方案:不要在
ImageBlob
上定义image
属性。 AppEngine 的模型自动为您定义一个向后引用,因此当您将ImageBlob
添加到Image
时,它会自动在ImageBlob
引用回引用它的Image
集合(在您当前的用例中,其大小应为 1)。You're trying to import from
image_blob.py
before the entirety ofimage.py
is processed. At the time which thefrom app.models.item import Item
occurs,class Image
hasn't yet been defined, and thus can't yet be imported (the entire class definition must have been processed before the symbol is actually defined).There's a simple solution to this: Don't define the
image
property onImageBlob
. AppEngine's models automatically define a backwards reference for you, so when you add theImageBlob
to theImage
, it'll automatically define a property on theImageBlob
which references back to the set ofImage
s which reference it (which, in your current use case, should be of size 1).