如何解决Flask中定义类的NameError
我正在做一个Flask项目,需要添加一个分页类来加载结果。我最终使用了一个预定义的方法,具体内容可以在这里找到,但当我尝试加载图片索引时遇到了NameError错误。
NameError: global name 'Pagination' is not defined
我知道这一定是我忽略了什么简单的东西,比如我在哪里声明了分页对象,但如果有人能给我一些建议,我会很感激。刚接触Python确实有些困难。
这是core.py中路由调用的代码(包括第6行的NameError错误调用)
#This import call initalizes Pagination as part of forms. There are other calls that
#are not pertinent
from kremlin import app, db, dbmodel, forms, imgutils, uploaded_images
#The route call for the images page
@app.route('/images', defaults={'page': 1})
@app.route('/images/page/<int:page>')
def entries_index(page):
""" Show an index of image thumbnails """
posts = dbmodel.Post.query.all()
pagination = Pagination(page, 20, posts) #This is where the error occurs
return render_template('board.html', form=forms.NewPostForm(),
posts=posts, pagination=pagination)
还有扩展自forms.py的分页对象
class Pagination(object):
def __init__(self, page, per_page, total_count):
self.page = page
self.per_page = per_page
self.total_count = total_count
@property
def pages(self):
return int(ceil(self.total_count / float(self.per_page)))
@property
def has_prev(self):
return self.page > 1
@property
def has_next(self):
return self.page < self.pages
def iter_pages(self, left_edge=2, left_current=2, right_current=5, right_edge=2):
last = 0;
for num in xrange(1, self.pages + 1):
if num <= left_edge or \
(num > self.page - left_current - 1 and \
num < self.page + right_current) or \
num > self.pages - right_edge:
if last + 1 != num:
yield None
yield num
last = num
我把完整的源代码放在这里:https://github.com/glasnost/kremlin/tree/pagination
1 个回答
1
NameError的意思是你使用的名字在当前的命名空间中不存在。这个名字是在forms.py文件中定义的。所以,你要么需要使用一个完整的名字,要么把这个名字导入到当前的命名空间中。
正如Sean提到的,要使用完整的名字,这段代码:
pagination = Pagination(page, 20, posts)
应该改成:
pagination = forms.Pagination(page, 20, posts)
或者,为了让那一行代码正常工作,你应该像这样把名字导入到当前的命名空间:
from kremlin import app, db, dbmodel, forms, imgutils, uploaded_images
from kremlin.forms import Pagination